App-MCP-CLI

 view release on metacpan or  search on metacpan

lib/App/MCP/CLI/Client.pm  view on Meta::CPAN


        my $r = sysread($fh, my $chunk, 65536);
        if (!defined $r) {
            next if $!{EINTR} || $!{EAGAIN};
            die "Read error while waiting for $what: $!\n";
        }
        return $r ? $chunk : undef;
    }
}

sub _stdio_message {
    my ($self, $deadline, $what) = @_;

    while (1) {
        if ($self->{buf} =~ s/\A([^\n]*)\n//) {
            my $line = $1;
            $line =~ s/\r\z//;
            next unless $line =~ /\S/;

            $self->_debug('<-', $line);
            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;



( run in 1.150 second using v1.01-cache-2.11-cpan-234fa220139 )