MCP/Server.pm

filter: Statementstmt 98.4% 261 / 265 Branchbran 92.4% 98 / 106 Conditioncond 64.2% 27 / 42 MC/DCmcdc 37.5% 9 / 24 Subroutinesub 96.4% 54 / 56 Podpod 100% 8 / 8 totaltotal 91.2% 457 / 501 CC 83 SCAR 15.7
CC
83
Cov
93%
_dispatch
13.0
_handle_discover
7.6
_jsonrpc_response
7.1
CRAP 4.8
« MCP/Tool.pm ↑ Summary MCP/Primitive.pm »
1 package MCP::Server;
2 10 ▶use Mojo::Base 'Mojo::EventEmitter', -signatures;
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 10 ▶use Crypt::PRNG qw(random_bytes);
Subroutine BEGIN: called CC=1 SCAR=0.0
5 10 ▶use List::Util qw(first min);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 10 ▶use Mojo::JSON qw(false true);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 10 ▶use Mojo::Log;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 10 ▶use MCP::Constants qw(INSUFFICIENT_SCOPE INTERNAL_ERROR INVALID_PARAMS INVALID_REQUEST META_CLIENT_CAPABILITIES),
Subroutine BEGIN: called CC=1 SCAR=0.0
9 qw(META_CLIENT_INFO META_LOG_LEVEL META_PROTOCOL_VERSION META_SERVER_INFO METHOD_NOT_FOUND PARSE_ERROR),
10 10 qw(SUPPORTED_VERSIONS UNSUPPORTED_PROTOCOL_VERSION);
11 10 ▶use MCP::Prompt;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 10 ▶use MCP::Resource;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 10 ▶use MCP::Server::Legacy qw(legacy_context legacy_result);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 10 ▶use MCP::Server::Subscription;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 10 ▶use MCP::Server::Transport::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 10 ▶use MCP::Server::Transport::Stdio;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 10 ▶use MCP::Tool;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 10 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 10 has cache_scope => 'public';
21 10 has cache_ttl => 0;
22 10 has 'instructions';
23 0 ▶has log => sub { Mojo::Log->new };
Subroutine __ANON__: not called CC=1 SCAR=1.2
24 10 has name => 'PerlServer';
25 8 ▶has prompts => sub { [] };
Subroutine __ANON__: called CC=1 SCAR=0.0
26 8 ▶has resources => sub { [] };
Subroutine __ANON__: called CC=1 SCAR=0.0
27 8 ▶has state_secret => sub { random_bytes(32) };
Subroutine __ANON__: called CC=1 SCAR=0.0
28 10 has state_timeout => 300;
29 12 ▶has tools => sub { [] };
Subroutine __ANON__: called CC=1 SCAR=0.0
30 10 has 'transport';
31 10 has version => '1.0.0';
32  
33 133 ▶sub handle ($self, $request, $context) {
Subroutine handle: called CC=5 SCAR=16.2
Pod documented
34 133 ▶ return _jsonrpc_error(PARSE_ERROR, 'Invalid JSON-RPC request') unless ref $request eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $request eq "HASH" 0 133 133
35 133 ▶ return _jsonrpc_error(INVALID_REQUEST, 'Missing JSON-RPC method') unless $request->{method};
Branch: 1 branch
BranchTrueFalseTotal
unless $$request{"method"} 0 133 133
36  
37 # Requests
38 133 ▶ if (defined(my $id = $request->{id})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $id = $$request{"id"})) 131 2 133
39 131 my $response;
40 return $self->_internal_error($context, $id, $@)
41 131 ▶ unless eval { $response = $self->_dispatch($request, $id, $context); 1 };
Branch: 1 branch
BranchTrueFalseTotal
unless eval { do { $response = $self->_dispatch($request, $id, $context); 1 } } 8 123 131
42 123 return $response;
43 }
44  
45 # Notifications (ignored for now)
46 2 return undef;
47 }
48  
49 5 ▶sub notify_list_changed ($self, $kind) {
Subroutine notify_list_changed: called CC=2 SCAR=7.2
Pod documented
50 5 ▶ return undef unless my $transport = $self->transport;
Branch: 1 branch
BranchTrueFalseTotal
unless my $transport = $self->transport 0 5 5
51 5 return $transport->notify_all("notifications/$kind/list_changed");
52 }
53  
54 1 ▶sub oauth_metadata ($self, %args) {
Subroutine oauth_metadata: called CC=5 SCAR=16.2
Pod documented
55 1 my %scopes;
56 1 for my $primitive (@{$self->tools}, @{$self->prompts}, @{$self->resources}) {
57 7 $scopes{$_} = 1 for @{$primitive->scopes};
58 }
59 1 my $metadata = {%args};
60 1 ▶ $metadata->{scopes_supported} //= [sort keys %scopes] if keys %scopes;
Branch: 1 branch
BranchTrueFalseTotal
if keys %scopes 1 0 1
Condition50%1/2
$$metadata{"scopes_supported"} //= [sort(keys %scopes)]
l!l
01
MC/DC0%0/1
$$metadata{"scopes_supported"} //= [sort(keys %scopes)]
$$metadata{"scopes_supported"}
Truth table50%1/2
A
A= $$metadata{"scopes_supported"}
Aresult
11
00
61 1 return $metadata;
62 }
63  
64 11 ▶sub prompt ($self, %args) {
Subroutine prompt: called CC=1 SCAR=0.0
Pod documented
65 11 my $prompt = MCP::Prompt->new(%args);
66 11 push @{$self->prompts}, $prompt;
67 11 return $prompt;
68 }
69  
70 11 ▶sub resource ($self, %args) {
Subroutine resource: called CC=1 SCAR=0.0
Pod documented
71 11 my $resource = MCP::Resource->new(%args);
72 11 push @{$self->resources}, $resource;
73 11 return $resource;
74 }
75  
76 13 ▶sub to_action ($self, $options = {}) {
Subroutine to_action: called CC=2 SCAR=6.9
Pod documented
77 13 $self->transport(my $http = MCP::Server::Transport::HTTP->new(server => $self, %$options));
78 13 ▶ return sub ($c) { $http->handle_request($c) };
Subroutine __ANON__: called CC=1 SCAR=0.0
79 }
80  
81 0 ▶sub to_stdio ($self) {
Subroutine to_stdio: not called CC=1 SCAR=6.9
Pod documented
82 0 $self->transport(my $stdio = MCP::Server::Transport::Stdio->new(server => $self));
83 0 $self->transport->handle_requests;
84 }
85  
86 30 ▶sub tool ($self, %args) {
Subroutine tool: called CC=1 SCAR=0.0
Pod documented
87 30 my $tool = MCP::Tool->new(%args);
88 30 push @{$self->tools}, $tool;
89 30 return $tool;
90 }
91  
92 3 ▶sub _handle_discover ($self) {
Subroutine _handle_discover: called CC=7 SCAR=20.3
93 3 my $transport = $self->transport;
94 3 ▶ my $caps = $transport && $transport->notifications ? {listChanged => true} : {};
Branch: 1 branch
BranchTrueFalseTotal
$transport && $transport->notifications ? : 1 2 3
Condition66%2/3
$transport and $transport->notifications
!ll&&!rl&&r
021
MC/DC50%1/2
$transport and $transport->notifications
$transport $transport->notifications
Truth table66%2/3
A and B
A= $transportB= $transport->notifications
ABresult
0X0
100
111
95  
96 3 my $capabilities = {extensions => {}};
97 3 ▶ $capabilities->{prompts} = $caps if @{$self->prompts};
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->prompts;} 3 0 3
98 3 ▶ $capabilities->{resources} = $caps if @{$self->resources};
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->resources;} 3 0 3
99 3 ▶ $capabilities->{tools} = $caps if @{$self->tools};
Branch: 1 branch
BranchTrueFalseTotal
if @{$self->tools;} 3 0 3
100  
101 3 my $result = {supportedVersions => SUPPORTED_VERSIONS, capabilities => $capabilities};
102 0 ▶ if (defined(my $instructions = $self->instructions)) { $result->{instructions} = $instructions }
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $instructions = $self->instructions)) 0 3 3
103 3 return $result;
104 }
105  
106 3 ▶sub _handle_listen ($self, $params, $id, $context) {
Subroutine _handle_listen: called CC=4 SCAR=14.1
107 3 my $transport = $self->transport;
108 return MCP::Server::Subscription->new(id => $id, notifications => $params->{notifications} // {})
109 3 ▶ if $transport && $transport->notifications;
Branch: 1 branch
BranchTrueFalseTotal
if $transport and $transport->notifications 2 1 3
Condition60%3/5
$transport and $transport->notifications
!ll&&!rl&&r
012
$$params{"notifications"} // {}
l!l
20
MC/DC50%1/2
$transport and $transport->notifications
$transport $transport->notifications
MC/DC0%0/1
$$params{"notifications"} // {}
$$params{"notifications"}
Truth table66%2/3
A and B
A= $transportB= $transport->notifications
ABresult
0X0
100
111
Truth table50%1/2
A
A= $$params{"notifications"}
Aresult
11
00
110 1 $context->status(404);
111 1 return _jsonrpc_error(METHOD_NOT_FOUND, "Method 'subscriptions/listen' not found", $id);
112 }
113  
114 6 ▶sub _handle_prompts_list ($self, $context) {
Subroutine _handle_prompts_list: called CC=3 SCAR=11.0
115 6 my $all = $self->_prompts($context);
116  
117 6 my (@prompts, @listed);
118 6 for my $prompt (@$all) {
119 11 ▶ next unless $context->has_scope(@{$prompt->scopes});
Branch: 1 branch
BranchTrueFalseTotal
unless $context->has_scope(@{$prompt->scopes;}) 1 10 11
120 10 my $info = {name => $prompt->name, description => $prompt->description, arguments => $prompt->arguments};
121 10 push @prompts, $info;
122 10 push @listed, $prompt;
123 }
124  
125 6 return {prompts => \@prompts}, $self->_list_cache_hints('prompts', $all, \@listed);
126 }
127  
128 18 ▶sub _handle_prompts_get ($self, $params, $id, $context) {
Subroutine _handle_prompts_get: called CC=6 SCAR=18.0
129 18 ▶ my $name = $params->{name} // '';
Condition50%1/2
$$params{"name"} // ""
l!l
180
MC/DC0%0/1
$$params{"name"} // ""
$$params{"name"}
Truth table50%1/2
A
A= $$params{"name"}
Aresult
11
00
130 18 ▶ my $args = $params->{arguments} // {};
Condition50%1/2
$$params{"arguments"} // {}
l!l
180
MC/DC0%0/1
$$params{"arguments"} // {}
$$params{"arguments"}
Truth table50%1/2
A
A= $$params{"arguments"}
Aresult
11
00
131 return _jsonrpc_error(INVALID_PARAMS, "Prompt '$name' not found", $id)
132 18 ▶ unless my $prompt = first { $_->name eq $name } @{$self->_prompts($context)};
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless my $prompt = &first(sub { $_->name eq $name; } , @{$self->_prompts($context);}) 2 16 18
133 16 ▶ if (my $err = $self->_check_scope($prompt, $context, $id)) { return $err }
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $self->_check_scope($prompt, $context, $id)) 1 15 16
134 15 ▶ return _jsonrpc_error(INVALID_PARAMS, 'Invalid arguments', $id) if $prompt->validate_input($args);
Branch: 1 branch
BranchTrueFalseTotal
if $prompt->validate_input($args) 1 14 15
135 14 $self->_state($context, $params, 'prompts/get', $name);
136  
137 14 return $self->_respond($prompt->call($args, $context), $id, $context);
138 }
139  
140 6 ▶sub _handle_resources_list ($self, $context) {
Subroutine _handle_resources_list: called CC=3 SCAR=11.0
141 6 my $all = $self->_resources($context);
142  
143 6 my (@resources, @listed);
144 6 for my $resource (@$all) {
145 11 ▶ next unless $context->has_scope(@{$resource->scopes});
Branch: 1 branch
BranchTrueFalseTotal
unless $context->has_scope(@{$resource->scopes;}) 1 10 11
146 10 my $info = {
147 uri => $resource->uri,
148 name => $resource->name,
149 description => $resource->description,
150 mimeType => $resource->mime_type
151 };
152 10 push @resources, $info;
153 10 push @listed, $resource;
154 }
155  
156 6 return {resources => \@resources}, $self->_list_cache_hints('resources', $all, \@listed);
157 }
158  
159 15 ▶sub _handle_resources_read ($self, $params, $id, $context) {
Subroutine _handle_resources_read: called CC=6 SCAR=17.9
160 15 ▶ my $uri = $params->{uri} // '';
Condition50%1/2
$$params{"uri"} // ""
l!l
150
MC/DC0%0/1
$$params{"uri"} // ""
$$params{"uri"}
Truth table50%1/2
A
A= $$params{"uri"}
Aresult
11
00
161 return _jsonrpc_error(INVALID_PARAMS, "Resource '$uri' not found", $id)
162 15 ▶ unless my $resource = first { $_->uri eq $uri } @{$self->_resources($context)};
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless my $resource = &first(sub { $_->uri eq $uri; } , @{$self->_resources($context);}) 2 13 15
163 13 ▶ if (my $err = $self->_check_scope($resource, $context, $id)) { return $err }
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $self->_check_scope($resource, $context, $id)) 1 12 13
164 my $hints
165 = $self->_state($context, $params, 'resources/read', $uri)
166 ? undef
167 12 ▶ : _cache_hints($resource->cache_ttl, @{$resource->scopes} ? 'private' : $resource->cache_scope);
Branch: 2 branches
BranchTrueFalseTotal
$self->_state($context, $params, 'resources/read', $uri) ? : 1 11 12
@{$resource->scopes;} ? : 2 9 11
168  
169 12 return $self->_respond($resource->call($context), $id, $context, $hints);
170 }
171  
172 58 ▶sub _handle_tools_call ($self, $params, $id, $context) {
Subroutine _handle_tools_call: called CC=6 SCAR=18.0
173 58 ▶ my $name = $params->{name} // '';
Condition50%1/2
$$params{"name"} // ""
l!l
580
MC/DC0%0/1
$$params{"name"} // ""
$$params{"name"}
Truth table50%1/2
A
A= $$params{"name"}
Aresult
11
00
174 58 ▶ my $args = $params->{arguments} // {};
Condition50%1/2
$$params{"arguments"} // {}
l!l
580
MC/DC0%0/1
$$params{"arguments"} // {}
$$params{"arguments"}
Truth table50%1/2
A
A= $$params{"arguments"}
Aresult
11
00
175 return _jsonrpc_error(INVALID_PARAMS, "Tool '$name' not found", $id)
176 58 ▶ unless my $tool = first { $_->name eq $name } @{$self->_tools($context)};
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless my $tool = &first(sub { $_->name eq $name; } , @{$self->_tools($context);}) 4 53 57
177 53 ▶ if (my $err = $self->_check_scope($tool, $context, $id)) { return $err }
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $self->_check_scope($tool, $context, $id)) 2 51 53
178 51 ▶ return _jsonrpc_error(INVALID_PARAMS, 'Invalid arguments', $id) if $tool->validate_input($args);
Branch: 1 branch
BranchTrueFalseTotal
if $tool->validate_input($args) 2 48 50
179 48 $self->_state($context, $params, 'tools/call', $name);
180  
181 48 return $self->_respond($tool->call($args, $context), $id, $context);
182 }
183  
184 10 ▶sub _handle_tools_list ($self, $context) {
Subroutine _handle_tools_list: called CC=5 SCAR=16.1
185 10 my $all = $self->_tools($context);
186  
187 9 my (@tools, @listed);
188 9 for my $tool (@$all) {
189 26 ▶ next unless $context->has_scope(@{$tool->scopes});
Branch: 1 branch
BranchTrueFalseTotal
unless $context->has_scope(@{$tool->scopes;}) 1 25 26
190 25 my $info = {name => $tool->name, description => $tool->description, inputSchema => $tool->input_schema};
191 25 ▶ if (my $output_schema = $tool->output_schema) { $info->{outputSchema} = $output_schema }
Branch: 1 branch
BranchTrueFalseTotal
if (my $output_schema = $tool->output_schema) 1 24 25
192  
193 25 my $annotations = $tool->annotations;
194 25 ▶ $info->{annotations} = $annotations if keys %$annotations;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$annotations 2 23 25
195 25 push @tools, $info;
196 25 push @listed, $tool;
197 }
198  
199 9 return {tools => \@tools}, $self->_list_cache_hints('tools', $all, \@listed);
200 }
201  
202 35 ▶sub _cache_hints ($ttl, $scope) { return {cacheScope => $scope, ttlMs => $ttl} }
Subroutine _cache_hints: called CC=1 SCAR=0.0
203  
204 115 ▶sub _check_fields ($meta, $id) {
Subroutine _check_fields: called CC=4 SCAR=13.9
205 115 my $version = $meta->{+META_PROTOCOL_VERSION};
206 115 ▶ return _jsonrpc_error(INVALID_PARAMS, 'Missing protocol version', $id) unless defined $version;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $version 1 114 115
207 return _jsonrpc_error(UNSUPPORTED_PROTOCOL_VERSION, "Unsupported protocol version '$version'",
208 $id, {supported => SUPPORTED_VERSIONS, requested => $version})
209 114 ▶ unless first { $_ eq $version } @{(SUPPORTED_VERSIONS)};
Subroutine __ANON__: called CC=1 SCAR=0.0
Branch: 1 branch
BranchTrueFalseTotal
unless &first(sub { $_ eq $version; } , @{["2026-07-28"];}) 1 113 114
210 return _jsonrpc_error(INVALID_PARAMS, 'Missing client capabilities', $id)
211 113 ▶ unless ref $meta->{+META_CLIENT_CAPABILITIES} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $$meta{"io.modelcontextprotocol/clientCapabilities"} eq "HASH" 1 112 113
212 112 return undef;
213 }
214  
215 115 ▶sub _check_meta ($self, $params, $id, $context) {
Subroutine _check_meta: called CC=6 SCAR=17.9
216 115 ▶ my $meta = $params->{_meta} // {};
Condition50%1/2
$$params{"_meta"} // {}
l!l
1150
MC/DC0%0/1
$$params{"_meta"} // {}
$$params{"_meta"}
Truth table50%1/2
A
A= $$params{"_meta"}
Aresult
11
00
217  
218 115 ▶ if (my $err = _check_fields($meta, $id)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = _check_fields($meta, $id)) 3 112 115
219 3 $context->status(400);
220 3 return $err;
221 }
222  
223 112 $context->protocol_version($meta->{+META_PROTOCOL_VERSION});
224 112 $context->client_capabilities($meta->{+META_CLIENT_CAPABILITIES});
225 112 ▶ if (my $info = $meta->{+META_CLIENT_INFO}) { $context->client_info($info) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $info = $$meta{"io.modelcontextprotocol/clientInfo"}) 97 15 112
226 112 ▶ if (my $level = $meta->{+META_LOG_LEVEL}) { $context->log_level($level) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $level = $$meta{"io.modelcontextprotocol/logLevel"}) 1 111 112
227 112 ▶ if (defined(my $token = $meta->{progressToken})) { $context->progress_token($token) }
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $token = $$meta{"progressToken"})) 3 109 112
228  
229 112 return undef;
230 }
231  
232 82 ▶sub _check_scope ($self, $primitive, $context, $id) {
Subroutine _check_scope: called CC=2 SCAR=6.9
233 82 my $scopes = $primitive->scopes;
234 82 ▶ return undef if $context->has_scope(@$scopes);
Branch: 1 branch
BranchTrueFalseTotal
if $context->has_scope(@$scopes) 78 4 82
235 4 $context->insufficient_scope($scopes)->status(403);
236 4 return _jsonrpc_error(INSUFFICIENT_SCOPE, 'Insufficient scope', $id);
237 }
238  
239 131 ▶sub _dispatch ($self, $request, $id, $context) {
Subroutine _dispatch: called CC=13 SCAR=25.7
240 131 my $method = $request->{method};
241 131 ▶ my $params = $request->{params} // {};
Condition50%1/2
$$request{"params"} // {}
l!l
1310
MC/DC0%0/1
$$request{"params"} // {}
$$request{"params"}
Truth table50%1/2
A
A= $$request{"params"}
Aresult
11
00
242  
243 # Legacy
244 131 ▶ if (my $version = $context->legacy) {
Branch: 2 branches
BranchTrueFalseTotal
if (my $version = $context->legacy) { } 16 115 131
elsif (my $err = $self->_check_meta($params, $id, $context)) { } 3 112 115
245 16 ▶ if (my $result = legacy_result($self, $method, $version)) { return $self->_jsonrpc_response($result, $id) }
Branch: 1 branch
BranchTrueFalseTotal
if (my $result = legacy_result($self, $method, $version)) 7 9 16
246 9 legacy_context($params, $context);
247 }
248 3 elsif (my $err = $self->_check_meta($params, $id, $context)) { return $err }
249  
250 121 ▶ if ($method eq 'server/discover') {
Branch: 8 branches
BranchTrueFalseTotal
if ($method eq 'server/discover') { } 3 118 121
elsif ($method eq 'tools/list') { } 10 108 118
elsif ($method eq 'tools/call') { } 58 50 108
elsif ($method eq 'prompts/list') { } 6 44 50
elsif ($method eq 'prompts/get') { } 18 26 44
elsif ($method eq 'resources/list') { } 6 20 26
elsif ($method eq 'resources/read') { } 15 5 20
elsif ($method eq 'subscriptions/listen') { } 3 2 5
251 3 my $hints = _cache_hints($self->cache_ttl, $self->cache_scope);
252 3 return $self->_jsonrpc_response($self->_handle_discover, $id, $hints);
253 }
254 elsif ($method eq 'tools/list') {
255 10 my ($result, $hints) = $self->_handle_tools_list($context);
256 9 return $self->_jsonrpc_response($result, $id, $hints);
257 }
258 elsif ($method eq 'tools/call') {
259 58 return $self->_handle_tools_call($params, $id, $context);
260 }
261 elsif ($method eq 'prompts/list') {
262 6 my ($result, $hints) = $self->_handle_prompts_list($context);
263 6 return $self->_jsonrpc_response($result, $id, $hints);
264 }
265 elsif ($method eq 'prompts/get') {
266 18 return $self->_handle_prompts_get($params, $id, $context);
267 }
268 elsif ($method eq 'resources/list') {
269 6 my ($result, $hints) = $self->_handle_resources_list($context);
270 6 return $self->_jsonrpc_response($result, $id, $hints);
271 }
272 elsif ($method eq 'resources/read') {
273 15 return $self->_handle_resources_read($params, $id, $context);
274 }
275 elsif ($method eq 'subscriptions/listen') {
276 3 return $self->_handle_listen($params, $id, $context);
277 }
278  
279 # Method not found
280 2 $context->status(404);
281 2 return _jsonrpc_error(METHOD_NOT_FOUND, "Method '$method' not found", $id);
282 }
283  
284 10 ▶sub _internal_error ($self, $context, $id, $err) {
Subroutine _internal_error: called CC=1 SCAR=0.0
285 10 $self->log->error("MCP request failed: $err");
286 10 $context->status(500);
287 10 return _jsonrpc_error(INTERNAL_ERROR, 'Internal error', $id);
288 }
289  
290 31 ▶sub _jsonrpc_error ($code, $message, $id = undef, $data = undef) {
Subroutine _jsonrpc_error: called CC=4 SCAR=13.9
291 31 my $error = {code => $code, message => $message};
292 31 ▶ $error->{data} = $data if defined $data;
Branch: 1 branch
BranchTrueFalseTotal
if defined $data 1 30 31
293 31 return {jsonrpc => '2.0', id => $id, error => $error};
294 }
295  
296 98 ▶sub _jsonrpc_response ($self, $result, $id = undef, $hints = undef) {
Subroutine _jsonrpc_response: called CC=7 SCAR=19.6
297 98 ▶ my $type = $result->{resultType} // 'complete';
Condition100%2/2
$$result{"resultType"} // "complete"
l!l
791
MC/DC100%1/1
$$result{"resultType"} // "complete"
$$result{"resultType"}
Truth table100%2/2
A
A= $$result{"resultType"}
Aresult
11
00
298 98 ▶ my %new = (%$result, ($hints && $type eq 'complete' ? %$hints : ()), resultType => $type);
Branch: 1 branch
BranchTrueFalseTotal
$hints && $type eq 'complete' ? : 34 64 98
Condition66%2/3
$hints and $type eq "complete"
!ll&&!rl&&r
64034
MC/DC50%1/2
$hints and $type eq "complete"
$hints $type eq "complete"
Truth table66%2/3
A and B
A= $hintsB= $type eq "complete"
ABresult
0X0
100
111
299 98 ▶ $new{_meta} = {%{$result->{_meta} // {}}, META_SERVER_INFO() => {name => $self->name, version => $self->version}};
Condition50%1/2
$$result{"_meta"} // {}
l!l
098
MC/DC0%0/1
$$result{"_meta"} // {}
$$result{"_meta"}
Truth table50%1/2
A
A= $$result{"_meta"}
Aresult
11
00
300 98 return {jsonrpc => '2.0', id => $id, result => \%new};
301 }
302  
303 21 ▶sub _list_cache_hints ($self, $event, $all, $listed) {
Subroutine _list_cache_hints: called CC=4 SCAR=13.9
304 21 ▶ my $private = $self->has_subscribers($event) || grep { @{$_->scopes} } @$all;
Condition100%3/3
$self->has_subscribers($event) || grep({@{$_->scopes;};} @$all)
l!l&&r!l&&!r
1047
MC/DC100%2/2
$self->has_subscribers($event) || grep({@{$_->scopes;};} @$all)
$self->has_subscribers($event) grep({@{$_->scopes;};} @$all)
Truth table100%3/3
A || B
A= $self->has_subscribers($event)B= grep({@{$_->scopes;};} @$all)
ABresult
1X1
011
000
305 21 ▶ return _cache_hints(min(map { $_->cache_ttl } @$listed) // 0, $private ? 'private' : 'public');
Branch: 1 branch
BranchTrueFalseTotal
$private ? : 14 7 21
Condition50%1/2
&min(map({$_->cache_ttl;} @$listed)) // 0
l!l
210
MC/DC0%0/1
&min(map({$_->cache_ttl;} @$listed)) // 0
&min(map({$_->cache_ttl;} @$listed))
Truth table50%1/2
A
A= &min(map({$_->cache_ttl;} @$listed))
Aresult
11
00
306 }
307  
308 24 ▶sub _prompts ($self, $context) {
Subroutine _prompts: called CC=1 SCAR=0.0
309 24 my $prompts = [@{$self->prompts}];
310 24 $self->emit('prompts', $prompts, $context);
311 24 return $prompts;
312 }
313  
314 21 ▶sub _resources ($self, $context) {
Subroutine _resources: called CC=1 SCAR=0.0
315 21 my $resources = [@{$self->resources}];
316 21 $self->emit('resources', $resources, $context);
317 21 return $resources;
318 }
319  
320 69 ▶sub _respond ($self, $result, $id, $context, $hints = undef) {
Subroutine _respond: called CC=4 SCAR=13.9
321 69 ▶ return $self->_jsonrpc_response($result, $id, $hints) unless blessed($result) && $result->isa('Mojo::Promise');
Branch: 1 branch
BranchTrueFalseTotal
unless builtin::blessed($result) and $result->isa("Mojo::Promise") 60 9 69
Condition66%2/3
builtin::blessed($result) and $result->isa("Mojo::Promise")
!ll&&!rl&&r
6009
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
322 7 ▶ return $result->then(sub { $self->_jsonrpc_response($_[0], $id, $hints) })
Subroutine __ANON__: called CC=1 SCAR=0.0
323 9 ▶ ->catch(sub { $self->_internal_error($context, $id, $_[0]) });
Subroutine __ANON__: called CC=1 SCAR=0.0
324 }
325  
326 74 ▶sub _state ($self, $context, $params, @binding) {
Subroutine _state: called CC=5 SCAR=16.1
327 74 $context->state_binding(join "\0", @binding)->state_secret($self->state_secret);
328 74 $context->state_timeout($self->state_timeout);
329 74 ▶ $context->input_responses($params->{inputResponses}) if ref $params->{inputResponses} eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $$params{"inputResponses"} eq "HASH" 4 70 74
330 74 ▶ $context->raw_request_state($params->{requestState}) if defined $params->{requestState};
Branch: 1 branch
BranchTrueFalseTotal
if defined $$params{"requestState"} 8 66 74
331 74 ▶ return $context->input_responses || defined $context->raw_request_state ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$context->input_responses || defined $context->raw_request_state ? : 8 66 74
Condition100%3/3
$context->input_responses or defined $context->raw_request_state
l!l&&r!l&&!r
4466
MC/DC100%2/2
$context->input_responses or defined $context->raw_request_state
$context->input_responses defined $context->raw_request_state
Truth table100%3/3
A or B
A= $context->input_responsesB= defined $context->raw_request_state
ABresult
1X1
011
000
332 }
333  
334 68 ▶sub _tools ($self, $context) {
Subroutine _tools: called CC=1 SCAR=0.0
335 68 my $tools = [@{$self->tools}];
336 68 $self->emit('tools', $tools, $context);
337 66 return $tools;
338 }
339  
340 10 1;
341  
342 =encoding utf8
343  
344 =head1 NAME
345  
346 MCP::Server - MCP server implementation
347  
348 =head1 SYNOPSIS
349  
350 use MCP::Server;
351  
352 my $server = MCP::Server->new(name => 'MyServer');
353  
354 $server->tool(
355 name => 'echo',
356 description => 'Echo the input text',
357 input_schema => {type => 'object', properties => {msg => {type => 'string'}}, required => ['msg']},
358 code => sub ($tool, $args) {
359 return "Echo: $args->{msg}";
360 }
361 );
362  
363 $server->prompt(
364 name => 'echo',
365 description => 'A prompt to demonstrate the echo tool',
366 code => sub ($prompt, $args) {
367 return 'Use the echo tool with the message "Hello, World!"';
368 }
369 );
370  
371 $server->resource(
372 uri => 'file:///example.txt',
373 name => 'example',
374 description => 'A simple text resource',
375 mime_type => 'text/plain',
376 code => sub ($resource) {
377 return 'This is an example resource content.';
378 }
379 );
380  
381 $server->to_stdio;
382  
383 =head1 DESCRIPTION
384  
385 L<MCP::Server> is an MCP (Model Context Protocol) server.
386  
387 =head1 EVENTS
388  
389 L<MCP::Server> inherits all events from L<Mojo::EventEmitter> and emits the following new ones.
390  
391 =head2 prompts
392  
393 $server->on(prompts => sub ($server, $prompts, $context) { ... });
394  
395 Emitted whenever the list of prompts is accessed.
396  
397 =head2 resources
398  
399 $server->on(resources => sub ($server, $resources, $context) { ... });
400  
401 Emitted whenever the list of resources is accessed.
402  
403 =head2 tools
404  
405 $server->on(tools => sub ($server, $tools, $context) { ... });
406  
407 Emitted whenever the list of tools is accessed.
408  
409 =head1 ATTRIBUTES
410  
411 L<MCP::Server> implements the following attributes.
412  
413 =head2 cache_scope
414  
415 my $scope = $server->cache_scope;
416 $server = $server->cache_scope('private');
417  
418 Cache scope advertised for C<server/discover> results, either C<public> or C<private>. Defaults to C<public>. Cache
419 hints for the other cacheable results are declared per primitive with L<MCP::Primitive/"cache_scope">.
420  
421 =head2 cache_ttl
422  
423 my $ttl = $server->cache_ttl;
424 $server = $server->cache_ttl(3_600_000);
425  
426 How long C<server/discover> results may be cached, in milliseconds. Defaults to C<0>, which means the document must
427 be revalidated on every request.
428  
429 =head2 instructions
430  
431 my $instructions = $server->instructions;
432 $server = $server->instructions('Use the echo tool to repeat text.');
433  
434 Free-form guidance for the model on how to use this server, returned by C<server/discover>. Omitted from the
435 document when C<undef>, which is the default.
436  
437 =head2 log
438  
439 my $log = $server->log;
440 $server = $server->log(Mojo::Log->new);
441  
442 Where exceptions thrown by prompts, resources, and tools are reported, defaults to a L<Mojo::Log> object writing to
443 C<STDERR>, which is where an MCP host collects the output of a stdio server.
444  
445 A server mounted in a L<Mojolicious> application with L</"to_action"> adopts the log of that application on its
446 first request, so exceptions end up wherever the rest of the application logs, with the same level and format. Set
447 this attribute yourself to opt out of that.
448  
449 The caller never sees the exception itself, only an C<InternalError>, since it can easily contain file system paths
450 or connection strings.
451  
452 =head2 name
453  
454 my $name = $server->name;
455 $server = $server->name('MyServer');
456  
457 The name of the server, used for identification.
458  
459 =head2 prompts
460  
461 my $prompts = $server->prompts;
462 $server = $server->prompts([MCP::Prompt->new]);
463  
464 An array reference containing registered prompts.
465  
466 =head2 resources
467  
468 my $resources = $server->resources;
469 $server = $server->resources([MCP::Resource->new]);
470  
471 An array reference containing registered resources.
472  
473 =head2 state_secret
474  
475 my $secret = $server->state_secret;
476 $server = $server->state_secret($ENV{MY_MCP_SECRET});
477  
478 Key used to authenticate the request state of C<input_required> results, which travels through the client and has to
479 be tamper proof. Defaults to 32 random bytes generated once per process.
480  
481 That default is only correct for a single process. Under a pre-forking web server or behind a load balancer every
482 worker mints state the others reject, so retries loop instead of completing, and you have to configure the same
483 secret everywhere. Use at least 32 bytes from a cryptographically secure source, and keep it out of your code.
484  
485 =head2 state_timeout
486  
487 my $seconds = $server->state_timeout;
488 $server = $server->state_timeout(60);
489  
490 How long the request state of an C<input_required> result stays valid, in seconds. Defaults to C<300>, and should be
491 no longer than a client plausibly needs to gather the requested input.
492  
493 =head2 tools
494  
495 my $tools = $server->tools;
496 $server = $server->tools([MCP::Tool->new]);
497  
498 An array reference containing registered tools.
499  
500 =head2 transport
501  
502 my $transport = $server->transport;
503 $server = $server->transport(MCP::Server::Transport::HTTP->new);
504  
505 The transport layer used by the server, such as L<MCP::Server::Transport::HTTP> or L<MCP::Server::Transport::Stdio>.
506  
507 =head2 version
508  
509 my $version = $server->version;
510 $server = $server->version('1.0.0');
511  
512 The version of the server.
513  
514 =head1 METHODS
515  
516 L<MCP::Server> inherits all methods from L<Mojo::EventEmitter> and implements the following new ones.
517  
518 =head2 handle
519  
520 my $response = $server->handle($request, $context);
521  
522 Handle a JSON-RPC request and return a response, which may also be a L<Mojo::Promise>. A C<subscriptions/listen>
523 request yields an L<MCP::Server::Subscription> object instead, which the transport turns into a notification
524 stream. Notifications yield C<undef>.
525  
526 =head2 notify_list_changed
527  
528 my $bool = $server->notify_list_changed('tools');
529  
530 Broadcast a C<notifications/$kind/list_changed> JSON-RPC notification to all connected clients. Returns true on
531 success, or C<undef> if no notification could be delivered.
532  
533 =head2 oauth_metadata
534  
535 my $metadata = $server->oauth_metadata(
536 resource => 'https://example.com/mcp',
537 authorization_servers => ['https://auth.example.com']
538 );
539  
540 Build an OAuth 2.0 Protected Resource Metadata document from the given fields, to be served from
541 C</.well-known/oauth-protected-resource>. Unless C<scopes_supported> is provided, it is filled in with the sorted
542 union of all scopes declared by registered tools, prompts, and resources.
543  
544 =head2 prompt
545  
546 my $prompt = $server->prompt(
547 name => 'my_prompt',
548 description => 'A sample prompt',
549 arguments => [{name => 'foo', description => 'Whatever', required => 1}],
550 code => sub ($prompt, $args) { ... }
551 );
552  
553 Register a new prompt with the server.
554  
555 =head2 resource
556  
557 my $resource = $server->resource(
558 uri => 'file://my_resource',
559 name => 'sample_resource',
560 description => 'A sample resource',
561 mime_type => 'text/plain',
562 code => sub ($resource) { ... }
563 );
564  
565 Register a new resource with the server.
566  
567 =head2 to_action
568  
569 my $action = $server->to_action;
570 my $action = $server->to_action({streaming => 1});
571  
572 Convert the server to a L<Mojolicious> action. Any options are passed through to the constructor of
573 L<MCP::Server::Transport::HTTP>; in particular, C<< streaming => 1 >> opts in to C<subscriptions/listen>, the
574 long-lived notification stream.
575  
576 =head2 to_stdio
577  
578 $server->to_stdio;
579  
580 Handles JSON-RPC requests over standard input/output.
581  
582 =head2 tool
583  
584 my $tool = $server->tool(
585 name => 'my_tool',
586 description => 'A sample tool',
587 input_schema => {type => 'object', properties => {foo => {type => 'string'}}},
588 code => sub ($tool, $args) { ... }
589 );
590  
591 Register a new tool with the server.
592  
593 =head1 SEE ALSO
594  
595 L<MCP>, L<https://mojolicious.org>, L<https://modelcontextprotocol.io>.
596  
597 =cut
« MCP/Tool.pm ↑ Summary MCP/Primitive.pm »