App-MCP-CLI

 view release on metacpan or  search on metacpan

examples/sse_server.pl  view on Meta::CPAN


        # Server-Sent Events channel
        if ($r->method eq 'GET' && $r->uri->path eq '/sse') {
            print "[Server] Received SSE connection handshake request.\n";

            my $res = HTTP::Response->new(RC_OK);
            $res->header('Content-Type'  => 'text/event-stream');
            $res->header('Cache-Control' => 'no-cache');
            $res->header('Connection'    => 'keep-alive');

            $res->content("event: endpoint\ndata: http://$HOST:$PORT/message\n\n");

            $c->send_response($res);
            print "[Server] Broadcasted dynamic endpoint to client. Channel open.\n";
        }
        elsif ($r->method eq 'POST' && $r->uri->path eq '/message') {
            my $raw_content = $r->content;
            my $payload     = eval { $json->decode($raw_content) };

            if ($@ || !$payload) {
                print "[Server] Error parsing incoming client JSON request: $@\n";
                $c->send_error(RC_BAD_REQUEST);
                next;
            }

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

=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

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

    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;

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

    $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}) {

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

=head1 TRANSPORT MODES

=head2 stdio (default)

The server is launched as a child process via C<IPC::Open2>.  Messages are
exchanged as newline-delimited JSON on its stdin/stdout.  This is the simplest
mode and works with any compliant MCP server script.

=head2 HTTP/SSE

When the resolved server endpoint begins with C<http://> or C<https://>, or
when the config entry contains a C<url> key, the client connects in SSE mode.
It opens the event stream with a C<GET> request, reads the C<endpoint> event
to learn the C<POST> URL, then sends all JSON-RPC messages as C<POST> requests
to that URL. Responses are accepted either in the C<POST> reply body or as
C<message> events on the stream. See L<App::MCP::CLI::Client>.

=head1 CONFIGURATION FILE

The command accepts a JSON configuration file (C<--config>) with the following
optional top-level keys:

=over 4

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

contain:

=over 4

=item C<command> (string) - executable to launch (stdio mode).

=item C<args> (array of strings) - additional arguments for the executable.

=item C<env> (object) - environment variables for the launched server only.

=item C<url> (string) - SSE endpoint URL (SSE mode).

=item C<transport> (string) - informational (C<"stdio"> or C<"sse">); a server
is SSE when it has a C<url>. C<"sse"> without a C<url> is an error.

=back

=item C<confirmTools> (boolean, default true)

When true, the agent pauses before executing any tool call and asks the user
for explicit confirmation.  Set to C<false> to allow autonomous execution.

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

sub _ollama_url {
    my $base = $ENV{OLLAMA_HOST} || 'http://localhost:11434';
    $base = "http://$base" unless $base =~ m{^https?://}i;
    $base =~ s{/+\z}{};
    return "$base/api/generate";
}

=head2 _ask_llm( $query, $tools )

Sends C<$query> together with the serialised C<$tools> array to the Ollama
C</api/generate> endpoint.  The system prompt instructs the model to respond
with a bare JSON object in one of two forms:

    { "action": "call_tool", "tool": "<name>", "arguments": { ... } }
    { "action": "reply",     "answer": "<text>" }

Returns the decoded hashref. If the model's output is not a JSON object, or
the request fails, a synthetic C<reply> hashref describing the problem (or
containing the raw text) is returned instead.

=cut

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

        print "No servers found in configuration.\n";
        return;
    }

    my $servers = $config_data->{mcpServers};
    my @rows    = (['Server Name', 'Transport', 'Command / URL']);

    foreach my $name (sort keys %$servers) {
        my $srv = $servers->{$name};

        my ($transport, $endpoint);
        if ($srv->{url} || (($srv->{transport} // '') eq 'sse')) {
            $transport = 'SSE';
            $endpoint  = $srv->{url} // '(transport: sse)';
        } else {
            $transport = 'stdio';
            my @parts  = ($srv->{command} // '');
            push @parts, @{ $srv->{args} // [] };
            $endpoint  = join(' ', @parts);
        }

        push @rows, [$name, $transport, $endpoint];
    }

    print "\nConfigured MCP Servers:\n";
    print generate_table(
        rows       => \@rows,
        header_row => 1,
        style      => 'classic'), "\n";
}

=head1 SEE ALSO

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

Additional command-line arguments passed to C<command>
(e.g. C<["stdio_server.pl"]>). Defaults to an empty list.

=item C<env> (object)

A map of environment variable names to values. The entries are passed to the
server subprocess only; they are never set in the C<mcpcli> process itself.

=item C<url> (string)

The SSE endpoint URL for remote servers (e.g.
C<"http://mcp.example.com/sse">). When present, the server is contacted via
HTTP/SSE instead of a local subprocess.

=item C<transport> (string)

Informational (C<"stdio"> or C<"sse">). A server is treated as SSE when it has
a C<url>. C<transport: "sse"> without a C<url> is rejected with an error.

=back

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


=head2 resolve_server_cmd

Signature: C<resolve_server_cmd( $config, $server_input )>.

    my ($cmd, $url, $env) = resolve_server_cmd($config, 'perl-math-server');
    my ($cmd, $url, $env) = resolve_server_cmd($config, 'http://localhost/sse');
    my ($cmd, $url, $env) = resolve_server_cmd($config, 'perl stdio_server.pl');
    my ($cmd, $url, $env) = resolve_server_cmd($config);   # sole configured server

Resolves C<$server_input> to a transport endpoint. C<$config> is the hashref
returned by L</load_config> (may be C<undef>).

Resolution order:

=over 4

=item 1. If C<$server_input> is empty or C<undef>: when the configuration
defines exactly one server, that server is used; otherwise this is a fatal
error that lists the available names.

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


=back

Return value is a three-element list C<($cmd, $url, $env)>:

=over 4

=item * For B<stdio> servers: C<$cmd> is an arrayref of command + arguments
suitable for passing to C<IPC::Open2::open2>; C<$url> is C<undef>.

=item * For B<SSE> servers: C<$url> is the endpoint URL string; C<$cmd> is
C<undef>.

=item * C<$env> is a hashref of extra environment variables from the
descriptor's C<env> block (empty when there is none). It is B<not> applied to
the current process; L<App::MCP::CLI::Client> sets it for the spawned server
only, so variables never leak from one server to another.

=back

=cut

script/mcpcli  view on Meta::CPAN

supports:

=over 4

=item C<command> (string) - executable to launch (stdio mode).

=item C<args> (array) - additional arguments for the executable.

=item C<env> (object) - environment variables to set before launching.

=item C<url> (string) - SSE endpoint URL (SSE mode).

=item C<transport> (string) - set to C<"sse"> to force SSE mode.

=back

=item C<confirmTools> (boolean, default: C<true>)

When true, the C<interactive>/C<chat> command pauses before executing any tool
call and asks the user for explicit confirmation. Set to C<false> to allow
autonomous execution.

script/mcpcli  view on Meta::CPAN


The server is launched as a child process. Messages are exchanged as
newline-delimited JSON on its stdin/stdout. This is the default mode when a
C<command> key is present in the server descriptor.

=head2 HTTP/SSE

When the server descriptor contains a C<url> key, or when C<--server> is
given an C<http://>/C<https://> URL directly, the client connects in SSE mode
(MCP protocol revision 2024-11-05).  It opens the event stream with a C<GET>,
reads the C<endpoint> event to learn the C<POST> URL, then sends all JSON-RPC
messages as C<POST> requests to that URL.  Responses are accepted either in the
C<POST> reply body or as C<message> events on the stream.  This works for
C<list>, C<call> and C<chat>.  C<https://> URLs need L<IO::Socket::SSL>.

=head1 ENVIRONMENT

=over 4

=item C<HOME> / C<USERPROFILE>

t/client.t  view on Meta::CPAN

# SSE
{
    my $port = free_port();
    my $pid  = start_bg(cmd => [ $^X, ROOT . '/t/lib/mock_sse.pl', $port ]);
    ok(wait_port($port), 'mock SSE server is up') or BAIL_OUT('mock SSE server did not start');

    my $c = App::MCP::CLI::Client->new(url => "http://127.0.0.1:$port/sse", timeout => 10);
    $c->connect;
    ok($c->is_sse, 'SSE transport selected');
    is($c->server_info->{name}, 'mock-sse', 'handshake over SSE (response arrives on the stream)');
    is($c->{post_url}, "http://127.0.0.1:$port/messages?session=abc", 'relative endpoint is resolved');

    my $tools = $c->list_tools;
    is($tools->[0]{name}, 'add_numbers', 'tools/list over SSE');
    is(content_text($c->call_tool('add_numbers', { a => 4, b => 5 })->{result}), 'sum=9',
       'tools/call over SSE, split chunked events reassembled');
    $c->close;
    stop_bg($pid);

    eval { App::MCP::CLI::Client->new(url => "http://127.0.0.1:$port/sse", timeout => 2)->connect };
    like($@, qr/Cannot connect/, 'an unreachable SSE server is a clear error');

t/lib/mock_sse.pl  view on Meta::CPAN

    my $fh = shift;
    my $b  = \$buf{refaddr $fh};
    return unless $$b =~ /\r\n\r\n/;
    my ($head) = $$b =~ /\A(.*?)\r\n\r\n/s;

    if ($head =~ m{^GET /sse}) {
        print $fh "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n"
                . "Cache-Control: no-cache\r\nTransfer-Encoding: chunked\r\n\r\n";
        $fh->flush;
        ($stream, $$b) = ($fh, '');
        send_event('endpoint', '/messages?session=abc');
    }
    elsif ($head =~ m{^POST /messages}) {
        my ($len) = $head =~ /content-length:\s*(\d+)/i;
        my $hl    = length($head) + 4;
        return if length($$b) < $hl + ($len // 0);
        my $body = substr($$b, $hl, $len);
        print $fh "HTTP/1.1 202 Accepted\r\nContent-Length: 8\r\nConnection: close\r\n\r\nAccepted";
        $fh->flush;
        drop($fh);
        handle_msg($j->decode($body));



( run in 1.123 second using v1.01-cache-2.11-cpan-eb134014566 )