App-MCP-CLI
view release on metacpan or search on metacpan
lib/App/MCP/CLI/Client.pm view on Meta::CPAN
use constant PROTOCOL_VERSION => '2024-11-05';
=encoding utf8
=head1 NAME
App::MCP::CLI::Client - Transport-neutral MCP client used by all mcpcli sub-commands
=head1 VERSION
This module is distributed as part of L<App::MCP::CLI> v0.0.1.
=head1 SYNOPSIS
use App::MCP::CLI::Client;
use App::MCP::CLI::Config qw(load_config resolve_server_cmd);
my ($cmd, $url, $env) = resolve_server_cmd(load_config(), 'my-server');
my $client = App::MCP::CLI::Client->new(
cmd => $cmd, # stdio transport, or
url => $url, # HTTP/SSE transport
env => $env,
timeout => 30,
);
$client->connect; # initialize + notifications/initialized
my $tools = $client->list_tools; # arrayref of tool descriptors
my $res = $client->call_tool('add_numbers', { a => 1, b => 2 });
print content_text($res->{result}) if $res->{result};
$client->close;
=head1 DESCRIPTION
C<App::MCP::CLI::Client> hides the differences between the two transports
supported by C<mcpcli> behind one small API, so every sub-command gets the
same behaviour:
=over 4
=item * Every wait for the server is bounded by a timeout (default 30 seconds).
=item * If a stdio server exits unexpectedly, or an SSE stream is closed, a
clear error is raised instead of a JSON parse failure.
=item * Responses are matched to requests by C<id>. Notifications and log
lines sent by the server in between are skipped, and server-initiated
C<ping> requests are answered.
=item * The C<initialize> request is followed by the
C<notifications/initialized> notification, as required by the
C<2024-11-05> lifecycle.
=back
B<stdio>: the server is started with L<IPC::Open2>; messages are
newline-delimited JSON.
B<HTTP/SSE> (protocol revision C<2024-11-05>): a long-lived C<GET> opens the
event stream, the C<endpoint> event announces where to C<POST>, and each
response is accepted either in the C<POST> reply body or as a C<message>
event on the stream. C<https://> URLs need L<IO::Socket::SSL>.
All errors are raised with C<die> and a message ending in a newline.
=head1 METHODS
=head2 new( %args )
Arguments: C<cmd> (arrayref) or C<url> (string); optional C<env> (hashref
applied only to the spawned process), C<timeout> (seconds, C<0> disables),
C<headers> (hashref, SSE only) and C<client_name>.
Set the environment variable C<MCPCLI_DEBUG> to see every JSON-RPC message on
STDERR.
=cut
sub new {
my ($class, %a) = @_;
die "Client needs either a command or a URL.\n"
unless $a{cmd} || defined $a{url};
return bless {
cmd => $a{cmd},
url => $a{url},
env => $a{env} || {},
headers => $a{headers} || {},
timeout => defined $a{timeout} ? $a{timeout} : 30,
name => $a{client_name} // 'mcpcli',
next_id => 1,
buf => '',
json => JSON::MaybeXS->new(utf8 => 1, allow_nonref => 1),
}, $class;
}
=head2 is_sse
True when the client talks HTTP/SSE.
=cut
sub is_sse { defined $_[0]{url} }
=head2 server_info
The C<serverInfo> hashref reported by the server (after L</connect>).
=cut
sub server_info { $_[0]{server_info} || {} }
sub _deadline {
my ($self) = @_;
return time + ($self->{timeout} > 0 ? $self->{timeout} : 1e9);
}
sub _debug {
my ($self, $dir, $data) = @_;
lib/App/MCP/CLI/Client.pm view on Meta::CPAN
my $m = eval { $self->{json}->decode($line) };
next unless ref $m; # tolerate stray non-JSON output on stdout
return $m;
}
my $chunk = _read_some($self->{out}, $deadline, "the MCP server's reply to '$what'");
die "The MCP server closed the connection (did the process exit?).\n"
unless defined $chunk;
$self->{buf} .= $chunk;
}
}
# SSE
sub _parse_url {
my ($url) = @_;
$url =~ m{^(https?)://(\[[^\]]+\]|[^/:?#]+)(?::(\d+))?([^#]*)}i
or die "Invalid URL: $url\n";
my ($scheme, $host, $port, $path) = (lc $1, $2, $3, $4);
$path = "/$path" unless $path =~ m{^/};
my $hostport = $host;
$hostport .= ":$port" if defined $port;
(my $bare = $host) =~ s/^\[|\]$//g;
return {
scheme => $scheme,
host => $bare,
port => $port // ($scheme eq 'https' ? 443 : 80),
path => $path,
origin => "$scheme://$hostport",
};
}
sub _open_socket {
my ($self, $u) = @_;
my %opt = (PeerHost => $u->{host}, PeerPort => $u->{port},
Timeout => $self->{timeout} > 0 ? $self->{timeout} : 60);
my $sock;
if ($u->{scheme} eq 'https') {
eval { require IO::Socket::SSL; 1 }
or die "https:// MCP servers need IO::Socket::SSL, which is not installed.\n";
no warnings 'once';
$sock = IO::Socket::SSL->new(%opt)
or die "Cannot connect to $u->{origin}: $IO::Socket::SSL::SSL_ERROR\n";
}
else {
my $class = eval { require IO::Socket::IP; 1 } ? 'IO::Socket::IP'
: do { require IO::Socket::INET; 'IO::Socket::INET' };
$sock = $class->new(%opt)
or die "Cannot connect to $u->{origin}: " . ($@ || $!) . "\n";
}
return $sock;
}
sub _resolve_endpoint {
my ($base, $ep) = @_;
$ep =~ s/^\s+|\s+$//g;
return $ep if $ep =~ m{^https?://}i;
my $u = _parse_url($base);
return $u->{origin} . $ep if $ep =~ m{^/};
(my $dir = $u->{path}) =~ s{[^/]*\z}{};
return $u->{origin} . $dir . $ep;
}
sub _connect_sse {
my ($self) = @_;
my $u = _parse_url($self->{url});
my $deadline = $self->_deadline;
my $sock = $self->_open_socket($u);
my $extra = join '', map { "$_: $self->{headers}{$_}\r\n" } sort keys %{ $self->{headers} };
my $host = $u->{origin};
$host =~ s{^https?://}{};
print {$sock} "GET $u->{path} HTTP/1.1\r\nHost: $host\r\n"
. "Accept: text/event-stream\r\nCache-Control: no-cache\r\n"
. "Connection: keep-alive\r\n$extra\r\n"
or die "Cannot send request to $u->{origin}: $!\n";
my $raw = '';
until ($raw =~ /\r?\n\r?\n/) {
my $chunk = _read_some($sock, $deadline, 'the SSE response headers');
die "SSE endpoint closed the connection before sending headers.\n"
unless defined $chunk;
$raw .= $chunk;
}
$raw =~ s/\A(.*?)\r?\n\r?\n//s;
my @head = split /\r?\n/, $1;
my ($code, $reason) = (shift(@head) // '') =~ m{^HTTP/\S+\s+(\d+)\s*(.*)}
or die "SSE endpoint sent an invalid HTTP response.\n";
die "Failed to connect to SSE endpoint ($code): $reason\n" unless $code == 200;
my %h = map { /^([^:]+):\s*(.*)$/ ? (lc $1, $2) : () } @head;
$self->{sse} = {
sock => $sock,
raw => $raw,
text => '',
chunked => (($h{'transfer-encoding'} // '') =~ /chunked/i ? 1 : 0),
remaining => (exists $h{'content-length'} ? $h{'content-length'} : undef),
eof => 0,
};
my $ep;
while (!defined $ep) {
my $ev = $self->_sse_event($deadline, 'the SSE endpoint event');
die "SSE stream ended before announcing a POST endpoint.\n" unless $ev;
$ep = $ev->{data} if $ev->{event} eq 'endpoint';
}
$self->{post_url} = _resolve_endpoint($self->{url}, $ep);
$self->{ua} = HTTP::Tiny->new(
timeout => ($self->{timeout} > 0 ? $self->{timeout} : 3600),
);
return;
}
sub _sse_decode {
my ($st) = @_;
if ($st->{chunked}) {
while (1) {
if ($st->{need_crlf}) {
return if length($st->{raw}) < 2;
substr($st->{raw}, 0, 2, '');
$st->{need_crlf} = 0;
}
if (!defined $st->{chunk_left}) {
return unless $st->{raw} =~ s/\A([0-9a-fA-F]+)[^\r\n]*\r\n//;
$st->{chunk_left} = hex $1;
if (!$st->{chunk_left}) { $st->{eof} = 1; return }
}
return unless length $st->{raw};
my $take = length($st->{raw}) < $st->{chunk_left}
? length($st->{raw}) : $st->{chunk_left};
$st->{text} .= substr($st->{raw}, 0, $take, '');
$st->{chunk_left} -= $take;
if (!$st->{chunk_left}) {
$st->{chunk_left} = undef;
$st->{need_crlf} = 1;
}
}
}
my $n = length $st->{raw};
$st->{text} .= $st->{raw};
$st->{raw} = '';
if (defined $st->{remaining}) {
$st->{remaining} -= $n;
$st->{eof} = 1 if $st->{remaining} <= 0;
}
return;
}
sub _sse_event {
my ($self, $deadline, $what) = @_;
my $st = $self->{sse};
while (1) {
_sse_decode($st) if length $st->{raw};
# A response with a fixed length (or a terminated chunked body) is a
# finished stream: release the connection at once so that
# single-threaded servers can accept our POSTs.
if ($st->{eof} && !$st->{released}++) {
eval { $st->{sock}->close };
}
if ($st->{text} =~ s/\A(.*?)\r?\n\r?\n//s) {
my ($event, @data) = ('message');
( run in 1.811 second using v1.01-cache-2.11-cpan-eb134014566 )