| 1 | package Net::Async::MCP::Server; | ||
| 2 | # ABSTRACT: Async MCP server base class | ||
| 3 | |||
| 4 | 5 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 5 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | |||
| 7 | 5 | ▶ | use parent 'IO::Async::Notifier'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | |||
| 9 | use Future::AsyncAwait; | ||
| 10 | |||
| 11 | use JSON::MaybeXS qw( encode_json ); | ||
| 12 | use Carp qw( croak ); | ||
| 13 | |||
| 14 | our $VERSION = '0.003'; | ||
| 15 | |||
| 16 | |||
| 17 | # The protocol revision this server advertises through the 2026-07-28 | ||
| 18 | # server/discover response. legacy_compat has a separate Stdio-only wire path; | ||
| 19 | # it does not make 2025-11-25 a valid 2026 per-request metadata version. | ||
| 20 | our $PROTOCOL_VERSION = '2026-07-28'; | ||
| 21 | |||
| 22 | # The 2026-07-28 metadata format does not negotiate down to its handshake-based | ||
| 23 | # predecessor. legacy_compat handles 2025-11-25 separately for Stdio. | ||
| 24 | sub supported_versions { [ '2026-07-28' ] } | ||
| 25 | |||
| 26 | |||
| 27 | # --- Registry: the three registrable kinds ------------------------------- | ||
| 28 | # | ||
| 29 | # tools, resources and prompts share one storage / lookup / wire-shape | ||
| 30 | # mechanism. Each kind names the field its entries are keyed by (used by | ||
| 31 | # _find) and the field lists that build its tools/list-style wire shape: | ||
| 32 | # `required` fields are copied verbatim, `optional` fields only when defined, | ||
| 33 | # and `defaults` supplies a value for a required field the caller omitted | ||
| 34 | # (prompts' arguments). register_* keeps its own validation — the required | ||
| 35 | # fields, error messages and normalisation genuinely differ per kind — but | ||
| 36 | # everything downstream of a stored entry is generic. | ||
| 37 | my %REGISTRY = ( | ||
| 38 | tools => { | ||
| 39 | key => 'name', | ||
| 40 | wire => { | ||
| 41 | required => [qw( name description inputSchema )], | ||
| 42 | optional => [qw( title annotations outputSchema )], | ||
| 43 | }, | ||
| 44 | }, | ||
| 45 | resources => { | ||
| 46 | key => 'uri', | ||
| 47 | wire => { | ||
| 48 | required => [qw( uri name )], | ||
| 49 | optional => [qw( mimeType description title )], | ||
| 50 | }, | ||
| 51 | }, | ||
| 52 | prompts => { | ||
| 53 | key => 'name', | ||
| 54 | wire => { | ||
| 55 | required => [qw( name )], | ||
| 56 | optional => [qw( title description )], | ||
| 57 | defaults => { arguments => sub { [] } }, | ||
| 58 | }, | ||
| 59 | }, | ||
| 60 | ); | ||
| 61 | |||
| 62 | sub _register { | ||
| 63 | my ( $self, $kind, %def ) = @_; | ||
| 64 | my $key = $def{ $REGISTRY{$kind}{key} }; | ||
| 65 | ( my $label = $kind ) =~ s/s\z//; | ||
| 66 | croak ucfirst( $label ).q{ '}.$key.q{' is already registered} | ||
| 67 | if $self->_find( $kind => $key ); | ||
| 68 | push @{ $self->{$kind} //= [] }, \%def; | ||
| 69 | return; | ||
| 70 | } | ||
| 71 | |||
| 72 | sub _find { | ||
| 73 | my ( $self, $kind, $key ) = @_; | ||
| 74 | my $field = $REGISTRY{$kind}{key}; | ||
| 75 | for my $entry ( @{ $self->{$kind} // [] } ) { | ||
| 76 | return $entry if $entry->{$field} eq $key; | ||
| 77 | } | ||
| 78 | return; | ||
| 79 | } | ||
| 80 | |||
| 81 | sub _wire_shape { | ||
| 82 | my ( $self, $kind, $def ) = @_; | ||
| 83 | my $spec = $REGISTRY{$kind}{wire}; | ||
| 84 | |||
| 85 | my %wire; | ||
| 86 | $wire{$_} = $def->{$_} for @{ $spec->{required} }; | ||
| 87 | for my $field ( sort keys %{ $spec->{defaults} // {} } ) { | ||
| 88 | $wire{$field} = defined $def->{$field} | ||
| 89 | ? $def->{$field} | ||
| 90 | : $spec->{defaults}{$field}->(); | ||
| 91 | } | ||
| 92 | for my $field ( @{ $spec->{optional} } ) { | ||
| 93 | $wire{$field} = $def->{$field} if defined $def->{$field}; | ||
| 94 | } | ||
| 95 | return \%wire; | ||
| 96 | } | ||
| 97 | |||
| 98 | sub configure { | ||
| 99 | my ( $self, %params ) = @_; | ||
| 100 | if (exists $params{name}) { | ||
| 101 | $self->{name} = delete $params{name}; | ||
| 102 | } | ||
| 103 | if (exists $params{legacy_compat}) { | ||
| 104 | $self->{legacy_compat} = delete $params{legacy_compat} ? 1 : 0; | ||
| 105 | } | ||
| 106 | $self->SUPER::configure(%params); | ||
| 107 | } | ||
| 108 | |||
| 109 | sub name { shift->{name} // 'NetAsyncMCPServer' } | ||
| 110 | |||
| 111 | sub legacy_compat { shift->{legacy_compat} // 0 } | ||
| 112 | |||
| 113 | |||
| 114 | |||
| 115 | sub server_info { | ||
| 116 | my ( $self ) = @_; | ||
| 117 | return { | ||
| 118 | name => $self->name, | ||
| 119 | version => $VERSION, | ||
| 120 | }; | ||
| 121 | } | ||
| 122 | |||
| 123 | |||
| 124 | sub server_capabilities { | ||
| 125 | my ( $self ) = @_; | ||
| 126 | return $self->_build_capabilities; | ||
| 127 | } | ||
| 128 | |||
| 129 | |||
| 130 | sub _build_capabilities { | ||
| 131 | my ( $self ) = @_; | ||
| 132 | my %cap = ( tools => {} ); | ||
| 133 | $cap{resources} = {} if @{ $self->resources }; | ||
| 134 | $cap{prompts} = {} if @{ $self->prompts }; | ||
| 135 | return \%cap; | ||
| 136 | } | ||
| 137 | |||
| 138 | async sub discover { | ||
| 139 | my ( $self ) = @_; | ||
| 140 | |||
| 141 | return { | ||
| 142 | resultType => 'complete', | ||
| 143 | supportedVersions => $self->supported_versions, | ||
| 144 | capabilities => $self->server_capabilities, | ||
| 145 | ttlMs => 300000, | ||
| 146 | cacheScope => 'public', | ||
| 147 | }; | ||
| 148 | } | ||
| 149 | |||
| 150 | |||
| 151 | sub tools { | ||
| 152 | my ( $self ) = @_; | ||
| 153 | return $self->{tools} // []; | ||
| 154 | } | ||
| 155 | |||
| 156 | |||
| 157 | sub find_tool { | ||
| 158 | my ( $self, $name ) = @_; | ||
| 159 | return unless defined $name; | ||
| 160 | return $self->_find( tools => $name ); | ||
| 161 | } | ||
| 162 | |||
| 163 | |||
| 164 | sub register_tool { | ||
| 165 | my ( $self, %tool ) = @_; | ||
| 166 | croak q{register_tool requires 'name'} unless defined $tool{name}; | ||
| 167 | |||
| 168 | # Normalise input_schema -> inputSchema. Accept the legacy snake_case key | ||
| 169 | # so existing callers don't have to change in lockstep. | ||
| 170 | if ( exists $tool{input_schema} && !exists $tool{inputSchema} ) { | ||
| 171 | $tool{inputSchema} = delete $tool{input_schema}; | ||
| 172 | } | ||
| 173 | |||
| 174 | croak "Tool '$tool{name}' requires 'inputSchema'" | ||
| 175 | unless exists $tool{inputSchema}; | ||
| 176 | |||
| 177 | return $self->_register( tools => %tool ); | ||
| 178 | } | ||
| 179 | |||
| 180 | |||
| 181 | async sub list_tools { | ||
| 182 | my ( $self ) = @_; | ||
| 183 | return [ map { $self->_wire_shape( tools => $_ ) } @{ $self->{tools} // [] } ]; | ||
| 184 | } | ||
| 185 | |||
| 186 | |||
| 187 | async sub call_tool { | ||
| 188 | my ( $self, $name, $arguments ) = @_; | ||
| 189 | |||
| 190 | my $tool = $self->_find( tools => $name ); | ||
| 191 | croak "No tool registered: $name" unless $tool; | ||
| 192 | |||
| 193 | if (my $code = $tool->{code}) { | ||
| 194 | my $result = $code->($arguments); | ||
| 195 | $result = await $result if ref $result eq 'Future'; | ||
| 196 | return $result; | ||
| 197 | } | ||
| 198 | |||
| 199 | croak "Tool '$name' has no implementation"; | ||
| 200 | } | ||
| 201 | |||
| 202 | |||
| 203 | sub resources { | ||
| 204 | my ( $self ) = @_; | ||
| 205 | return $self->{resources} // []; | ||
| 206 | } | ||
| 207 | |||
| 208 | |||
| 209 | sub register_resource { | ||
| 210 | my ( $self, %resource ) = @_; | ||
| 211 | croak q{register_resource requires 'uri'} unless defined $resource{uri}; | ||
| 212 | croak q{register_resource requires 'name'} unless defined $resource{name}; | ||
| 213 | |||
| 214 | return $self->_register( resources => %resource ); | ||
| 215 | } | ||
| 216 | |||
| 217 | |||
| 218 | async sub list_resources { | ||
| 219 | my ( $self ) = @_; | ||
| 220 | return [ map { $self->_wire_shape( resources => $_ ) } @{ $self->{resources} // [] } ]; | ||
| 221 | } | ||
| 222 | |||
| 223 | |||
| 224 | async sub read_resource { | ||
| 225 | my ( $self, $uri ) = @_; | ||
| 226 | |||
| 227 | my $resource = $self->_find( resources => $uri ); | ||
| 228 | croak "No resource registered: $uri" unless $resource; | ||
| 229 | |||
| 230 | my $result; | ||
| 231 | if ( my $code = $resource->{code} ) { | ||
| 232 | $result = $code->($uri); | ||
| 233 | $result = await $result if ref $result eq 'Future'; | ||
| 234 | } | ||
| 235 | else { | ||
| 236 | croak "Resource '$uri' has no implementation"; | ||
| 237 | } | ||
| 238 | |||
| 239 | # A resource may return its own result hashref already carrying contents | ||
| 240 | # blocks (multiple parts, a blob, an explicit mimeType). Pass it through. | ||
| 241 | return $result | ||
| 242 | if ref $result eq 'HASH' && ref $result->{contents} eq 'ARRAY'; | ||
| 243 | |||
| 244 | # Default wrapping: a bare scalar becomes a single text content block, | ||
| 245 | # tagged with the resource's declared mimeType when it has one. | ||
| 246 | my $content = { | ||
| 247 | uri => $uri, | ||
| 248 | text => ( defined $result ? "$result" : '' ), | ||
| 249 | }; | ||
| 250 | $content->{mimeType} = $resource->{mimeType} if defined $resource->{mimeType}; | ||
| 251 | |||
| 252 | return { contents => [ $content ] }; | ||
| 253 | } | ||
| 254 | |||
| 255 | |||
| 256 | sub prompts { | ||
| 257 | my ( $self ) = @_; | ||
| 258 | return $self->{prompts} // []; | ||
| 259 | } | ||
| 260 | |||
| 261 | |||
| 262 | sub register_prompt { | ||
| 263 | my ( $self, %prompt ) = @_; | ||
| 264 | croak q{register_prompt requires 'name'} unless defined $prompt{name}; | ||
| 265 | |||
| 266 | return $self->_register( prompts => %prompt ); | ||
| 267 | } | ||
| 268 | |||
| 269 | |||
| 270 | async sub list_prompts { | ||
| 271 | my ( $self ) = @_; | ||
| 272 | return [ map { $self->_wire_shape( prompts => $_ ) } @{ $self->{prompts} // [] } ]; | ||
| 273 | } | ||
| 274 | |||
| 275 | |||
| 276 | async sub get_prompt { | ||
| 277 | my ( $self, $name, $arguments ) = @_; | ||
| 278 | |||
| 279 | my $prompt = $self->_find( prompts => $name ); | ||
| 280 | croak "No prompt registered: $name" unless $prompt; | ||
| 281 | |||
| 282 | my $result; | ||
| 283 | if ( my $code = $prompt->{code} ) { | ||
| 284 | $result = $code->($arguments); | ||
| 285 | $result = await $result if ref $result eq 'Future'; | ||
| 286 | } | ||
| 287 | else { | ||
| 288 | croak "Prompt '$name' has no implementation"; | ||
| 289 | } | ||
| 290 | |||
| 291 | # A prompt may return its own result hashref already carrying a messages | ||
| 292 | # arrayref (and an optional description). Pass it through verbatim. | ||
| 293 | return $result | ||
| 294 | if ref $result eq 'HASH' && ref $result->{messages} eq 'ARRAY'; | ||
| 295 | |||
| 296 | # Default wrapping: a bare scalar becomes a single user text message. | ||
| 297 | return { | ||
| 298 | messages => [ | ||
| 299 | { | ||
| 300 | role => 'user', | ||
| 301 | content => { | ||
| 302 | type => 'text', | ||
| 303 | text => ( defined $result ? "$result" : '' ), | ||
| 304 | }, | ||
| 305 | }, | ||
| 306 | ], | ||
| 307 | }; | ||
| 308 | } | ||
| 309 | |||
| 310 | |||
| 311 | # JSON-RPC method -> handler, tried once per-request _meta has validated. Each | ||
| 312 | # entry is invoked as $self->$handler( $request, $id ) and pulls whatever it | ||
| 313 | # needs (params, id) from those; this map replaces the former if/elsif ladder. | ||
| 314 | my %DISPATCH = ( | ||
| 315 | 'server/discover' => sub { $_[0]->_handle_discover( $_[2] ) }, | ||
| 316 | 'tools/list' => sub { $_[0]->_handle_tools_list( $_[2] ) }, | ||
| 317 | 'tools/call' => sub { $_[0]->_handle_tools_call( $_[1]->{params} // {}, $_[2] ) }, | ||
| 318 | 'resources/list' => sub { $_[0]->_handle_resources_list( $_[2] ) }, | ||
| 319 | 'resources/read' => sub { $_[0]->_handle_resources_read( $_[1]->{params} // {}, $_[2] ) }, | ||
| 320 | 'prompts/list' => sub { $_[0]->_handle_prompts_list( $_[2] ) }, | ||
| 321 | 'prompts/get' => sub { $_[0]->_handle_prompts_get( $_[1]->{params} // {}, $_[2] ) }, | ||
| 322 | ); | ||
| 323 | |||
| 324 | sub handle { | ||
| 325 | my ( $self, $request, $context ) = @_; | ||
| 326 | |||
| 327 | return _jsonrpc_error( -32700, 'Invalid JSON-RPC request' ) | ||
| 328 | unless ref $request eq 'HASH'; | ||
| 329 | |||
| 330 | my $method = $request->{method}; | ||
| 331 | my $id = $request->{id}; | ||
| 332 | |||
| 333 | return _jsonrpc_error( -32600, 'Missing JSON-RPC method', $id ) | ||
| 334 | unless defined $method; | ||
| 335 | |||
| 336 | return $self->_handle_legacy_request($request) | ||
| 337 | if $self->_is_legacy_stdio_request( $request, $context ); | ||
| 338 | |||
| 339 | if ( defined $id ) { | ||
| 340 | # Per-request _meta validation. Required on every RPC; missing or | ||
| 341 | # wrong-version fields short-circuit the dispatch with a JSON-RPC | ||
| 342 | # error so the client can fall back / renegotiate. | ||
| 343 | if ( my $err = $self->_validate_request_meta($request) ) { | ||
| 344 | return $err; | ||
| 345 | } | ||
| 346 | |||
| 347 | if ( my $handler = $DISPATCH{$method} ) { | ||
| 348 | return $self->$handler( $request, $id ); | ||
| 349 | } | ||
| 350 | |||
| 351 | return _jsonrpc_error( -32601, "Method '$method' not found", $id ); | ||
| 352 | } | ||
| 353 | |||
| 354 | # Notifications (no id): no-op. The stdio transport skips writing | ||
| 355 | # anything when handle() returns undef. | ||
| 356 | return undef; | ||
| 357 | } | ||
| 358 | |||
| 359 | sub _is_legacy_stdio_request { | ||
| 360 | my ( $self, $request, $context ) = @_; | ||
| 361 | |||
| 362 | return unless $self->legacy_compat; | ||
| 363 | return unless ref $context eq 'HASH' && ( $context->{transport} // '' ) eq 'stdio'; | ||
| 364 | return unless $request->{method} =~ /\A(?:initialize|ping|notifications\/initialized|tools\/list|tools\/call)\z/; | ||
| 365 | return unless !defined $self->_request_protocol_version($request); | ||
| 366 | |||
| 367 | return 1; | ||
| 368 | } | ||
| 369 | |||
| 370 | sub _request_protocol_version { | ||
| 371 | my ( $self, $request ) = @_; | ||
| 372 | |||
| 373 | my $params = $request->{params}; | ||
| 374 | return undef unless ref $params eq 'HASH'; | ||
| 375 | |||
| 376 | my $meta = $params->{_meta}; | ||
| 377 | return undef unless ref $meta eq 'HASH'; | ||
| 378 | |||
| 379 | return $meta->{'io.modelcontextprotocol/protocolVersion'}; | ||
| 380 | } | ||
| 381 | |||
| 382 | sub _handle_legacy_request { | ||
| 383 | my ( $self, $request ) = @_; | ||
| 384 | |||
| 385 | my $method = $request->{method}; | ||
| 386 | my $id = $request->{id}; | ||
| 387 | |||
| 388 | return undef if $method eq 'notifications/initialized' && !defined $id; | ||
| 389 | return undef unless defined $id; | ||
| 390 | |||
| 391 | if ( $method eq 'initialize' ) { | ||
| 392 | my $params = ref $request->{params} eq 'HASH' ? $request->{params} : {}; | ||
| 393 | my $version = $params->{protocolVersion}; | ||
| 394 | unless ( defined $version && $version eq '2025-11-25' ) { | ||
| 395 | return _jsonrpc_error( | ||
| 396 | -32602, | ||
| 397 | 'Invalid params: unsupported protocolVersion', | ||
| 398 | $id, | ||
| 399 | ); | ||
| 400 | } | ||
| 401 | |||
| 402 | return $self->_legacy_jsonrpc_response( | ||
| 403 | { | ||
| 404 | protocolVersion => '2025-11-25', | ||
| 405 | capabilities => { tools => {} }, | ||
| 406 | serverInfo => $self->server_info, | ||
| 407 | }, | ||
| 408 | $id, | ||
| 409 | ); | ||
| 410 | } | ||
| 411 | |||
| 412 | return $self->_legacy_jsonrpc_response( {}, $id ) if $method eq 'ping'; | ||
| 413 | return $self->_handle_legacy_tools_list($id) if $method eq 'tools/list'; | ||
| 414 | if ( $method eq 'tools/call' ) { | ||
| 415 | my $params = $request->{params} // {}; | ||
| 416 | return _jsonrpc_error( -32602, 'Invalid params: params must be an object', $id ) | ||
| 417 | unless ref $params eq 'HASH'; | ||
| 418 | return $self->_handle_legacy_tools_call( $params, $id ); | ||
| 419 | } | ||
| 420 | |||
| 421 | return _jsonrpc_error( -32601, "Method '$method' not found", $id ); | ||
| 422 | } | ||
| 423 | |||
| 424 | sub _handle_legacy_tools_list { | ||
| 425 | my ( $self, $id ) = @_; | ||
| 426 | |||
| 427 | return $self->_legacy_jsonrpc_response( | ||
| 428 | { tools => $self->list_tools->get }, | ||
| 429 | $id, | ||
| 430 | ); | ||
| 431 | } | ||
| 432 | |||
| 433 | sub _handle_legacy_tools_call { | ||
| 434 | my ( $self, $params, $id ) = @_; | ||
| 435 | |||
| 436 | my $name = $params->{name} // ''; | ||
| 437 | my $args = $params->{arguments} // {}; | ||
| 438 | |||
| 439 | return _jsonrpc_error( -32602, 'Invalid params: arguments must be an object', $id ) | ||
| 440 | unless ref $args eq 'HASH'; | ||
| 441 | |||
| 442 | my $tool = $self->_find( tools => $name ); | ||
| 443 | unless ($tool) { | ||
| 444 | return _jsonrpc_error( | ||
| 445 | -32602, | ||
| 446 | "Invalid params: unknown tool '$name'", | ||
| 447 | $id, | ||
| 448 | ); | ||
| 449 | } | ||
| 450 | |||
| 451 | my $result; | ||
| 452 | eval { | ||
| 453 | $result = $self->call_tool( $name, $args )->get; | ||
| 454 | 1; | ||
| 455 | } or do { | ||
| 456 | return $self->_legacy_jsonrpc_response( | ||
| 457 | { | ||
| 458 | content => [ { type => 'text', text => "$@" } ], | ||
| 459 | isError => JSON::MaybeXS::true(), | ||
| 460 | }, | ||
| 461 | $id, | ||
| 462 | ); | ||
| 463 | }; | ||
| 464 | |||
| 465 | return $self->_legacy_jsonrpc_response( | ||
| 466 | $self->_legacy_tool_result($result), | ||
| 467 | $id, | ||
| 468 | ); | ||
| 469 | } | ||
| 470 | |||
| 471 | sub _legacy_tool_result { | ||
| 472 | my ( $self, $result ) = @_; | ||
| 473 | |||
| 474 | if ( ref $result eq 'HASH' | ||
| 475 | && ( ref $result->{content} eq 'ARRAY' | ||
| 476 | || exists $result->{structuredContent} ) ) { | ||
| 477 | my %legacy = ( | ||
| 478 | isError => $self->_legacy_boolean($result->{isError}), | ||
| 479 | ); | ||
| 480 | $legacy{content} = $result->{content} | ||
| 481 | if ref $result->{content} eq 'ARRAY'; | ||
| 482 | $legacy{structuredContent} = $result->{structuredContent} | ||
| 483 | if exists $result->{structuredContent}; | ||
| 484 | $legacy{content} = [ | ||
| 485 | { | ||
| 486 | type => 'text', | ||
| 487 | text => encode_json($result->{structuredContent}), | ||
| 488 | }, | ||
| 489 | ] unless exists $legacy{content}; | ||
| 490 | return \%legacy; | ||
| 491 | } | ||
| 492 | |||
| 493 | if ( ref $result eq 'HASH' && defined $result->{resultType} ) { | ||
| 494 | return { | ||
| 495 | content => [ | ||
| 496 | { | ||
| 497 | type => 'text', | ||
| 498 | text => 'Tool result type '.$result->{resultType} | ||
| 499 | .' is unavailable with protocol version 2025-11-25', | ||
| 500 | }, | ||
| 501 | ], | ||
| 502 | isError => JSON::MaybeXS::true(), | ||
| 503 | }; | ||
| 504 | } | ||
| 505 | |||
| 506 | my $text = ref $result | ||
| 507 | ? encode_json($result) | ||
| 508 | : ( defined $result ? "$result" : '' ); | ||
| 509 | |||
| 510 | return { | ||
| 511 | content => [ { type => 'text', text => $text } ], | ||
| 512 | isError => JSON::MaybeXS::false(), | ||
| 513 | }; | ||
| 514 | } | ||
| 515 | |||
| 516 | sub _legacy_boolean { | ||
| 517 | my ( $self, $value ) = @_; | ||
| 518 | return $value ? JSON::MaybeXS::true() : JSON::MaybeXS::false(); | ||
| 519 | } | ||
| 520 | |||
| 521 | sub _legacy_jsonrpc_response { | ||
| 522 | my ( $self, $result, $id ) = @_; | ||
| 523 | return { jsonrpc => '2.0', id => $id, result => $result }; | ||
| 524 | } | ||
| 525 | |||
| 526 | |||
| 527 | sub _validate_request_meta { | ||
| 528 | my ( $self, $request ) = @_; | ||
| 529 | my $id = $request->{id}; | ||
| 530 | my $params = $request->{params}; | ||
| 531 | my $meta = ( ref $params eq 'HASH' && ref $params->{_meta} eq 'HASH' ) | ||
| 532 | ? $params->{_meta} | ||
| 533 | : {}; | ||
| 534 | |||
| 535 | my $version = $meta->{'io.modelcontextprotocol/protocolVersion'}; | ||
| 536 | unless ( defined $version && length $version ) { | ||
| 537 | return _jsonrpc_error( | ||
| 538 | -32602, | ||
| 539 | 'Invalid params: missing io.modelcontextprotocol/protocolVersion', | ||
| 540 | $id, | ||
| 541 | ); | ||
| 542 | } | ||
| 543 | |||
| 544 | my $supported = $self->supported_versions; | ||
| 545 | unless ( grep { $_ eq $version } @{$supported} ) { | ||
| 546 | return _jsonrpc_error( | ||
| 547 | -32022, | ||
| 548 | 'Unsupported protocol version', | ||
| 549 | $id, | ||
| 550 | { | ||
| 551 | supported => $supported, | ||
| 552 | requested => $version, | ||
| 553 | }, | ||
| 554 | ); | ||
| 555 | } | ||
| 556 | |||
| 557 | unless ( exists $meta->{'io.modelcontextprotocol/clientCapabilities'} ) { | ||
| 558 | return _jsonrpc_error( | ||
| 559 | -32602, | ||
| 560 | 'Invalid params: missing io.modelcontextprotocol/clientCapabilities', | ||
| 561 | $id, | ||
| 562 | ); | ||
| 563 | } | ||
| 564 | |||
| 565 | return undef; | ||
| 566 | } | ||
| 567 | |||
| 568 | sub _handle_discover { | ||
| 569 | my ( $self, $id ) = @_; | ||
| 570 | |||
| 571 | my $result = $self->discover->get; | ||
| 572 | return $self->_jsonrpc_response( $result, $id ); | ||
| 573 | } | ||
| 574 | |||
| 575 | sub _handle_tools_list { | ||
| 576 | my ( $self, $id ) = @_; | ||
| 577 | |||
| 578 | my $tools = $self->list_tools->get; | ||
| 579 | return $self->_jsonrpc_response( | ||
| 580 | { | ||
| 581 | resultType => 'complete', | ||
| 582 | tools => $tools, | ||
| 583 | ttlMs => 300000, | ||
| 584 | cacheScope => 'public', | ||
| 585 | }, | ||
| 586 | $id, | ||
| 587 | ); | ||
| 588 | } | ||
| 589 | |||
| 590 | sub _handle_tools_call { | ||
| 591 | my ( $self, $params, $id ) = @_; | ||
| 592 | |||
| 593 | my $name = $params->{name} // ''; | ||
| 594 | my $args = $params->{arguments} // {}; | ||
| 595 | |||
| 596 | # Protocol error: unknown tool. The spec routes this through JSON-RPC, | ||
| 597 | # not through an isError result, so the model can't retry it as if it | ||
| 598 | # were a recoverable tool failure. | ||
| 599 | my $tool = $self->_find( tools => $name ); | ||
| 600 | unless ($tool) { | ||
| 601 | return _jsonrpc_error( | ||
| 602 | -32602, | ||
| 603 | "Invalid params: unknown tool '$name'", | ||
| 604 | $id, | ||
| 605 | ); | ||
| 606 | } | ||
| 607 | |||
| 608 | my $result; | ||
| 609 | eval { | ||
| 610 | $result = $self->call_tool($name, $args)->get; | ||
| 611 | 1; | ||
| 612 | } or do { | ||
| 613 | # Tool execution error — wrap in isError content block so the model | ||
| 614 | # can see and self-correct, instead of a JSON-RPC error that would | ||
| 615 | # abort the call. | ||
| 616 | return $self->_jsonrpc_response( | ||
| 617 | { | ||
| 618 | resultType => 'complete', | ||
| 619 | content => [ { type => 'text', text => "$@" } ], | ||
| 620 | isError => JSON::MaybeXS::true(), | ||
| 621 | }, | ||
| 622 | $id, | ||
| 623 | ); | ||
| 624 | }; | ||
| 625 | |||
| 626 | # MRTR: a tool may return its own result hashref (e.g. resultType => | ||
| 627 | # 'input_required'). Passed through; only isError is normalized, on a | ||
| 628 | # shallow copy so the tool's own hash is not mutated. | ||
| 629 | if ( ref $result eq 'HASH' && defined $result->{resultType} ) { | ||
| 630 | $result = { %$result, isError => $self->_legacy_boolean( $result->{isError} ) } | ||
| 631 | if exists $result->{isError}; | ||
| 632 | return $self->_jsonrpc_response( $result, $id ); | ||
| 633 | } | ||
| 634 | |||
| 635 | # Rich content: a tool may return a hashref carrying its own content | ||
| 636 | # blocks and/or structuredContent (without a resultType). Pass it | ||
| 637 | # through verbatim; _jsonrpc_response fills in resultType => 'complete'. | ||
| 638 | if ( ref $result eq 'HASH' | ||
| 639 | && ( ref $result->{content} eq 'ARRAY' | ||
| 640 | || exists $result->{structuredContent} ) ) { | ||
| 641 | # isError is a schema boolean; tool authors may return Perl truthiness. | ||
| 642 | $result = { %$result, isError => $self->_legacy_boolean( $result->{isError} ) } | ||
| 643 | if exists $result->{isError}; | ||
| 644 | # CallToolResult requires content; for backwards compatibility the | ||
| 645 | # spec says structured content SHOULD also be serialized as text. | ||
| 646 | $result = { | ||
| 647 | %$result, | ||
| 648 | content => [ { type => 'text', text => encode_json( $result->{structuredContent} ) } ], | ||
| 649 | } if exists $result->{structuredContent} && ref $result->{content} ne 'ARRAY'; | ||
| 650 | return $self->_jsonrpc_response( $result, $id ); | ||
| 651 | } | ||
| 652 | |||
| 653 | # Default wrapping: a tool's plain return value becomes a text content | ||
| 654 | # block inside a complete result. Scalars are stringified; refs are | ||
| 655 | # JSON-encoded so the tool author can return any JSON-shaped data | ||
| 656 | # without having to think about it. | ||
| 657 | my $text = ref $result | ||
| 658 | ? encode_json($result) | ||
| 659 | : ( defined $result ? "$result" : '' ); | ||
| 660 | |||
| 661 | return $self->_jsonrpc_response( | ||
| 662 | { | ||
| 663 | resultType => 'complete', | ||
| 664 | content => [ { type => 'text', text => $text } ], | ||
| 665 | }, | ||
| 666 | $id, | ||
| 667 | ); | ||
| 668 | } | ||
| 669 | |||
| 670 | sub _handle_resources_list { | ||
| 671 | my ( $self, $id ) = @_; | ||
| 672 | |||
| 673 | my $resources = $self->list_resources->get; | ||
| 674 | return $self->_jsonrpc_response( | ||
| 675 | { | ||
| 676 | resultType => 'complete', | ||
| 677 | resources => $resources, | ||
| 678 | }, | ||
| 679 | $id, | ||
| 680 | ); | ||
| 681 | } | ||
| 682 | |||
| 683 | sub _handle_resources_read { | ||
| 684 | my ( $self, $params, $id ) = @_; | ||
| 685 | |||
| 686 | my $uri = $params->{uri} // ''; | ||
| 687 | |||
| 688 | # Protocol error: unknown resource. Routed through JSON-RPC -32602. | ||
| 689 | my $resource = $self->_find( resources => $uri ); | ||
| 690 | unless ($resource) { | ||
| 691 | return _jsonrpc_error( | ||
| 692 | -32602, | ||
| 693 | "Invalid params: unknown resource '$uri'", | ||
| 694 | $id, | ||
| 695 | ); | ||
| 696 | } | ||
| 697 | |||
| 698 | my $result; | ||
| 699 | eval { | ||
| 700 | $result = $self->read_resource($uri)->get; | ||
| 701 | 1; | ||
| 702 | } or do { | ||
| 703 | # Resource execution error — a dying code ref or a registered-but- | ||
| 704 | # codeless resource. Unlike tools/call, which routes tool execution | ||
| 705 | # failures into isError content blocks so the model can self-correct, | ||
| 706 | # a resource read failure is a server-side internal error: -32603. | ||
| 707 | return _jsonrpc_error( -32603, "Internal error: $@", $id ); | ||
| 708 | }; | ||
| 709 | |||
| 710 | return $self->_jsonrpc_response( $result, $id ); | ||
| 711 | } | ||
| 712 | |||
| 713 | sub _handle_prompts_list { | ||
| 714 | my ( $self, $id ) = @_; | ||
| 715 | |||
| 716 | my $prompts = $self->list_prompts->get; | ||
| 717 | return $self->_jsonrpc_response( | ||
| 718 | { | ||
| 719 | resultType => 'complete', | ||
| 720 | prompts => $prompts, | ||
| 721 | }, | ||
| 722 | $id, | ||
| 723 | ); | ||
| 724 | } | ||
| 725 | |||
| 726 | sub _handle_prompts_get { | ||
| 727 | my ( $self, $params, $id ) = @_; | ||
| 728 | |||
| 729 | my $name = $params->{name} // ''; | ||
| 730 | my $args = $params->{arguments} // {}; | ||
| 731 | |||
| 732 | # Protocol error: unknown prompt. Routed through JSON-RPC -32602. | ||
| 733 | my $prompt = $self->_find( prompts => $name ); | ||
| 734 | unless ($prompt) { | ||
| 735 | return _jsonrpc_error( | ||
| 736 | -32602, | ||
| 737 | "Invalid params: unknown prompt '$name'", | ||
| 738 | $id, | ||
| 739 | ); | ||
| 740 | } | ||
| 741 | |||
| 742 | # Protocol error: a registered argument marked required must be present. | ||
| 743 | for my $def ( @{ $prompt->{arguments} // [] } ) { | ||
| 744 | next unless ref $def eq 'HASH' && $def->{required}; | ||
| 745 | my $arg = $def->{name}; | ||
| 746 | next unless defined $arg; | ||
| 747 | next if ref $args eq 'HASH' && defined $args->{$arg}; | ||
| 748 | return _jsonrpc_error( | ||
| 749 | -32602, | ||
| 750 | "Invalid params: missing required argument '$arg'", | ||
| 751 | $id, | ||
| 752 | ); | ||
| 753 | } | ||
| 754 | |||
| 755 | my $result; | ||
| 756 | eval { | ||
| 757 | $result = $self->get_prompt($name, $args)->get; | ||
| 758 | 1; | ||
| 759 | } or do { | ||
| 760 | # Prompt execution error — a dying code ref or a registered-but- | ||
| 761 | # codeless prompt. Unlike tools/call, which routes tool execution | ||
| 762 | # failures into isError content blocks so the model can self-correct, | ||
| 763 | # a prompt fetch failure is a server-side internal error: -32603. | ||
| 764 | return _jsonrpc_error( -32603, "Internal error: $@", $id ); | ||
| 765 | }; | ||
| 766 | |||
| 767 | return $self->_jsonrpc_response( $result, $id ); | ||
| 768 | } | ||
| 769 | |||
| 770 | sub _jsonrpc_error { | ||
| 771 | my ( $code, $message, $id, $data ) = @_; | ||
| 772 | my $err = { code => $code, message => $message }; | ||
| 773 | $err->{data} = $data if defined $data; | ||
| 774 | return { | ||
| 775 | jsonrpc => '2.0', | ||
| 776 | id => $id, | ||
| 777 | error => $err, | ||
| 778 | }; | ||
| 779 | } | ||
| 780 | |||
| 781 | sub _jsonrpc_response { | ||
| 782 | my ( $self, $result, $id ) = @_; | ||
| 783 | if ( ref $result eq 'HASH' ) { | ||
| 784 | $result->{resultType} //= 'complete'; | ||
| 785 | $result->{_meta}{'io.modelcontextprotocol/serverInfo'} = $self->server_info; | ||
| 786 | } | ||
| 787 | return { jsonrpc => '2.0', id => $id, result => $result }; | ||
| 788 | } | ||
| 789 | |||
| 790 | 1; | ||
| 791 | |||
| 792 | __END__ | ||