AnyEvent-MCP

 view release on metacpan or  search on metacpan

bin/mcp-multibroker  view on Meta::CPAN


C<stdio:COMMAND> retains shell interpretation. Use it for shell syntax or
when a child needs a literal C<---> argument. Quoting C<'---'> in the
delimited form cannot escape the delimiter: shell quoting is already gone.

Broker-wide options precede the first server entry. Downstream options
follow that server's URL or closing C<--->; Getopt::Long stops at the next
prefix. Options inside an argv list belong exclusively to the child.

C<--hidden> after a server keeps its tools out of normal MCP C<tools/list>
and unfiltered C<list-tools> results. This reduces the initial tool list
for large or rarely used servers. C<discover-brokers> still lists it;
C<list-tools broker=PREFIX>
returns its definitions; C<search-tools> includes hidden tools, and
C<call-tool> still works. Hiding affects advertisement, not permissions.
C<--disable> after a server excludes it entirely: no child is started,
no HTTP connection is made, and its tools cannot be discovered or called.
The prefix stays reserved so a reverse connection cannot take its place.
This takes precedence over C<--eager> and C<--required>; remove the flag
to re-enable the server.

C<--eager> after either stdio form starts that child at
multibroker startup rather than waiting for its first MCP use. This is useful
for children that also provide their own TCP service, such as C<mcp-vim>.
Other stdio children remain lazy. Eager startup attempts one connection and
logs failures; it does not continually restart failed children.
C<--required> implies C<--eager> and makes the multibroker exit with failure
if that child cannot initialize or later disconnects unexpectedly. A supervisor
can then restart the broker. An explicitly accepted managed idle shutdown is
not a failure; the child can be started again on the next use. Both options
apply only to spawned stdio children, never remote HTTP peers.

=head2 Reverse connections

The HTTP listener also accepts authenticated reverse MCP connections. It
can run with no configured downstream servers. With upstream stdio, add
C<--listen> to keep this listener active:

   mcp-multibroker --stdio --listen --bind 127.0.0.1:31740
   mcp-multibroker --bind 127.0.0.1:31740 --print-url
   mcp-fs --connect http://127.0.0.1:31740/TOKEN/files /home/alice/project

Use the token returned by C<--print-url>. The connecting server extracts
the host, port, token and alias from this URL, sends
C<["mcp-connect", token, alias]> followed by a newline, then ordinary MCP
JSONL. The connection uses the HTTP listener but is not an HTTP request.
With C<--tls-cert> or C<--tls-key>, the same port also accepts TLS, and
C<--print-url> prints HTTPS first and HTTP second. Reverse connections using
C<https://> verify the listener certificate and hostname; C<http://> uses
plaintext.
It uses the same accepted tokens as HTTP. Authentication grants registration
under any free alias; configured or connected aliases cannot be replaced.

The connecting program remains the MCP server. The multibroker attaches an
MCP client and discovers its tools immediately. Forms and cancellation follow
the same routes as other downstream connections. An unexpected disconnect
fails pending calls, removes the registration and starts a new connection
period. Refused TCP connections are retried every second, up to sixty times.
Other TCP setup failures and TLS verification failures log an error and stop;
there is no automatic downgrade to plaintext. No interrupted operation is
replayed. Plain HTTP endpoint URLs do not provide transport encryption;
use a trusted connection or tunnel as needed.

=head2 Process lifetime

Each downstream connection advertises C<anyevent-mcp/multibroker> version 1
in its client capabilities. A spawned stdio child can request managed idle
shutdown with C<anyevent-mcp/idle-exit>. When no calls are outstanding, the
broker may send C<anyevent-mcp/shutdown>; the child acknowledges before
exiting. This is optional and never makes HTTP children exit. Unexpected
disconnects are logged, not proactively restarted. A later use reconnects.

=head1 PERMISSION PROMPTS

C<--ask helper> (the default) answers downstream form challenges locally.
Ordinary forms use C<anyevent-mcp-form-elicitation>; permission requests keep their
specialised permission dialogs. C<--ask mcp> forwards modern challenges to
the upstream client. C<--ask auto> uses upstream form support when advertised,
otherwise the local helper. Both modes deliberately trust the upstream
client's user assertion when permission authority has been delegated to it.
The multibroker forwards the original authenticated user with every tool call,
even when a downstream saved permission rule resolves that request without
another prompt. A decline or cancel is never retried through another
interface. If a client advertises forms but silently declines them,
select C<helper> explicitly.

C<--ask tty> and C<--ask yad> select only the built-in terminal or YAD
interface for both ordinary forms and permission dialogs. These modes
ignore custom helper variables and do not fall back to another interface.

The broker advertises its local form support to downstream calls when it
will handle their forms itself. In C<mcp> mode it forwards the upstream
caller's capabilities instead. Local forms work for HTTP and stdio children,
including when the upstream caller cannot handle native input challenges.
Continuation tokens remain opaque; the broker sends the human response back
to the same downstream operation and returns its eventual result.

Spawned stdio children default to C<--ask mcp>, delegating permissions to
the multibroker, which handles them according to its own C<--ask> mode.
An explicit child C<--ask> overrides this default. Independently running
servers keep their own configuration.
Spawned C<mcp-ask-user> instances normally delegate presentation to this broker.
Use C<--ask mcp> on a separately started C<mcp-ask-user> to delegate to its
connecting client, including a multibroker.

Local permission and question dialogs share one queue. Set
C<PERL_ANYEVENT_MCP_ELICITATION_HELPER> to replace the form helper and
C<PERL_ANYEVENT_MCP_PERMISSION_HELPER> to replace the permission helper.
Cancelling a tool call cancels its downstream operation and pending local
prompt.
Downstream C<notifications/progress> are forwarded to the corresponding
upstream request by its progress token, including through HTTP children.

=head1 CLIENT CONNECTION

The upstream listener uses L<AnyEvent::MCP::Server::Simple/mcp_start>: HTTP
without stdout output by default, or stdio when run by another broker.
The service instance name defaults to C<default>. Repeated
C<--token TOKEN> options before the broker pairs configure credentials
accepted by the upstream HTTP listener. They are separate from C<--bearer>
after a downstream broker URL, which authenticates the client connection.

bin/mcp-multibroker  view on Meta::CPAN

first use. Not available for HTTP children.

=item --required

Require the preceding stdio child to initialize and remain connected.
Implies C<--eager>; an unexpected disconnect causes the broker to exit.
Managed idle shutdown is permitted. Not available for HTTP children.

=back

=head2 Shared-option behavior

=over

=item --name NAME

Select the upstream broker's instance (default C<default>).
Does not affect downstream prefixes or their instance names.

=item --token TOKEN

Authenticate clients of the upstream broker. To authenticate an
HTTP(S) child, use C<--bearer> after its URL instead.

=item --tool-help

Lists only the broker's own tools. Use its C<list-tools> tool to
discover individual downstream registries.

=item --auto-allow TOOL[,ACTION[,CAPABILITY]]

Matches the broker-visible tool names, not a downstream server's
independent permission checks.

=back

=cut

use common::sense;
use Getopt::Long ();

use AnyEvent ();
use AnyEvent::MCP::Client::HTTP ();
use AnyEvent::MCP::Client::JSONL ();
use AnyEvent::MCP::Permissions::Ask ();
use AnyEvent::MCP::Helper ();
use AnyEvent::MCP::Config ();
use AnyEvent::MCP::Server::Toolset ();

use AnyEvent::MCP::Server::Simple;

AnyEvent::detect; # initialise child watchers before starting subprocesses.
$| = 1;

my $usage = "Usage: $0 [OPTION]... PREFIX (URL | --- PROGRAM ARG... ---) [CHILD-OPTION] ...\n";
Getopt::Long::Configure ("require_order");
my $server_options = mcp_getoptions
   {
      usage       => $usage,
      path        => "/",
      description => "Combine MCP servers behind one endpoint, with tools named PREFIX.TOOL.\n"
         . "Each server is HTTP(S), stdio:COMMAND, or --- PROGRAM ARG... ---; downstream options follow its entry.",
      options     => [
         "Broker-wide options:",
         ["--listen", "Keep the upstream HTTP listener active alongside stdio or --connect"],
         "Downstream options (after the URL or closing ---):",
         ["--eager", "Start the preceding stdio child at broker startup"],
         ["--required", "Require stdio child; implies --eager, exit on failure"],
         ["--bearer TOKEN", "Authenticate to the preceding HTTP child"],
         ["--hidden", "Hide child's tools from default discovery; explicit list-tools and calls still work"],
         ["--disable", "Exclude the preceding child entirely, keeping its prefix reserved"],
      ],
      examples    => "  $0 --ask auto files 'stdio:mcp-fs /home/alice/src/project'\n"
         . "  $0 files --- mcp-fs /home/alice/src/project --- --eager\n"
         . "  $0 vim --- mcp-vim --bind :: --- --required\n"
         . "  $0 remote https://example.org/mcp/ --bearer TOKEN\n"
         . "  $0 --name tools --print-url",
   },
   "listen" => \my $listen,
;

my $ask_mode = delete $server_options->{ask};

$AnyEvent::Log::FILTER->level ("debug")
   unless defined $ENV{PERL_ANYEVENT_VERBOSE}
      || ($ENV{PERL_ANYEVENT_LOG} // "") =~ /(?:\A|\s)filter=/;
$ask_mode //= $ENV{PERL_ANYEVENT_MCP_PERMISSION_ASK} || "helper";
$ask_mode =~ /\A(?:helper|tty|yad|auto|mcp|none)\z/
   or die "--ask must be helper, tty, yad, auto, mcp, or none\n";

my (%broker, %disabled, %stdio, %eager, %required, %hidden, %progress);
my $shutting_down;
my @prompts;
my $prompt;

# keep local dialogs serial, including dialogs from different brokers.
sub next_prompt;
sub ask_prompt {
   my ($req, $prepared, $done, $form) = @_;

   my $entry = { request => $req, prepared => $prepared, done => $done, form => $form };
   push @prompts, $entry;

   my $old_cancel = $req->{on_cancel};
   $req->{on_cancel} = sub {
      AE::log trace => "local prompt cancelled "
         . (defined $entry->{started} ? sprintf ("after %.2fs", AE::now - $entry->{started}) : "while queued")
         . (defined $_[1] ? ": $_[1]" : "");
      $entry->{job}->cancel if $entry->{job};
      $old_cancel->(@_) if $old_cancel;
   };
   next_prompt;
}

sub next_prompt {
   return if $prompt;
   while (@prompts) {
      my $entry = shift @prompts;
      next if $entry->{request}{finished};
      $prompt = $entry;
      $entry->{job} = $entry->{form}



( run in 0.878 second using v1.01-cache-2.11-cpan-1bcd28dbaf1 )