App-MCP-CLI

 view release on metacpan or  search on metacpan

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

    mcpcli interactive --server ./server.pl --model llama3

    # Point at an SSE server by URL
    mcpcli interactive --server http://localhost:8080/sse

    # Override every option explicitly
    mcpcli interactive \
        --server   myserver       \
        --provider ollama         \
        --model    qwen2.5:1.5b   \
        --config   /etc/mcp/config.json

=head1 DESCRIPTION

C<App::MCP::CLI::Command::interactive> implements the C<interactive> (alias
C<chat>) sub-command of the C<mcpcli> application.  It starts a Read-Eval-Print
Loop (REPL) that:

=over 4

=item 1.

Connects to the MCP server specified by C<--server> (either as a stdio
subprocess or via HTTP/SSE).

=item 2.

Retrieves the full tool catalogue from the server with C<tools/list>.

=item 3.

Enters a prompt loop where each user message is forwarded to a local LLM
(currently only B<Ollama> is supported) together with the tool catalogue
and a structured JSON dispatch schema.

=item 4.

If the LLM decides to invoke a tool (C<action: "call_tool">), the command
optionally asks the user for confirmation before executing the C<tools/call>
request and summarising the raw result via a second LLM call.

=item 5.

If no tool is needed (C<action: "reply">), the LLM's plain-text answer is
printed directly.

=back

Type C<exit> or C<quit> (case-insensitive) at the prompt to end the session.

=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

=item C<mcpServers> (object)

A map of server alias names to server descriptor objects.  Each descriptor may
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.

=back

The configuration file is searched in the following order when C<--config> is
not given:

=over 4

=item 1. C<./server_config.json> in the current directory.

=item 2. C<./mcp-config.json> in the current directory.

=item 3. C<$HOME/.config/mcp-cli/config.json>.

=back

Example configuration:

    {
      "confirmTools": true,
      "mcpServers": {
        "myserver": {
          "command": "node",
          "args": ["/opt/mcp/server.js"],
          "env": { "DEBUG": "1" }
        },
        "remote": {
          "url": "http://mcp.example.com/sse"
        }
      }
    }

=head1 OPTIONS

=over 4

=item C<--server|-s> I<name_or_path>

The MCP server to connect to (optional when the config file defines exactly
one server).  Can be:

=over 4

=item * A key in the C<mcpServers> section of the config file.

=item * A C<.pl> file path (launched with the current Perl interpreter).

=item * An C<http://> or C<https://> URL (SSE mode).

=item * A bare shell command string (split on whitespace).

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

                    print "[-] Execution aborted by user request.\n\n";
                    $proceed = 0;
                }
            }

            if ($proceed) {
                my $tool_res = eval { $client->call_tool($tool_name, $tool_args) };
                if (!$tool_res) {
                    $warn->('Error:', $@);
                    next;
                }
                if (my $e = $tool_res->{error}) {
                    $warn->('Error:', $e->{message});
                    next;
                }

                my $result     = $tool_res->{result} || {};
                my $raw_result = content_text($result);
                if ($result->{isError}) {
                    $warn->('Tool error:', $raw_result);
                    next;
                }

                my $final_reply = $self->_summarize_with_llm($user_query, $raw_result);
                print "\e[1;32mResponse:\e[0m $final_reply\n\n";
            }
        }
        elsif ($action eq 'reply') {
            my $answer = $decision->{answer};
            $answer = $json->encode($answer) if ref $answer;
            print "\e[1;32mResponse:\e[0m " . ($answer // '') . "\n\n";
        }
        else {
            print "\e[1;31mResponse:\e[0m Failed to parse structural response from LLM.\n\n";
        }
    }

    $client->close;

    print "[-] Session Closed.\n";
}

=head2 _ollama_url

Returns the Ollama C</api/generate> URL. The base address defaults to
C<http://localhost:11434> and can be changed with the C<OLLAMA_HOST>
environment variable (with or without the C<http://> prefix).

=cut

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

sub _ask_llm {
    my ($self, $query, $tools) = @_;

    if (lc($self->{provider}) ne 'ollama') {
        return {
            action => 'reply',
            answer => "Error: Provider '" . $self->{provider} . "' is not supported. Please configure '--provider ollama'."
        };
    }

    my $ua   = HTTP::Tiny->new(timeout => 30);
    my $json = JSON::MaybeXS->new(utf8 => 1);

    my $system_prompt = "You are an AI assistant with access to these local tools:\n"
                      . $json->encode($tools) . "\n"
                      . "If the user request requires a tool, respond ONLY with a JSON object like: {\"action\":\"call_tool\",\"tool\":\"tool_name\",\"arguments\":{...}}\n"
                      . "If no tool is needed, respond with: {\"action\":\"reply\",\"answer\":\"your text answer here\"}\n"
                      . "Respond with valid raw JSON only, no markdown blocks.";

    my $res = $ua->post(
        _ollama_url(),
        {
            headers => { 'content-type' => 'application/json' },
            content => $json->encode({
                model  => $self->{model},
                prompt => "$system_prompt\n\nUser Question: $query",
                stream => JSON::MaybeXS::false()
            })
        }
    );

    if ($res->{success}) {
        # Raw text body resides inside the 'content' key
        my $body = eval { $json->decode($res->{content}) };
        my $raw_response = ref $body eq 'HASH' ? $body->{response} : undef;

        return { action => 'reply', answer => 'The LLM returned an empty or unreadable response.' }
            unless defined $raw_response && !ref $raw_response;

        $raw_response =~ s/\`{3}(?:json)?//g;
        $raw_response =~ s/\`{3}//g;
        $raw_response =~ s/^\s+|\s+$//g;

        my $parsed = eval { $json->decode($raw_response) };
        if ($@ || ref $parsed ne 'HASH') {
            return { action => 'reply', answer => $raw_response };
        }

        return $parsed;



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