=head1 NAME AnyEvent::MCP::Server::HTTP - an optional MCP HTTP listener and socket handler =head1 DESCRIPTION A subclass of L implementing ordinary HTTP POST request/response. It can listen itself, or accept sockets from an existing listener. Applications with their own HTTP parser can use Server directly. This initial implementation uses JSON responses and drops notifications; SSE and subscriptions are not implemented. Requests on one connection are dispatched in sequence, preserving HTTP response order. Other connections are independent. Request bodies require Content-Length; chunked requests are not implemented yet. The server does not assign protocol sessions. Legacy clients use the 2025 request/response subset. =head1 METHODS =head2 $server = AnyEvent::MCP::Server::HTTP->new (%config) Construction does not start a listener. In addition to Server options, the following configuration options are supported: =over 4 =item host => $host The listening address, defaulting to C<127.0.0.1>. =item port => $port The listening port, defaulting to zero for an automatically assigned port. =item path => $path The MCP endpoint path, defaulting to C. Bearer and Basic authentication use C<$path> directly; URL cookies prefix it with C. =item connection_close => $boolean When true, disables persistent connections, sends C and closes the socket after draining each response. Defaults to false. This is useful when an existing listener routes sockets by their first request and cannot route subsequent requests independently. =item max_size => $bytes Limits incoming headers and request bodies, defaulting to 1 MiB. =item origins => [$origin...] Allowed Origin header values. Defaults to an empty array: requests with an Origin header are rejected, while requests without one are accepted. C<["*"]> permits any origin. Allowed origins receive CORS response headers, and configured origins enable OPTIONS preflight for POST. Preflight does not require authentication; the subsequent POST still does. =item handle => { %handle } AnyEvent::Handle constructor options, such as C, C, C or C. The socket and the read/error/EOF handlers belong to this class. =item cookie => $token Authenticates requests using C followed by the configured C. Cookie credentials are URL path components, not HTTP cookies. =item bearer => $token Authenticates requests using an C header. =item users => { $username => $password, ... } Basic authentication users and passwords. An empty hash permits no Basic users. C can alternatively be an array of allowed usernames, or a comma-separated configuration string. Their Basic passwords are derived from the global secret and C, which is required for this form. C prints the matching password. =item name => $name Loads C, C, C, C, C, C, C and C defaults from C<[server NAME]>. Explicit constructor arguments override them. Without C no global configuration is read. =item url_host => $hostname Overrides the advertised hostname, for example when listening on a wildcard address. Otherwise a wildcard uses the nodename from C. =item url_scheme => $scheme Overrides the advertised scheme; otherwise TLS handle options select C, and plain handles select C. =back Any configured authentication method can authenticate the request. Omitting C, C and C leaves authentication to the embedding application. Explicitly undefined options disable that method. Cookie URLs are also accepted when using bearer or Basic authentication. =head2 $url = $server->url ($with_cookie) Returns the advertised URL with the actual listening port. C<$with_cookie> defaults to true, including the URL cookie when configured. Pass false for the clean URL to use with a bearer token or Basic authentication. The port must be known. Wildcard hostname resolution and reverse-proxy routing remain the caller's responsibility. =head2 $server->listen ($host, $port, %handle) Starts a listener, replacing any previous listener. Omitted arguments use the configured host and port. The actual bound port is stored in C<< $server->{port} >>, including when requesting an ephemeral port. C<%handle> overrides the configured C options for connections accepted by this listener. =head2 $handle = $server->accept ($socket, %handle) Starts handling an already accepted socket. The server takes ownership of C<$socket>. No listener is needed. C<%handle> overrides the configured C options for this connection. =head2 $server->close Stops listening, closes accepted sockets and cancels outstanding requests. The same object can subsequently listen or accept again. =head1 EVENTS =head2 on_connection_error => $callback->($server, $handle, $message) Called for socket errors before closing the connection. =head2 on_close => $callback->($server) Called once after C stops the listener and closes all connections. Calling C or C again starts a new lifetime. =cut package AnyEvent::MCP::Server::HTTP; use common::sense; use parent "AnyEvent::MCP::Server"; use AnyEvent::Handle (); use AnyEvent::Socket (); use HTTP::Parser::XS (); use JSON::XS (); use MIME::Base64 (); use Scalar::Util qw(weaken); use POSIX (); sub new { my ($class, %kv) = @_; if (defined $kv{name}) { require AnyEvent::MCP::Config; my $settings = AnyEvent::MCP::Config->global->{section}{"server $kv{name}"} || {}; %kv = ( (map { exists $settings->{$_} ? ($_ => $settings->{$_}) : () } qw(host port path url_host url_scheme cookie bearer users)), %kv, ); } if (defined $kv{users} && ref $kv{users} ne "HASH") { die "Derived Basic users require a server name\n" unless defined $kv{name}; require AnyEvent::MCP::Config; my $config = AnyEvent::MCP::Config->global; my @users = ref $kv{users} eq "ARRAY" ? @{$kv{users}} : split /\s*,\s*/, $kv{users}; $kv{users} = { map { $_ => $config->credential ("basic", $kv{name}, $_) } @users }; } $class->SUPER::new (host => "127.0.0.1", port => 0, path => "/mcp/", origins => [], %kv) } sub listen { my ($self, $host, $port, %handle) = @_; delete $self->{_closed}; $host = $self->{host} unless defined $host; $port = $self->{port} unless defined $port; $self->{listen_host} = $host; $self->{listen_handle} = { %{$self->{handle} || {}}, %handle }; delete $self->{listener}; weaken $self; $self->{listener} = AnyEvent::Socket::tcp_server $host, $port, sub { $self->accept ($_[0], %handle) if $self; }, sub { $self->{port} = $_[2] if $self; () }; } sub _cookie_path { my ($self) = @_; my $cookie = AnyEvent::MCP::utf8enc $self->{cookie}; $cookie =~ s/([^A-Za-z0-9_.~-])/sprintf "%%%02X", ord $1/ge; "/$cookie$self->{path}" } sub url { my ($self, $with_cookie) = @_; $with_cookie = 1 unless defined $with_cookie; my $host = $self->{url_host} || (defined $self->{listen_host} ? $self->{listen_host} : $self->{host}); $host = (POSIX::uname)[1] if !length $host || $host eq "0.0.0.0" || $host eq "::"; $host = "[$host]" if $host =~ /:/ && $host !~ /\A\[/; my $port = $self->{port} or die "HTTP port is not known\n"; my $scheme = $self->{url_scheme} || (($self->{listen_handle} || $self->{handle} || {})->{tls} ? "https" : "http"); my $path = $with_cookie && defined $self->{cookie} ? $self->_cookie_path : $self->{path}; "$scheme://$host:$port$path" } sub accept { my ($self, $socket, %handle) = @_; delete $self->{_closed}; weaken $self; my $handle = AnyEvent::Handle->new ( rbuf_max => $self->{max_size} || 1024 * 1024, %{$self->{handle}}, %handle, fh => $socket, on_read => undef, on_error => sub { $self->event (connection_error => $_[0], $_[2]) if $self; $self->_close ($_[0]) if $self; }, on_eof => sub { $self->_close ($_[0]) if $self }, ); $handle->{mcp_peer} = {}; $self->{connections}{$handle} = $handle; $self->_read ($handle); $handle } sub _read { my ($self, $handle) = @_; weaken $self; $handle->push_read (line => "\r\n\r\n", sub { my ($handle, $header) = @_; return unless $self; my $parsed = HTTP::Parser::XS::parse_http_request ($header . "\r\n\r\n", \my %env); $handle->{mcp_close} = $self->{connection_close} || $env{SERVER_PROTOCOL} ne "HTTP/1.1" || $env{HTTP_CONNECTION} =~ /\bclose\b/i; $env{CONTENT_LENGTH} = 0 unless defined $env{CONTENT_LENGTH}; return $self->_respond ($handle, 400, "Bad Request", "") if $parsed < 0 || exists $env{HTTP_TRANSFER_ENCODING} || $env{CONTENT_LENGTH} !~ /\A[0-9]+\z/; return $self->_respond ($handle, 413, "Content Too Large", "") if $env{CONTENT_LENGTH} > ($self->{max_size} || 1024 * 1024); if ($env{HTTP_EXPECT}) { return $self->_respond ($handle, 417, "Expectation Failed", "") unless lc $env{HTTP_EXPECT} eq "100-continue"; $handle->push_write ("HTTP/1.1 100 Continue\r\n\r\n"); } $handle->push_read (chunk => $env{CONTENT_LENGTH}, sub { my ($handle, $body) = @_; $self->_request ($handle, \%env, $body) if $self; }); }); } sub _request { my ($self, $handle, $env, $body) = @_; delete $handle->{mcp_origin}; my $cookie_path = defined $self->{cookie} && $env->{REQUEST_URI} eq $self->_cookie_path; return $self->_respond ($handle, 404, "Not Found", "") unless $env->{REQUEST_URI} eq $self->{path} || $cookie_path; if (exists $env->{HTTP_ORIGIN}) { my $wildcard = grep $_ eq "*", @{$self->{origins}}; return $self->_respond ($handle, 403, "Forbidden", "") unless $wildcard || grep $_ eq $env->{HTTP_ORIGIN}, @{$self->{origins}}; $handle->{mcp_origin} = $wildcard ? "*" : $env->{HTTP_ORIGIN}; } if ($env->{REQUEST_METHOD} eq "OPTIONS" && @{$self->{origins}}) { return $self->_respond ($handle, 405, "Method Not Allowed", "") if exists $env->{HTTP_ACCESS_CONTROL_REQUEST_METHOD} && $env->{HTTP_ACCESS_CONTROL_REQUEST_METHOD} ne "POST"; return $self->_respond ($handle, 204, "No Content", ""); } return $self->_respond ($handle, 405, "Method Not Allowed", "") unless $env->{REQUEST_METHOD} eq "POST"; if (defined $self->{cookie} || defined $self->{bearer} || defined $self->{users}) { my $authenticated = $cookie_path; my $authorization = $env->{HTTP_AUTHORIZATION}; if (defined $self->{bearer} && $authorization =~ /\ABearer ([^\s]+)\z/i) { $authenticated ||= $1 eq $self->{bearer}; } if ($self->{users} && $authorization =~ /\ABasic ([A-Za-z0-9+\/=]+)\z/i) { my ($username, $password) = split /:/, MIME::Base64::decode_base64 ($1), 2; $authenticated ||= defined $password && exists $self->{users}{$username} && $password eq $self->{users}{$username}; } return $self->_respond ($handle, 401, "Unauthorized", "") unless $authenticated; } return $self->_respond ($handle, 415, "Unsupported Media Type", "") unless $env->{CONTENT_TYPE} =~ m{\Aapplication/json(?:\s*;|\z)}i; my $message = eval { JSON::XS::decode_json $body }; if ($@) { return $self->_rpc_error (sub { $self->_respond ($handle, 400, "Bad Request", JSON::XS::encode_json $_[0]); }, undef, -32700, "Parse error"); } my $params = ref $message eq "HASH" && ref $message->{params} eq "HASH" ? $message->{params} : {}; my $meta = ref $params->{_meta} eq "HASH" ? $params->{_meta} : {}; my $modern = exists $meta->{"io.modelcontextprotocol/protocolVersion"} || $env->{HTTP_MCP_PROTOCOL_VERSION} ge "2026"; if ($modern && ref $message eq "HASH" && exists $message->{id}) { my %headers = ( HTTP_MCP_PROTOCOL_VERSION => $meta->{"io.modelcontextprotocol/protocolVersion"}, HTTP_MCP_METHOD => $message->{method}, ); $headers{HTTP_MCP_NAME} = exists $params->{name} ? $params->{name} : $params->{uri} if $message->{method} =~ /\A(?:tools\/call|prompts\/get|resources\/read)\z/; for my $name (keys %headers) { my $value = $env->{$name}; if ($name eq "HTTP_MCP_NAME" && $value =~ /\A=\?base64\?([A-Za-z0-9+\/=]*)\?=\z/) { $value = eval { AnyEvent::MCP::utf8dec (MIME::Base64::decode_base64 ($1)) }; } unless (defined $value && defined $headers{$name} && $value eq $headers{$name}) { return $self->_rpc_error (sub { $self->_respond ($handle, 400, "Bad Request", JSON::XS::encode_json $_[0]); }, $message->{id}, -32020, "Header mismatch: $name"); } } } weaken $self; $self->rpc ($message, sub { my ($response) = @_; return unless $self && !$handle->{mcp_closed}; my ($status, $reason) = defined $response ? (200, "OK") : (202, "Accepted"); if ($modern && defined $response && $response->{error}) { ($status, $reason) = $response->{error}{code} == -32601 ? (404, "Not Found") : (400, "Bad Request"); } $self->_respond ($handle, $status, $reason, defined $response ? JSON::XS::encode_json $response : ""); }, peer => $handle->{mcp_peer}, protocol_version => $env->{HTTP_MCP_PROTOCOL_VERSION} || "2025-03-26", ); } sub _respond { my ($self, $handle, $status, $reason, $body) = @_; return if $handle->{mcp_closed}; $handle->push_write ( "HTTP/1.1 $status $reason\r\n" . "Content-Type: application/json\r\n" . "Content-Length: " . length ($body) . "\r\n" . (defined $handle->{mcp_origin} ? "Access-Control-Allow-Origin: $handle->{mcp_origin}\r\n" . ($handle->{mcp_origin} ne "*" ? "Vary: Origin\r\n" : "") : "") . ($status == 204 ? "Access-Control-Allow-Methods: POST, OPTIONS\r\n" . "Access-Control-Allow-Headers: content-type,authorization,mcp-protocol-version,mcp-method,mcp-name\r\n" . "Access-Control-Max-Age: 86400\r\n" : "") . ($status == 405 ? "Allow: POST" . (@{$self->{origins}} ? ", OPTIONS" : "") . "\r\n" : "") . ($status == 401 && defined $self->{bearer} ? "WWW-Authenticate: Bearer\r\n" : "") . ($status == 401 && $self->{users} ? "WWW-Authenticate: Basic realm=\"MCP\"\r\n" : "") . ($handle->{mcp_close} || $status != 200 && $status != 202 ? "Connection: close\r\n" : "") . "\r\n$body" ); if ($handle->{mcp_close} || $status != 200 && $status != 202) { weaken $self; $handle->on_drain (sub { $self->_close ($_[0]) if $self }); } else { $self->_read ($handle); } } sub _close { my ($self, $handle) = @_; return if $handle->{mcp_closed}; $handle->{mcp_closed} = 1; my $requests = delete $handle->{mcp_peer}{requests} || {}; $_->cancel ("Connection closed") for grep defined, values %$requests; delete $self->{connections}{$handle}; $handle->destroy; } sub close { my ($self) = @_; return if $self->{_closed}++; delete $self->{listener}; $self->_close ($_) for values %{$self->{connections} || {}}; $self->event (close =>); } sub DESTROY { $_[0]->close } 1