| 1 | package Net::Async::MCP::Server::Transport::StreamableHTTP; | ||
| 2 | # ABSTRACT: Streamable HTTP transport for Net::Async::MCP::Server | ||
| 3 | |||
| 4 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 6 | |||
| 7 | 1 | ▶ | use parent 'IO::Async::Notifier'; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 8 | |||
| 9 | use JSON::MaybeXS qw( encode_json decode_json ); | ||
| 10 | use MIME::Base64 qw( decode_base64 ); | ||
| 11 | use Encode qw( decode FB_DEFAULT ); | ||
| 12 | use Scalar::Util qw( looks_like_number ); | ||
| 13 | use HTTP::Server::PSGI; | ||
| 14 | |||
| 15 | our $VERSION = '0.003'; | ||
| 16 | |||
| 17 | |||
| 18 | # The methods whose name-ish parameter is mirrored into Mcp-Name, and the | ||
| 19 | # parameter it is taken from. Same table the client half uses. | ||
| 20 | my %NAME_PARAM = ( | ||
| 21 | 'tools/call' => 'name', | ||
| 22 | 'resources/read' => 'uri', | ||
| 23 | 'prompts/get' => 'name', | ||
| 24 | ); | ||
| 25 | |||
| 26 | # The header names the spec owns. HTTP/1.1 header lookup is case-insensitive | ||
| 27 | # but we still need canonical spellings to read PSGI's HTTP_MCP_PROTOCOL_VERSION | ||
| 28 | # (a CGI-style env key is one underscore per dash, uppercased) back into the | ||
| 29 | # spec's form. | ||
| 30 | my $PROTOCOL_HEADER = 'MCP-Protocol-Version'; | ||
| 31 | my $METHOD_HEADER = 'Mcp-Method'; | ||
| 32 | my $NAME_HEADER = 'Mcp-Name'; | ||
| 33 | my $PARAM_HEADER_PREFIX = 'Mcp-Param-'; | ||
| 34 | |||
| 35 | sub new { | ||
| 36 | my ( $class, %params ) = @_; | ||
| 37 | my $server = delete $params{server}; | ||
| 38 | my $self = $class->SUPER::new(%params); | ||
| 39 | $self->{server} = $server if defined $server; | ||
| 40 | return $self; | ||
| 41 | } | ||
| 42 | |||
| 43 | sub configure { | ||
| 44 | my ( $self, %params ) = @_; | ||
| 45 | for my $key (qw( server host port path origin_allow )) { | ||
| 46 | $self->{$key} = delete $params{$key} if exists $params{$key}; | ||
| 47 | } | ||
| 48 | |||
| 49 | $self->{host} //= '127.0.0.1'; | ||
| 50 | $self->{port} //= 8080; | ||
| 51 | $self->{path} //= '/mcp'; | ||
| 52 | $self->{origin_allow} //= []; | ||
| 53 | |||
| 54 | # Adapt origin_allow to a hash for O(1) membership tests. | ||
| 55 | if ( ref $self->{origin_allow} eq 'ARRAY' ) { | ||
| 56 | my %o = map { $_ => 1 } @{ $self->{origin_allow} }; | ||
| 57 | $self->{origin_allow_set} = \%o; | ||
| 58 | } | ||
| 59 | |||
| 60 | $self->SUPER::configure(%params); | ||
| 61 | } | ||
| 62 | |||
| 63 | |||
| 64 | sub server { $_[0]->{server} } | ||
| 65 | |||
| 66 | |||
| 67 | sub host { $_[0]->{host} } | ||
| 68 | |||
| 69 | |||
| 70 | sub port { $_[0]->{port} } | ||
| 71 | |||
| 72 | |||
| 73 | sub path { $_[0]->{path} } | ||
| 74 | |||
| 75 | |||
| 76 | sub origin_allow { $_[0]->{origin_allow} || [] } | ||
| 77 | |||
| 78 | |||
| 79 | sub to_app { | ||
| 80 | my ( $self ) = @_; | ||
| 81 | my $transport = $self; | ||
| 82 | |||
| 83 | return sub { | ||
| 84 | my ( $env ) = @_; | ||
| 85 | return $transport->_handle_request($env); | ||
| 86 | }; | ||
| 87 | } | ||
| 88 | |||
| 89 | |||
| 90 | sub listen { | ||
| 91 | my ( $self, %opts ) = @_; | ||
| 92 | my $host = $self->{host}; | ||
| 93 | |||
| 94 | # Refuse to silently expose the server on a public interface. | ||
| 95 | unless ( $opts{allow_external_bind} | ||
| 96 | || $host eq '127.0.0.1' | ||
| 97 | || $host eq '::1' | ||
| 98 | || $host eq 'localhost' | ||
| 99 | || $host eq '' ) { | ||
| 100 | warn "StreamableHTTP listening on $host:${\$self->{port}}; " | ||
| 101 | . "this is non-loopback. Set 'host' to 127.0.0.1 or pass " | ||
| 102 | . "allow_external_bind to acknowledge.\n"; | ||
| 103 | } | ||
| 104 | |||
| 105 | my $server = HTTP::Server::PSGI->new( | ||
| 106 | host => $host, | ||
| 107 | port => $self->{port}, | ||
| 108 | ); | ||
| 109 | $server->run( $self->to_app ); | ||
| 110 | return $server; | ||
| 111 | } | ||
| 112 | |||
| 113 | # --- The PSGI dispatch path ---------------------------------------------- | ||
| 114 | |||
| 115 | # Reads the request body off the PSGI input handle. PSGI gives us a stream | ||
| 116 | # to read from, not a string; this is straightforward but the format's two | ||
| 117 | # scalar/array forms are easy to get wrong. | ||
| 118 | sub _read_body { | ||
| 119 | my ( $env ) = @_; | ||
| 120 | my $in = $env->{'psgi.input'}; | ||
| 121 | return '' unless $in; | ||
| 122 | |||
| 123 | my $cl = $env->{CONTENT_LENGTH}; | ||
| 124 | return '' unless defined $cl && length $cl && $cl =~ /\A[0-9]+\z/; | ||
| 125 | |||
| 126 | my $body = ''; | ||
| 127 | my $remaining = $cl; | ||
| 128 | while ( $remaining > 0 ) { | ||
| 129 | my $chunk = ''; | ||
| 130 | my $read = $in->read( $chunk, $remaining ); | ||
| 131 | return $body unless defined $read && $read > 0; | ||
| 132 | $body .= $chunk; | ||
| 133 | $remaining -= $read; | ||
| 134 | } | ||
| 135 | return $body; | ||
| 136 | } | ||
| 137 | |||
| 138 | # Header lookup by the spec's spelling: maps the name to the PSGI env key | ||
| 139 | # (HTTP_ + uppercased, dashes to underscores). PSGI servers already normalise | ||
| 140 | # header names that way, which is what makes this case-insensitive in | ||
| 141 | # practice; there is no fallback scan of other env keys. | ||
| 142 | sub _lookup_psgi_header { | ||
| 143 | my ( $env, $name ) = @_; | ||
| 144 | my $psgi_key = 'HTTP_' . uc $name; | ||
| 145 | $psgi_key =~ tr/-/_/; | ||
| 146 | return $env->{$psgi_key}; | ||
| 147 | } | ||
| 148 | |||
| 149 | sub _check_origin { | ||
| 150 | my ( $self, $env ) = @_; | ||
| 151 | |||
| 152 | my $set = $self->{origin_allow_set}; | ||
| 153 | return undef unless $set && keys %$set; | ||
| 154 | |||
| 155 | my $origin = $env->{HTTP_ORIGIN}; | ||
| 156 | return undef unless defined $origin && length $origin; | ||
| 157 | |||
| 158 | return undef if $set->{$origin}; | ||
| 159 | return $self->_origin_blocked_response(); | ||
| 160 | } | ||
| 161 | |||
| 162 | sub _origin_blocked_response { | ||
| 163 | my ( $self ) = @_; | ||
| 164 | my $body = encode_json({ | ||
| 165 | jsonrpc => '2.0', | ||
| 166 | id => undef, | ||
| 167 | error => { | ||
| 168 | code => -32600, | ||
| 169 | message => 'Forbidden: invalid Origin', | ||
| 170 | }, | ||
| 171 | }); | ||
| 172 | return [ | ||
| 173 | 403, | ||
| 174 | [ | ||
| 175 | 'Content-Type' => 'application/json', | ||
| 176 | 'Content-Length' => length($body), | ||
| 177 | ], | ||
| 178 | [$body], | ||
| 179 | ]; | ||
| 180 | } | ||
| 181 | |||
| 182 | # The PSGI entry point (private) — one call per HTTP request. Exposed | ||
| 183 | # mostly for tests that want to feed canned %env hashes around to_app. | ||
| 184 | sub _handle_request { | ||
| 185 | my ( $self, $env ) = @_; | ||
| 186 | |||
| 187 | # Anything not on the configured MCP endpoint is a 404. A real server | ||
| 188 | # might also host a management UI or health check; this one does not. | ||
| 189 | my $path = $env->{PATH_INFO} // '/'; | ||
| 190 | $path = '/' . $path unless $path =~ m{^/}; | ||
| 191 | return $self->_not_found_response() unless $path eq $self->{path}; | ||
| 192 | |||
| 193 | # Origin is checked on every request, including GET/DELETE — the spec's | ||
| 194 | # DNS-rebinding guard isn't only about POST. | ||
| 195 | if ( my $err = $self->_check_origin($env) ) { | ||
| 196 | return $err; | ||
| 197 | } | ||
| 198 | |||
| 199 | my $method = $env->{REQUEST_METHOD} // 'GET'; | ||
| 200 | |||
| 201 | # Per the 2026-07-28 spec, the only client-server methods this revision | ||
| 202 | # binds to the MCP endpoint are POST and GET on /mcp. GET is the legacy | ||
| 203 | # stream-open hook that 2025-03-26..2025-11-25 servers used, and this | ||
| 204 | # revision dropped it — answering 405 makes the era difference visible. | ||
| 205 | unless ( $method eq 'POST' || $method eq 'GET' || $method eq 'DELETE' ) { | ||
| 206 | return $self->_method_not_allowed_response(); | ||
| 207 | } | ||
| 208 | |||
| 209 | if ( $method eq 'GET' || $method eq 'DELETE' ) { | ||
| 210 | return $self->_method_not_allowed_response(); | ||
| 211 | } | ||
| 212 | |||
| 213 | # Content-Type MUST be application/json. Anything else (text/plain, | ||
| 214 | # multipart/form-data, an empty body with a notification) is a client | ||
| 215 | # error we surface immediately rather than waste a parse on. | ||
| 216 | my $ct = $env->{CONTENT_TYPE} // ''; | ||
| 217 | unless ( $ct =~ m{^application/json\b}i ) { | ||
| 218 | return $self->_json_rpc_error_response( | ||
| 219 | -32700, 'Content-Type must be application/json', undef, | ||
| 220 | ); | ||
| 221 | } | ||
| 222 | |||
| 223 | my $body = _read_body($env); | ||
| 224 | my $request = eval { decode_json($body) }; | ||
| 225 | if ( $@ || ref $request ne 'HASH' ) { | ||
| 226 | return $self->_json_rpc_error_response( | ||
| 227 | -32700, 'Parse error', undef, | ||
| 228 | ); | ||
| 229 | } | ||
| 230 | |||
| 231 | # A notification (no id) is accepted and discarded; the spec calls for | ||
| 232 | # 202 Accepted with no body. The 2026-07-28 spec explicitly notes that | ||
| 233 | # "header requirements for notification POSTs are not defined by this | ||
| 234 | # revision", so we skip the full header validation path here. | ||
| 235 | if ( !defined $request->{id} ) { | ||
| 236 | $self->server->handle($request); | ||
| 237 | return $self->_accepted_response(); | ||
| 238 | } | ||
| 239 | |||
| 240 | if ( my $err = $self->_validate_headers($env, $request) ) { | ||
| 241 | return $err; | ||
| 242 | } | ||
| 243 | |||
| 244 | # subscriptions/listen has no server->client push channel to deliver | ||
| 245 | # *ListChanged in 0.002, so it falls through to handle() and gets the | ||
| 246 | # normal -32601 — the same answer the Stdio transport gives. Real push | ||
| 247 | # delivery is deferred to k24. | ||
| 248 | |||
| 249 | # Default: synchronous JSON-RPC dispatch. handle() returns either a | ||
| 250 | # response hashref or undef (the no-id case we already handled above | ||
| 251 | # doesn't reach here, so undef here would be a malformed request — | ||
| 252 | # treat it as such). | ||
| 253 | my $response = $self->server->handle($request); | ||
| 254 | if ( !$response ) { | ||
| 255 | return $self->_json_rpc_error_response( | ||
| 256 | -32600, 'Invalid request', $request->{id}, | ||
| 257 | ); | ||
| 258 | } | ||
| 259 | |||
| 260 | # The client's Accept governs whether we wrap as JSON or as SSE. The | ||
| 261 | # spec gives the server the choice per request, and clients that send | ||
| 262 | # both content types leave it free. We pick the one the client says it | ||
| 263 | # can handle; absent Accept, default to application/json. | ||
| 264 | my $accept = $env->{HTTP_ACCEPT} // ''; | ||
| 265 | my $sse = $accept =~ m{text/event-stream}i; | ||
| 266 | |||
| 267 | if ( $sse && ( $response->{error} || !$response->{result} ) ) { | ||
| 268 | # Errors and notifications don't naturally stream; SSE alone won't | ||
| 269 | # carry a JSON-RPC error in any spec-mandated way. Stay on JSON. | ||
| 270 | $sse = 0; | ||
| 271 | } | ||
| 272 | |||
| 273 | if ( $sse ) { | ||
| 274 | return $self->_handle_sse_stream($env, $request, $response); | ||
| 275 | } | ||
| 276 | |||
| 277 | # A spec-mandated JSON-RPC error takes its matching HTTP status (404 for | ||
| 278 | # method-not-found, 400 for a protocol/version parity error); everything | ||
| 279 | # else stays 200 with the payload in the body. Error responses never | ||
| 280 | # reach the SSE branch above - the downgrade already forced $sse off. | ||
| 281 | return $self->_json_response( | ||
| 282 | $response, | ||
| 283 | $self->_http_status_for_response($response), | ||
| 284 | ); | ||
| 285 | } | ||
| 286 | |||
| 287 | # --- Header validation per spec section "Server Validation" ------------- | ||
| 288 | |||
| 289 | sub _validate_headers { | ||
| 290 | my ( $self, $env, $request ) = @_; | ||
| 291 | |||
| 292 | # MCP-Protocol-Version: derived from the body's | ||
| 293 | # _meta.io.modelcontextprotocol/protocolVersion; missing or mismatched | ||
| 294 | # is a HeaderMismatch. | ||
| 295 | my $protocol_header = _lookup_psgi_header($env, $PROTOCOL_HEADER); | ||
| 296 | unless ( defined $protocol_header && length $protocol_header ) { | ||
| 297 | return $self->_header_mismatch( | ||
| 298 | "$PROTOCOL_HEADER header is required", | ||
| 299 | $request->{id}, | ||
| 300 | ); | ||
| 301 | } | ||
| 302 | my $body_version = $self->_meta_field($request, 'io.modelcontextprotocol/protocolVersion'); | ||
| 303 | unless ( defined $body_version && length $body_version ) { | ||
| 304 | return $self->_json_rpc_error_response( | ||
| 305 | -32602, | ||
| 306 | 'Invalid params: missing io.modelcontextprotocol/protocolVersion', | ||
| 307 | $request->{id}, | ||
| 308 | ); | ||
| 309 | } | ||
| 310 | unless ( $protocol_header eq $body_version ) { | ||
| 311 | return $self->_header_mismatch( | ||
| 312 | "$PROTOCOL_HEADER header '$protocol_header' does not match " | ||
| 313 | . "body '$body_version'", | ||
| 314 | $request->{id}, | ||
| 315 | ); | ||
| 316 | } | ||
| 317 | |||
| 318 | # io.modelcontextprotocol/clientCapabilities: the spec requires it to be | ||
| 319 | # present in params._meta on every request; its value is not inspected, | ||
| 320 | # so a JSON null satisfies the check. This presence test lives here in | ||
| 321 | # the HTTP transport - not in the shared handle() - so a missing required | ||
| 322 | # field is rejected with the spec's 400 Bad Request, while the -32602 | ||
| 323 | # handle() itself can still return (an unknown tool/resource/prompt name) | ||
| 324 | # remains an application-level error on HTTP 200. | ||
| 325 | unless ( | ||
| 326 | $self->_meta_has( $request, 'io.modelcontextprotocol/clientCapabilities' ) | ||
| 327 | ) { | ||
| 328 | return $self->_json_rpc_error_response( | ||
| 329 | -32602, | ||
| 330 | 'Invalid params: missing io.modelcontextprotocol/clientCapabilities', | ||
| 331 | $request->{id}, | ||
| 332 | ); | ||
| 333 | } | ||
| 334 | |||
| 335 | # Mcp-Method: mirrors method. | ||
| 336 | my $method_header = _lookup_psgi_header($env, $METHOD_HEADER); | ||
| 337 | unless ( defined $method_header && length $method_header ) { | ||
| 338 | return $self->_header_mismatch( | ||
| 339 | "$METHOD_HEADER header is required", | ||
| 340 | $request->{id}, | ||
| 341 | ); | ||
| 342 | } | ||
| 343 | my $body_method = $request->{method}; | ||
| 344 | unless ( defined $body_method && length $body_method ) { | ||
| 345 | return $self->_json_rpc_error_response( | ||
| 346 | -32600, 'Missing JSON-RPC method', $request->{id}, | ||
| 347 | ); | ||
| 348 | } | ||
| 349 | unless ( $method_header eq $body_method ) { | ||
| 350 | return $self->_header_mismatch( | ||
| 351 | "$METHOD_HEADER header '$method_header' does not match body", | ||
| 352 | $request->{id}, | ||
| 353 | ); | ||
| 354 | } | ||
| 355 | |||
| 356 | # Mcp-Name: required for tools/call, resources/read, prompts/get. | ||
| 357 | my $name_param = $NAME_PARAM{ $body_method }; | ||
| 358 | if ( $name_param ) { | ||
| 359 | my $name_header = _lookup_psgi_header($env, $NAME_HEADER); | ||
| 360 | unless ( defined $name_header && length $name_header ) { | ||
| 361 | return $self->_header_mismatch( | ||
| 362 | "$NAME_HEADER header is required for $body_method", | ||
| 363 | $request->{id}, | ||
| 364 | ); | ||
| 365 | } | ||
| 366 | |||
| 367 | my $body_params = ref $request->{params} eq 'HASH' ? $request->{params} : {}; | ||
| 368 | my $body_name = $body_params->{$name_param}; | ||
| 369 | unless ( defined $body_name && length $body_name ) { | ||
| 370 | return $self->_json_rpc_error_response( | ||
| 371 | -32602, | ||
| 372 | "Invalid params: missing params.$name_param", | ||
| 373 | $request->{id}, | ||
| 374 | ); | ||
| 375 | } | ||
| 376 | |||
| 377 | my $decoded_name = $self->_decode_header($name_header); | ||
| 378 | unless ( defined $decoded_name && $decoded_name eq $body_name ) { | ||
| 379 | return $self->_header_mismatch( | ||
| 380 | "$NAME_HEADER header value does not match body " | ||
| 381 | . "params.$name_param", | ||
| 382 | $request->{id}, | ||
| 383 | ); | ||
| 384 | } | ||
| 385 | } | ||
| 386 | |||
| 387 | # Mcp-Param-{Name}: only meaningful for tools/call. The spec names these | ||
| 388 | # via x-mcp-header annotations in the tool's inputSchema, which the | ||
| 389 | # server's registry holds. Two rules: | ||
| 390 | # 1. an annotated property that carries a non-null value in | ||
| 391 | # params.arguments MUST have its Mcp-Param-{Name} header; | ||
| 392 | # 2. every Mcp-Param-* header present must match the argument it names | ||
| 393 | # (the annotated property, else an argument of that very name). | ||
| 394 | if ( $body_method eq 'tools/call' ) { | ||
| 395 | my $params = ref $request->{params} eq 'HASH' ? $request->{params} : {}; | ||
| 396 | my $arguments = ref $params->{arguments} eq 'HASH' ? $params->{arguments} : {}; | ||
| 397 | |||
| 398 | # Unknown tool: no schema check; handle() answers -32602 as before. | ||
| 399 | my $tool = ( defined $params->{name} && !ref $params->{name} ) | ||
| 400 | ? $self->server->find_tool( $params->{name} ) | ||
| 401 | : undef; | ||
| 402 | my @annotated = $tool ? @{ $self->_header_params( $tool->{inputSchema} ) } : (); | ||
| 403 | my %by_header = map { lc $_->{name} => $_ } reverse @annotated; | ||
| 404 | |||
| 405 | for my $param (@annotated) { | ||
| 406 | my $value = _arg_value( $arguments, $param->{path} ); | ||
| 407 | next unless defined $value; | ||
| 408 | my $header = _lookup_psgi_header( $env, $PARAM_HEADER_PREFIX . $param->{name} ); | ||
| 409 | unless ( defined $header ) { | ||
| 410 | return $self->_header_mismatch( | ||
| 411 | "$PARAM_HEADER_PREFIX$param->{name} header is required", | ||
| 412 | $request->{id}, | ||
| 413 | ); | ||
| 414 | } | ||
| 415 | } | ||
| 416 | |||
| 417 | # HTTP field names are case-insensitive (RFC 9110) and tool authors | ||
| 418 | # are free to annotate a JSON property `region` with x-mcp-header | ||
| 419 | # "Region", so the body-side lookup has to follow. | ||
| 420 | my %lc_args = map { lc $_ => $_ } keys %$arguments; | ||
| 421 | |||
| 422 | for my $key ( sort keys %{$env} ) { | ||
| 423 | next unless $key =~ m{^HTTP_MCP_PARAM_(.+)$}; | ||
| 424 | my $arg_name = $1; | ||
| 425 | $arg_name =~ tr/_/-/; | ||
| 426 | my $header_value = $env->{$key}; | ||
| 427 | |||
| 428 | my ( $body_value, $body_label, $type ); | ||
| 429 | if ( my $param = $by_header{ lc $arg_name } ) { | ||
| 430 | $body_value = _arg_value( $arguments, $param->{path} ); | ||
| 431 | $body_label = join '.', @{ $param->{path} }; | ||
| 432 | $type = $param->{type}; | ||
| 433 | } | ||
| 434 | else { | ||
| 435 | my $body_key = $lc_args{ lc $arg_name }; | ||
| 436 | unless ($body_key) { | ||
| 437 | return $self->_header_mismatch( | ||
| 438 | "$PARAM_HEADER_PREFIX$arg_name header set but body " | ||
| 439 | . "has no arguments.$arg_name", | ||
| 440 | $request->{id}, | ||
| 441 | ); | ||
| 442 | } | ||
| 443 | $body_value = $arguments->{$body_key}; | ||
| 444 | $body_label = $body_key; | ||
| 445 | } | ||
| 446 | |||
| 447 | my $decoded = $self->_decode_header($header_value); | ||
| 448 | unless ( | ||
| 449 | defined $decoded | ||
| 450 | && $self->_header_value_matches( $decoded, $body_value, $type ) | ||
| 451 | ) { | ||
| 452 | return $self->_header_mismatch( | ||
| 453 | "$PARAM_HEADER_PREFIX$arg_name header value does not " | ||
| 454 | . "match body arguments.$body_label", | ||
| 455 | $request->{id}, | ||
| 456 | ); | ||
| 457 | } | ||
| 458 | } | ||
| 459 | } | ||
| 460 | |||
| 461 | return undef; | ||
| 462 | } | ||
| 463 | |||
| 464 | sub _meta_field { | ||
| 465 | my ( $self, $request, $name ) = @_; | ||
| 466 | my $params = ref $request->{params} eq 'HASH' ? $request->{params} : {}; | ||
| 467 | my $meta = ref $params->{_meta} eq 'HASH' ? $params->{_meta} : {}; | ||
| 468 | return $meta->{$name}; | ||
| 469 | } | ||
| 470 | |||
| 471 | # Presence-only companion to _meta_field: a required _meta key whose value is | ||
| 472 | # not otherwise inspected (a JSON null is a legitimate value) is checked with | ||
| 473 | # exists, not truthiness. | ||
| 474 | sub _meta_has { | ||
| 475 | my ( $self, $request, $name ) = @_; | ||
| 476 | my $params = ref $request->{params} eq 'HASH' ? $request->{params} : {}; | ||
| 477 | my $meta = ref $params->{_meta} eq 'HASH' ? $params->{_meta} : {}; | ||
| 478 | return exists $meta->{$name}; | ||
| 479 | } | ||
| 480 | |||
| 481 | # Decodes a Mcp-Name / Mcp-Param-* header. A value wrapped in the | ||
| 482 | # =?base64?...?= sentinel is decoded from Base64 of UTF-8; everything else | ||
| 483 | # is returned as-is. A value that looks like the sentinel but doesn't | ||
| 484 | # actually decode is flagged as an invalid header. | ||
| 485 | sub _decode_header { | ||
| 486 | my ( $self, $value ) = @_; | ||
| 487 | |||
| 488 | if ( $value =~ /\A=\?base64\?(.*)\?=\z/s ) { | ||
| 489 | my $raw = $1; | ||
| 490 | my $bytes = eval { decode_base64($raw) }; | ||
| 491 | return undef unless defined $bytes && length $bytes; | ||
| 492 | my $decoded = eval { decode('UTF-8', $bytes, FB_DEFAULT) }; | ||
| 493 | return $decoded unless $@; | ||
| 494 | return undef; | ||
| 495 | } | ||
| 496 | |||
| 497 | return $value; | ||
| 498 | } | ||
| 499 | |||
| 500 | # Compares a decoded Mcp-Param-{Name} header against the body argument it | ||
| 501 | # mirrors, honouring the wire encoding the spec (and the sibling client's | ||
| 502 | # _header_value) uses. A raw `eq` mishandled the non-string JSON types: | ||
| 503 | # - a JSON boolean stringifies to "1"/"" in Perl but is carried on the wire | ||
| 504 | # as lowercase 'true'/'false', so it is compared against those words; | ||
| 505 | # - a JSON number is carried as its decimal string and compared *numerically* | ||
| 506 | # ("42" and "42.0" agree), with a non-numeric header rejected up front; | ||
| 507 | # - everything else (plain strings, an undef / JSON-null body) falls back | ||
| 508 | # to `eq`. | ||
| 509 | # Without a declared type, a JSON string that merely looks numeric (e.g. "42") | ||
| 510 | # is indistinguishable from a JSON number at the Perl level, so it takes the | ||
| 511 | # numeric path; with the schema's declared type 'string' it compares as a | ||
| 512 | # string, while a declared integer keeps the numeric leniency. | ||
| 513 | sub _header_value_matches { | ||
| 514 | my ( $self, $header_decoded, $body_value, $type ) = @_; | ||
| 515 | |||
| 516 | # A null or missing body value compares as the empty string, as the | ||
| 517 | # final `eq` always has; stated explicitly so it does not warn. | ||
| 518 | $body_value = '' unless defined $body_value; | ||
| 519 | |||
| 520 | if ( JSON::MaybeXS::is_bool($body_value) ) { | ||
| 521 | return $header_decoded eq ( $body_value ? 'true' : 'false' ); | ||
| 522 | } | ||
| 523 | |||
| 524 | # A declared string is a string, whatever it looks like: "42" vs "42.0" | ||
| 525 | # differ. Only the schema's type can tell, so it is passed in when known. | ||
| 526 | if ( defined $type && $type eq 'string' && !ref $body_value ) { | ||
| 527 | return "$header_decoded" eq "$body_value"; | ||
| 528 | } | ||
| 529 | |||
| 530 | if ( !ref $body_value && looks_like_number($body_value) ) { | ||
| 531 | return unless looks_like_number($header_decoded); | ||
| 532 | return $header_decoded == $body_value; | ||
| 533 | } | ||
| 534 | |||
| 535 | return "$header_decoded" eq "$body_value"; | ||
| 536 | } | ||
| 537 | |||
| 538 | # The properties of an inputSchema annotated with x-mcp-header, reachable | ||
| 539 | # from the root through a chain of "properties" keys only (never items, | ||
| 540 | # oneOf/anyOf/allOf/not, if/then/else or $ref). Same walk as the client's | ||
| 541 | # _header_params. Returns [ { name, path => [...], type } ]. | ||
| 542 | sub _header_params { | ||
| 543 | my ( $self, $schema, $path ) = @_; | ||
| 544 | $path //= []; | ||
| 545 | |||
| 546 | return [] unless ref $schema eq 'HASH' && ref $schema->{properties} eq 'HASH'; | ||
| 547 | |||
| 548 | my @params; | ||
| 549 | for my $key ( sort keys %{ $schema->{properties} } ) { | ||
| 550 | my $property = $schema->{properties}{$key}; | ||
| 551 | next unless ref $property eq 'HASH'; | ||
| 552 | |||
| 553 | my @next = ( @$path, $key ); | ||
| 554 | push @params, { | ||
| 555 | name => $property->{'x-mcp-header'}, | ||
| 556 | path => \@next, | ||
| 557 | type => $property->{type}, | ||
| 558 | } if defined $property->{'x-mcp-header'} && !ref $property->{'x-mcp-header'}; | ||
| 559 | push @params, @{ $self->_header_params( $property, \@next ) }; | ||
| 560 | } | ||
| 561 | |||
| 562 | return \@params; | ||
| 563 | } | ||
| 564 | |||
| 565 | # The argument value at a property path, or undef when absent or null. | ||
| 566 | sub _arg_value { | ||
| 567 | my ( $arguments, $path ) = @_; | ||
| 568 | |||
| 569 | my $value = $arguments; | ||
| 570 | for my $key (@$path) { | ||
| 571 | return undef unless ref $value eq 'HASH'; | ||
| 572 | $value = $value->{$key}; | ||
| 573 | } | ||
| 574 | return $value; | ||
| 575 | } | ||
| 576 | |||
| 577 | sub _header_mismatch { | ||
| 578 | my ( $self, $message, $id ) = @_; | ||
| 579 | return $self->_json_rpc_error_response( | ||
| 580 | -32020, "Header mismatch: $message", $id, | ||
| 581 | ); | ||
| 582 | } | ||
| 583 | |||
| 584 | sub _json_rpc_error_response { | ||
| 585 | my ( $self, $code, $message, $id, $data ) = @_; | ||
| 586 | my $err = { code => $code, message => $message }; | ||
| 587 | $err->{data} = $data if defined $data; | ||
| 588 | my $body = encode_json({ | ||
| 589 | jsonrpc => '2.0', | ||
| 590 | id => $id, | ||
| 591 | error => $err, | ||
| 592 | }); | ||
| 593 | return [ | ||
| 594 | 400, | ||
| 595 | [ | ||
| 596 | 'Content-Type' => 'application/json', | ||
| 597 | 'Content-Length' => length($body), | ||
| 598 | ], | ||
| 599 | [$body], | ||
| 600 | ]; | ||
| 601 | } | ||
| 602 | |||
| 603 | sub _json_response { | ||
| 604 | my ( $self, $response, $status ) = @_; | ||
| 605 | $status //= 200; | ||
| 606 | my $body = encode_json($response); | ||
| 607 | return [ | ||
| 608 | $status, | ||
| 609 | [ | ||
| 610 | 'Content-Type' => 'application/json', | ||
| 611 | 'Content-Length' => length($body), | ||
| 612 | ], | ||
| 613 | [$body], | ||
| 614 | ]; | ||
| 615 | } | ||
| 616 | |||
| 617 | # Maps a JSON-RPC error response from handle() to the HTTP status the | ||
| 618 | # 2026-07-28 spec mandates. Only two error classes carry a non-200 status: | ||
| 619 | # -32601 (method not found) -> 404 | ||
| 620 | # -32020/-32021/-32022 (parity/version) -> 400 | ||
| 621 | # Everything else - a -32602 for an unknown tool/resource/prompt, a -32603 | ||
| 622 | # internal error - stays 200 with the JSON-RPC error in the body, since the | ||
| 623 | # request reached a real method and failed at the application level. | ||
| 624 | sub _http_status_for_response { | ||
| 625 | my ( $self, $response ) = @_; | ||
| 626 | return 200 | ||
| 627 | unless ref $response eq 'HASH' && ref $response->{error} eq 'HASH'; | ||
| 628 | my $code = $response->{error}{code}; | ||
| 629 | return 200 unless defined $code; | ||
| 630 | return 404 if $code == -32601; | ||
| 631 | return 400 if $code == -32020 || $code == -32021 || $code == -32022; | ||
| 632 | return 200; | ||
| 633 | } | ||
| 634 | |||
| 635 | sub _accepted_response { | ||
| 636 | return [ | ||
| 637 | 202, | ||
| 638 | [ | ||
| 639 | 'Content-Length' => 0, | ||
| 640 | ], | ||
| 641 | [''], | ||
| 642 | ]; | ||
| 643 | } | ||
| 644 | |||
| 645 | sub _not_found_response { | ||
| 646 | my $body = ''; | ||
| 647 | return [ | ||
| 648 | 404, | ||
| 649 | [ | ||
| 650 | 'Content-Type' => 'text/plain', | ||
| 651 | 'Content-Length' => 0, | ||
| 652 | ], | ||
| 653 | [$body], | ||
| 654 | ]; | ||
| 655 | } | ||
| 656 | |||
| 657 | sub _method_not_allowed_response { | ||
| 658 | return [ | ||
| 659 | 405, | ||
| 660 | [ | ||
| 661 | 'Allow' => 'POST', | ||
| 662 | 'Content-Length' => 0, | ||
| 663 | ], | ||
| 664 | [''], | ||
| 665 | ]; | ||
| 666 | } | ||
| 667 | |||
| 668 | # --- SSE response path ---------------------------------------------------- | ||
| 669 | |||
| 670 | # A successful request that the client wants as SSE arrives here. We emit | ||
| 671 | # the JSON-RPC response as the single SSE event so the client gets its | ||
| 672 | # answer in the stream form it asked for; the stream is closed afterwards. | ||
| 673 | # There is no keepalive: the single event is written and the stream closed | ||
| 674 | # in the same call. | ||
| 675 | sub _handle_sse_stream { | ||
| 676 | my ( $self, $env, $request, $response ) = @_; | ||
| 677 | my $jsonrpc = encode_json($response); | ||
| 678 | |||
| 679 | return sub { | ||
| 680 | my ( $respond ) = @_; | ||
| 681 | my $writer = $respond->([ | ||
| 682 | 200, | ||
| 683 | $self->_sse_headers, | ||
| 684 | ]); | ||
| 685 | $writer->write( $self->_format_sse_event( '', $jsonrpc ) ); | ||
| 686 | $writer->close; | ||
| 687 | return; | ||
| 688 | }; | ||
| 689 | } | ||
| 690 | |||
| 691 | sub _sse_headers { | ||
| 692 | return [ | ||
| 693 | 'Content-Type' => 'text/event-stream', | ||
| 694 | 'X-Accel-Buffering' => 'no', | ||
| 695 | 'Cache-Control' => 'no-cache', | ||
| 696 | 'Connection' => 'keep-alive', | ||
| 697 | ]; | ||
| 698 | } | ||
| 699 | |||
| 700 | # Formats a single SSE event. data lines prefix each line of the JSON | ||
| 701 | # with "data: " per the spec; the event terminator is a blank line. | ||
| 702 | sub _format_sse_event { | ||
| 703 | my ( $self, $event_name, $data ) = @_; | ||
| 704 | |||
| 705 | my @lines; | ||
| 706 | if ( defined $event_name && length $event_name ) { | ||
| 707 | push @lines, "event: $event_name"; | ||
| 708 | } | ||
| 709 | my $payload = defined $data ? $data : ''; | ||
| 710 | for my $line ( split /\r?\n/, $payload, -1 ) { | ||
| 711 | push @lines, "data: $line"; | ||
| 712 | } | ||
| 713 | # The trailing blank line that terminates the event. | ||
| 714 | return join("\n", @lines, '') . "\n"; | ||
| 715 | } | ||
| 716 | |||
| 717 | 1; | ||
| 718 | |||
| 719 | __END__ | ||