#!/opt/bin/perl

=head1 NAME

mcp-multibroker - combine MCP servers under tool name prefixes

=head1 SYNOPSIS

   mcp-multibroker files 'stdio:mcp-fs /home/alice/src/project' \
                   search https://example.org/mcp/ --bearer TOKEN
   mcp-multibroker vim --- mcp-vim --bind :: --- --required

=head1 DESCRIPTION

C<mcp-multibroker> combines several MCP servers behind one connection to
your MCP client. You can give an assistant access to filesystem tools,
Vim editors and other services by configuring them here, then connecting
the client to this broker.

For each server, give a name prefix and an HTTP URL, a C<stdio:COMMAND>,
or C<--- PROGRAM ARG... ---> to start it as a subprocess. These are the downstream
servers. The multibroker starts or connects to them, obtains their tool
definitions and forwards tool calls and replies between them and your
client.

The prefix identifies which server a tool belongs to. For example, a
filesystem server configured as C<files> has a tool named
C<files.read-lines>. Your client can ask the multibroker which servers and
tools are available, then call a tool by its prefixed name.

The connection from your MCP client to the multibroker is the upstream
connection. It can use HTTP or stdin/stdout, independently of how the
downstream servers connect. See L<AnyEvent::MCP::Intro> for a complete
setup example.

=head1 FIRST USE

Configure a local MCP client to start a multibroker with two servers:

   mcp-multibroker --stdio \
      files --- mcp-fs --name project /home/alice/src/project --- \
      questions --- mcp-ask-user ---

The client launches only the broker; it starts children as needed. Ask:

   Call discover-brokers and list-tools, then use files.workdirs
   to show which project directories are configured.

C<files> and C<questions> are routing prefixes, not child instance names
or permission profiles. Each child still applies its own permissions.
The broker selects stdio automatically for bundled AnyEvent::MCP children.
Third-party servers must support MCP over stdio in their own startup mode.
You can replace a child with any stdio-speaking MCP server by putting
its executable and arguments between the C<---> delimiters, or connect
an existing HTTP server by URL; see L</DOWNSTREAM SERVERS>.

For HTTP clients, omit C<--stdio>, leave the broker running, and obtain
its upstream URL with C<--print-url> using the same listener settings.
For missing tools, try C<search-tools> with keywords, or
C<discover-brokers> for connection errors and C<list-tools> to refresh
discovery; your MCP client may also need to
refresh its cached list. C<--tool-help> only shows the broker's own
tools, not those of its children. Ordinary children start lazily. Use C<--eager>
after the child specification for services that accept independent
connections, such as Vim or browser brokers.

=head1 TOOLS

The broker exposes four tools of its own:

=over

=item discover-brokers

Lists the configured downstream servers and their instructions by prefix.
An entry is a string of instructions, C<null> for a reachable server with
no instructions, or C<{error: MESSAGE}> for an unreachable server.
Hidden servers are listed, with instructions on how to discover their tools.

=item search-tools

Search full tool definitions from visible downstream servers, or one
explicitly selected server (including hidden ones), but not the broker's
own tools. BM25 ranks matches using names, descriptions, and argument names
and descriptions. Returns up to 25 compact text entries, ordered by relevance;
if more match, reports how many were omitted. Search for C<edit lines in vim
buffer> without knowing its broker, then call C<PREFIX.TOOL> via C<call-tool>.

=item list-tools

Queries downstream tool definitions and returns compact text entries. The
optional C<broker> selects one downstream, including hidden servers and
excluding local tools. C<name> additionally selects a single tool and
returns its full description and exact C<inputSchema> as JSON text.
This is not the MCP protocol C<tools/list>: the latter forwards complete
tool definitions, including annotations and other fields.

Compact entries have one qualified name line, indented argument lines
(C<!> means required, C<=> indicates a default). Numeric, string and array
bounds and enum values appear beside their types. Objects show all nested
properties recursively; C<{string: string, ...}> means arbitrarily many
string-valued properties, and C<...> alone means unrestricted additional
properties. C<--> separates a field's inline description or starts the
tool's indented multiline description. Within one response, identical
parameter schemas by name become C<name: E<lt>as beforeE<gt>>; repeated
descriptions are omitted even when other constraints change. The most recent
occurrence of that name supplies the omitted information; each request
starts fresh. No schema content is truncated;
unknown JSON Schema keywords are shown verbatim. Blank lines separate tools.
Use C<broker> and C<name> to retrieve the original JSON Schema if needed.
Discovery results contain only MCP text content, no C<structuredContent>.
Without C<broker>, hidden servers are omitted. Unknown broker names or
arguments are errors. Unreachable servers are omitted but reported by
C<discover-brokers>.

=item call-tool

Calls a downstream tool by its C<PREFIX.TOOL> name with the supplied
arguments, including hidden servers. Calls to an unavailable server fail
as tool errors; calls are
not replayed after transport failures.

=back

A refreshed list is a snapshot of what is reachable at that point. It
includes configured servers and currently registered reverse connections.
A listed server might become unavailable before a later call.

=head1 DOWNSTREAM SERVERS

Each prefix identifies one downstream server. HTTP URLs may include a URL-path token,
or be followed by C<--bearer TOKEN>. C<bearer> and C<timeout> defaults
are read from C<[client PREFIX]> in the global configuration; the URL in
the command line overrides any configured C<url>. Stdio children receive
C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio> and
C<PERL_ANYEVENT_MCP_MULTIBROKER_ALIAS=PREFIX> in their environment.
The alias may be displayed in downstream permission prompts, without changing
the server's instance name or permission rules.

For direct execution, use C<PREFIX --- PROGRAM ARG... --->:

   mcp-multibroker vim --- mcp-vim --bind :: --- --eager \
                   files --- mcp-fs '/home/alice/project with spaces' ---

The next exact C<---> argument closes the list. Everything inside, including
C<-->, C<--eager> and C<--bearer>, is passed unchanged to the child. There is
no shell interpretation. Empty arguments are preserved; the program must be
nonempty. An empty list or missing closing delimiter is an error.

A subprocess can also connect to an MCP server on another machine via SSH:

   mcp-multibroker remote-fs --- ssh remotehost mcp-fs --stdio --ask mcp /workdir ---

C<--stdio> tells the remote C<mcp-fs> to use stdin/stdout for MCP. It must be
specified explicitly because the multibroker's environment variables are
not passed through SSH. C<--ask mcp> forwards permission prompts over MCP to
the local multibroker, instead of trying to display dialogs on the remote
host. The local broker then presents them according to its own C<--ask> mode
(normally using a local helper); see L</PERMISSION PROMPTS>.

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> or C<search-tools broker=PREFIX>
returns its definitions; unqualified searches omit 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<--guard> after a configured server requires multibroker permission
before forwarding any tool call to it. One shared rule file covers all
guarded servers, with independent broker and tool scopes. Reverse-connected
servers are not guarded.

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.
Both ends of reverse connections enable TCP keepalive, using the operating
system's default probe timings.

=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

The broker offers these C<--ask> modes:

=over

=item C<helper> (default)

Answer downstream form challenges locally. Ordinary forms use
C<anyevent-mcp-form-elicitation>; permission requests keep their
specialised permission dialogs.

=item C<mcp>

Forward modern challenges to the upstream client.

=item C<auto>

Use upstream form support when advertised, otherwise the local helper.

=item C<tty>, C<yad>

Use only the built-in terminal or YAD interface, respectively, for ordinary
forms and permission dialogs. These modes ignore custom helper variables
and do not fall back to another interface.

=item C<none>

Decline requests requiring human input without displaying a prompt.

=back

C<mcp> and C<auto> 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.

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.
See L<AnyEvent::MCP::Permissions::Helper> for the helper protocol and
integration examples, and L<anyevent-mcp-form-elicitation> for ordinary
form helpers.
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.
C<--name NAME>
selects C<[instance NAME]> in the global configuration, including its
credentials and optional C<bind> address. C<--bind ADDRESS[:PORT]> overrides
that address. The default is IPv4 loopback with a stable name-derived port
in 16384..32767. Port zero requests an ephemeral port.
C<--print-url> prints the credential-bearing URL without opening a listener
or starting children; it requires a nonzero port. Upstream stdio startup
skips HTTP listener configuration unless C<--listen> is specified; named HTTP
children still load their client defaults. Browser origins are unrestricted by default; HTTP requests
still require an accepted token. See L<AnyEvent::MCP::Intro> for examples.

=head1 OPTIONS

Shared upstream switches are documented in
L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.
Put broker-wide options before the first PREFIX/URL pair. Downstream
options must immediately follow the server they configure.

=head2 Broker options

=over

=item --listen

Keep the upstream HTTP/extension listener active alongside C<--stdio>
or C<--connect>. Without those, HTTP is already the default.
Applies to the broker, not its downstream servers.

=item --ask MODE

Select how downstream permission prompts are presented:
C<helper> (default), C<tty>, C<yad>, C<mcp>, C<auto>, or C<none>.
C<none> replies with a standard decline without invoking any UI.
Spawned stdio children delegate to the broker with their own default C<mcp>.
See L</PERMISSION PROMPTS>.

=back

=head2 Downstream options

=over

=item --bearer TOKEN

Authenticate the preceding HTTP(S) child with a bearer token, not
the broker's upstream listener. Supply after the child URL;
invalid for stdio children.

=item --force-protocol DATE

Force the negotiated MCP protocol version of the preceding downstream
server. Use only for a server that advertises an incorrect version.
DATE must be a supported MCP revision. Applies to HTTP and stdio children.

=item --hidden

Omit the preceding child's tools from ordinary tool discovery,
including unfiltered C<list-tools>. Discover its definitions with
C<list-tools> specifying its C<broker> prefix. Its tools remain
callable by name. Applies to HTTP and stdio children.

=item --guard

Require multibroker permission to call any tool of the preceding server.
Prompts offer this/all guarded brokers, this/all tools and, when known,
this/all users. Saved rules share C<multibroker-NAME.ini>, with the
usual one-time and expiring permissions. Applies to HTTP and stdio children.

=item --disable

Ignore the preceding downstream entry without removing it from the command
line. No startup, discovery or calls; the prefix remains reserved.
Overrides C<--eager> and C<--required>. Applies to HTTP and stdio children.

=item --eager

Start the preceding stdio child at broker startup instead of on
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::Permissions ();
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"],
         ["--force-protocol DATE", "Override preceding child's broken MCP version negotiation"],
         ["--hidden", "Hide child's tools from default discovery; explicit list-tools and calls still work"],
         ["--guard", "Ask permission before forwarding tool calls to this child"],
         ["--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, %guarded, %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}
         ? AnyEvent::MCP::Helper->new (
            helper => $ask_mode eq "tty" || $ask_mode eq "yad"
               ? ["anyevent-mcp-form-elicitation", "--$ask_mode"]
               : $ENV{PERL_ANYEVENT_MCP_ELICITATION_HELPER} || "anyevent-mcp-form-elicitation",
            timeout => 1800,
         )
         : AnyEvent::MCP::Permissions::Ask->new (
            ($ask_mode eq "tty" || $ask_mode eq "yad"
               ? (helper => ["anyevent-mcp-askpermission", "--$ask_mode"]) : ()),
         );
      $entry->{started} = AE::now;
      AE::log trace => "local prompt started (" . ($entry->{form} ? "form" : "permission") . ")";
      $entry->{job}->ask ($entry->{prepared}, sub {
         my ($success, $result) = @_;

         unless ($entry->{request}{finished}) {
            my $outcome = $success
               ? (ref $result eq "HASH" ? $result->{decision} || $result->{action} || "answered" : "answered")
               : "failed: $result";
            AE::log trace => sprintf "local prompt %s after %.2fs", $outcome, AE::now - $entry->{started};
         }
         undef $prompt;
         delete $entry->{job};
         $entry->{done}->($success, $result) unless $entry->{request}{finished};
         next_prompt;
      });
      return
   }
}

sub on_input {
   my ($client, $req) = @_;

   return $req->error (-32601, "Only form elicitation is supported locally")
      unless $req->{method} eq "elicitation/create";
   return $req->reply ({ action => "decline" }) if $ask_mode eq "none";

   my $offer = eval { AnyEvent::MCP::Permissions::Ask::permission_offer $req };
   return $req->error (-32602, "$@") if $@;
   unless ($offer) {
      return $req->error (-32602, "Only form elicitation is supported locally")
         if defined $req->{params}{mode} && $req->{params}{mode} ne "form";
      defined $req->{params}{message} && !ref $req->{params}{message}
         or return $req->error (-32602, "Form needs a message");
      ask_prompt $req, {
         %{$req->{params}},
         message => "Server: $client->{name}\n\n$req->{params}{message}",
      }, sub {
         my ($success, $response) = @_;

         return $req->error (-32603, $response) unless $success;
         my $action = ref $response eq "HASH" ? $response->{action} : undef;
         defined $action && !ref $action && $action =~ /\A(?:accept|decline|cancel)\z/
            && ($action ne "accept" || ref $response->{content} eq "HASH")
               or return $req->error (-32603, "Invalid form helper response");
         $req->reply ({
            action => $action,
            ($action eq "accept" ? (content => $response->{content}) : ()),
         });
      }, 1;
      return;
   }
   ask_prompt $req, $offer, sub {
      my ($success, $answer) = @_;

      return $req->error (-32603, $answer) unless $success;
      my $response = eval { AnyEvent::MCP::Permissions::Ask::response ($offer, $answer) };
      return $req->error (-32603, "Invalid permission helper decision: $@") if $@;
      $req->reply ($response);
   };
}

sub on_child_notification {
   my ($prefix, $client, $method, $params) = @_;

   if ($method eq "notifications/progress" && ref $params eq "HASH") {
      my $token = $params->{progressToken};
      return unless defined $token && !ref $token;
      my $req = $progress{$prefix}{$token} or return;
      $req->progress ($params->{progress}, $params->{total}, $params->{message})
         unless $req->{finished};
      return;
   }

   return unless $stdio{$prefix} && $method eq "anyevent-mcp/idle-exit";
   return if $client->{idle_shutdown_pending};
   # the child offered to exit; only act while no broker calls need it.
   return if keys %{$client->{operations}};

   $client->{idle_shutdown_pending} = 1;
   $client->rpc ("anyevent-mcp/shutdown", {}, sub {
      my ($success, $result) = @_;

      if ($success && $result->{accepted}) {
         $client->{idle_shutdown_expected} = 1;
      } else {
         AE::log debug => "$prefix: idle shutdown declined: "
            . ($result->{message} || "child is busy");
      }
      delete $client->{idle_shutdown_pending};
   });
}

# required children must not leave spawned peers running after broker failure.
sub required_failure {
   my ($prefix, $message) = @_;
   AE::log error => "$prefix: required child $message";
   $shutting_down = 1;
   $_->close for values %broker;
   exit 1;
}

sub on_child_close {
   my ($prefix, $client, $error) = @_;

   return if $shutting_down;
   if (delete $client->{idle_shutdown_expected}) {
      mcp_log "$prefix: managed idle shutdown";
   } elsif ($required{$prefix}) {
      required_failure $prefix, "disconnected: $error->{message}"
         . ($error->{pending} ? " ($error->{pending} outstanding requests)" : "");
   } elsif ($stdio{$prefix} || $error->{pending}) {
      my $message = "$prefix: unexpected disconnect: $error->{message}"
         . ($error->{pending} ? " ($error->{pending} outstanding requests)" : "");
      AE::log warn => $message or mcp_log $message;
   } else {
      mcp_log "$prefix: disconnected: $error->{message}";
   }
   delete $client->{idle_shutdown_pending};
}

sub broker_config {
   my ($prefix) = @_;

   (
      name                => $prefix,
      client_info         => { name => "mcp-multibroker", version => "$AnyEvent::MCP::VERSION" },
      client_capabilities => {
         elicitation => { form => {} },
         extensions  => { "anyevent-mcp/multibroker" => { version => 1 } },
      },
      on_request      => \&on_input,
      on_ready        => sub { mcp_log "$prefix: connected" },
      on_notification => sub { on_child_notification ($prefix, @_) },
      on_close        => sub { on_child_close ($prefix, @_) },
   )
}

sub accept_extension {
   my ($server, $handle, $hello) = @_;

   @$hello == 3 && $hello->[0] eq "mcp-connect"
      && defined $hello->[2] && !ref $hello->[2] && $hello->[2] =~ /\A[A-Za-z0-9_-]+\z/
      or die "Invalid reverse MCP hello\n";
   my $prefix = $hello->[2];
   !exists $broker{$prefix} && !$disabled{$prefix} or die "Broker alias '$prefix' is occupied\n";

   $handle->keepalive (1);
   my $client = AnyEvent::MCP::Client::JSONL->new (
      broker_config ($prefix),
      on_close => sub {
         on_child_close ($prefix, @_);
         delete $broker{$prefix} if $broker{$prefix} == $_[0];
      },
   );
   $broker{$prefix} = $client;
   $client->attach ($handle);
   $client->connect (sub {
      my ($success, $error) = @_;

      unless ($success) {
         AE::log warn => "$prefix: reverse MCP initialization failed: $error->{message}";
         delete $broker{$prefix} if $broker{$prefix} == $client;
         $client->close;
      }
   });
}

while (@ARGV) {
   @ARGV >= 2 or die $usage;
   my ($prefix, $url) = splice @ARGV, 0, 2;
   $prefix =~ /\A[A-Za-z0-9_-]+\z/ or die "Invalid broker prefix '$prefix'\n";
   (exists $broker{$prefix} || $disabled{$prefix}) and die "Duplicate broker prefix '$prefix'\n";

   my $command;

   if ($url eq "---") {
      my ($end) = grep $ARGV[$_] eq "---", 0 .. $#ARGV;
      defined $end or die "Missing closing --- for '$prefix'\n";
      $command = [splice @ARGV, 0, $end];
      shift @ARGV;
      @$command && length $command->[0] or die "Empty stdio argv for '$prefix'\n";
   } elsif ($url =~ s/\Astdio://) {
      length $url or die "Empty stdio command for '$prefix'\n";
      # preserve shell commands, but let ordinary programs receive TERM directly.
      $command = $url =~ / ^\s*(?: exec\b | source\b | \.\s ) | = | ; | \( | \{ | \|\| | && /x
         ? $url : "exec $url";
   }

   my %config = broker_config $prefix;
   my ($hide, $guard, $disable, $eager, $require);
   Getopt::Long::GetOptionsFromArray (\@ARGV,
      "eager" => sub { $eager = 1 },
      "hidden" => sub { $hide = 1 },
      "guard" => sub { $guard = 1 },
      "disable" => sub { $disable = 1 },
      "required" => sub { $eager = $require = 1 },
      "bearer=s" => sub {
         !defined $command && $url =~ m{\Ahttps?://} or die "Authentication options require an HTTP broker\n";
         length $_[1] or die "Missing bearer token for '$prefix'\n";
         $config{bearer} = $_[1];
      },
      "force-protocol=s" => sub { $config{force_protocol} = $_[1] },
   ) or die $usage;

   defined $command || $url =~ m{\Ahttps?://} or die "Invalid broker URL '$url'\n";
   if ($disable) {
      $disabled{$prefix} = 1;
      mcp_log "$prefix: disabled";
      next;
   }
   defined $command || !$require or die "--required requires a stdio broker ('$prefix')\n";
   defined $command || !$eager or die "--eager requires a stdio broker ('$prefix')\n";
   $hidden{$prefix} = 1 if $hide;
   $guarded{$prefix} = 1 if $guard;
   $eager{$prefix} = 1 if $eager;
   $required{$prefix} = 1 if $require;

   if (defined $command) {
      $broker{$prefix} = AnyEvent::MCP::Client::JSONL->new (
         %config, command => $command,
         env => {
            PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL => "stdio",
            PERL_ANYEVENT_MCP_MULTIBROKER_ALIAS => $prefix,
            PERL_ANYEVENT_MCP_PERMISSION_ASK => "mcp",
         },
      );
      $stdio{$prefix} = 1;
   } else {
      $broker{$prefix} = AnyEvent::MCP::Client::HTTP->new (%config, url => $url);
   }
}

my $toolset = AnyEvent::MCP::Server::Toolset->new;

sub broker_alias {
   my ($name) = @_;
   return $name if exists $broker{$name} || $disabled{$name};
   $name =~ tr/_/-/;
   $name
}

sub all_tools {
   my ($req, $done, $name, $include_hidden) = @_;

   my @tools = defined $name ? () : map @{$_->list}, @{$req->{server}{toolsets}};
   my @prefix = defined $name ? ($name) : grep $include_hidden || !$hidden{$_}, sort keys %broker;
   my @results;
   my %pending = map { $_ => 1 } @prefix;
   my $remaining = @prefix;
   my $finished;
   my $timer;
   my $finish = sub {
      return if $finished++;
      undef $timer;
      push @tools, @{$_ || []} for @results;
      $done->(\@tools) unless $req->{finished};
   };
   return $finish->() unless $remaining;

   $timer = AnyEvent->timer (after => 15, cb => sub {
      AE::log warn => "Tool discovery timed out: " . join ", ", sort keys %pending;
      $finish->();
   });
   for my $i (0 .. $#prefix) {
      my $prefix = $prefix[$i];
      my $client = $broker{$prefix};
      $client->tools (sub {
         return if $finished;
         my ($success, $result) = @_;
         if ($success) {
            $results[$i] = [map { +{ %$_, name => "$prefix.$_->{name}" } } @$result];
         } else {
            AE::log warn => "$prefix: $result->{message}";
         }
         delete $pending{$prefix};
         $finish->() unless --$remaining;
      });
   }
}

# Tool definitions are small enough to score directly on each search.
# Flatten argument names and descriptions recursively, ignoring schema mechanics.
sub schema_search_text {
   my ($value, $text) = @_;
   if (ref $value eq "HASH") {
      push @$text, $value->{description} if defined $value->{description} && !ref $value->{description};
      push @$text, keys %{$value->{properties}} if ref $value->{properties} eq "HASH";
      schema_search_text ($_, $text) for values %$value;
   } elsif (ref $value eq "ARRAY") {
      schema_search_text ($_, $text) for @$value;
   }
}

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

   my $words = sub {
      my ($text) = @_;
      $text =~ s/([a-z0-9])([A-Z])/$1 $2/g; # inputSchema -> input Schema
      grep length, split /[^[:alnum:]]+/, lc $text;
   };

   # Query terms are a set: repeating a word in the request has no extra weight.
   my %query = map { $_ => 1 } $words->($query);
   return ([], 0) unless %query;

   # Build per-tool term frequencies (tf), document lengths and the number
   # of tools containing each query term (df). No persistent index needed.
   my (@documents, %df, $total_length);
   for my $tool (@$tools) {
      # The broker's own tools are already exposed. Search qualified
      # downstream names (PREFIX.TOOL) only.
      next unless $tool->{name} =~ /\./;
      my @text = ($tool->{name}, $tool->{description});
      schema_search_text ($tool->{inputSchema}, \@text) if $tool->{inputSchema};
      my @words = $words->(join " ", grep defined && !ref, @text);
      my %tf;
      ++$tf{$_} for @words;
      ++$df{$_} for grep exists $tf{$_}, keys %query;
      $total_length += @words;
      push @documents, [$tool, \%tf, scalar @words];
   }

   # Okapi BM25, with positive IDF, k1=1.2 for frequency saturation and
   # b=0.75 for length normalization. Thus 2.2 = k1+1 and .25 = 1-b.
   # Sum each matching query term's contribution; nonmatches score zero.
   my $n = @documents;
   my $avg = $total_length / ($n || 1);
   my @scored;
   for my $doc (@documents) {
      my ($tool, $tf, $length) = @$doc;
      my $score = 0;
      for my $term (keys %query) {
         my $f = $tf->{$term} || next;
         my $idf = log (1 + ($n - $df{$term} + .5) / ($df{$term} + .5));
         $score += $idf * $f * 2.2 / ($f + 1.2 * (.25 + .75 * $length / ($avg || 1)));
      }
      push @scored, [$score, $tool] if $score > 0;
   }
   @scored = sort { $b->[0] <=> $a->[0] || $a->[1]{name} cmp $b->[1]{name} } @scored;
   my @ranked = map $_->[1], @scored[0 .. ($#scored < 24 ? $#scored : 24)];
   (\@ranked, scalar @scored)
}

# Render complete schemas in compact notation, not lossy summaries.
sub schema_json {
   JSON::XS->new->canonical->allow_nonref->encode ($_[0])
}

sub schema_type {
   my ($schema, $indent, $top, $seen, $field) = @_;

   return schema_json ($schema) unless ref $schema eq "HASH";

   my %used = map { $_ => 1 } qw(type properties required additionalProperties patternProperties
      items minimum maximum minLength maxLength minItems maxItems minProperties maxProperties
      enum const anyOf oneOf allOf default description);

   my $object = sub {
      my ($schema, $indent) = @_;
      my $properties = $schema->{properties} || {};
      my %required = map { $_ => 1 } @{$schema->{required} || []};
      my @fields = map {
         my $name = /\A[A-Za-z_][A-Za-z0-9_.-]*\z/ ? $_ : schema_json ($_);
         my $signature = ($required{$_} ? "!" : "") . schema_json ($properties->{$_});
         my $type = exists $seen->{$_}{schema} && $seen->{$_}{schema} eq $signature
            ? "<as before>"
            : schema_type ($properties->{$_}, $indent + 2, undef, $seen, $_);
         $seen->{$_}{schema} = $signature;
         "  " . (" " x $indent) . $name . ($required{$_} ? "!" : "")
            . ": " . $type
      } sort { !!$required{$b} <=> !!$required{$a} || $a cmp $b } keys %$properties;

      push @fields, map {
         "  " . (" " x $indent) . "pattern(" . schema_json ($_) . "): "
            . schema_type ($schema->{patternProperties}{$_}, $indent + 2, undef, $seen)
      } sort keys %{$schema->{patternProperties} || {}};

      if (!exists $schema->{additionalProperties} || $schema->{additionalProperties}) {
         push @fields, "  " . (" " x $indent)
            . (ref $schema->{additionalProperties} eq "HASH"
               ? "string: " . schema_type ($schema->{additionalProperties}, $indent + 2, undef, $seen) . ", ..."
               : "...");
      }

      return "{}" unless @fields;
      return "{" . substr ($fields[0], $indent + 2) . "}" if !$top && @fields == 1
         && $fields[0] !~ /\n/;
      "{\n" . join ("\n", @fields) . "\n" . (" " x $indent) . "}"
   };

   my $types = $schema->{type};
   my @types = ref $types eq "ARRAY" ? @$types : defined $types ? ($types) : ();
   @types = ("object") if !@types && (exists $schema->{properties}
      || exists $schema->{additionalProperties} || exists $schema->{patternProperties});
   @types = ("array") if !@types && exists $schema->{items};
   @types = ("any") unless @types;

   my $result = join "|", map {
      $_ eq "object" ? $object->($schema, $indent)
        : $_ eq "array" ? (exists $schema->{items}
             ? do {
                  my $item = schema_type ($schema->{items}, $indent, undef, $seen);
                  ($item =~ /[ \n#]/ ? "($item)" : $item) . "[]"
               } : "array")
        : $_
   } @types;

   for my $key (qw(anyOf oneOf allOf)) {
      if (ref $schema->{$key} eq "ARRAY") {
         my $choice = "$key(" . join (" | ", map schema_type ($_, $indent, undef, $seen), @{$schema->{$key}}) . ")";
         $result = $result eq "any" ? $choice : "$result & $choice";
      }
   }

   $result .= " enum(" . join (" | ", map schema_json ($_), @{$schema->{enum}}) . ")"
      if ref $schema->{enum} eq "ARRAY";
   $result .= " const=" . schema_json ($schema->{const}) if exists $schema->{const};

   my @ranges = (
      [minimum => "maximum", ""],
      [minLength => "maxLength", "len"],
      [minItems => "maxItems", "items"],
      [minProperties => "maxProperties", "keys"],
   );
   for my $range (@ranges) {
      my ($min, $max, $label) = @$range;
      next unless exists $schema->{$min} || exists $schema->{$max};
      $result .= " " . $label
         . (exists $schema->{$min} && exists $schema->{$max}
            ? ($label ? "=" : "") . "$schema->{$min}..$schema->{$max}"
            : exists $schema->{$min} ? ">=$schema->{$min}" : "<=$schema->{$max}");
   }

   my $properties = $schema->{properties} || {};
   my @unbound = grep !exists $properties->{$_}, @{$schema->{required} || []};
   $result .= " required=" . schema_json (\@unbound) if @unbound;

   # Unknown JSON Schema keywords remain verbatim instead of disappearing.
   $result .= " $_=" . schema_json ($schema->{$_})
      for sort grep !$used{$_}, keys %$schema;
   $result .= " = " . schema_json ($schema->{default}) if exists $schema->{default};
   if (exists $schema->{description}) {
      my $description = $schema->{description};
      $description =~ s/\s+/ /g;
      $description =~ s/\A | \z//g;
      if (!defined $field || !exists $seen->{$field}{description}
         || $seen->{$field}{description} ne $description) {
         $result .= " -- $description";
         $seen->{$field}{description} = $description if defined $field;
      }
   } elsif (defined $field) {
      delete $seen->{$field}{description};
   }
   $result
}

sub tool_summary {
   my ($tool, $seen) = @_;
   my $schema = $tool->{inputSchema} || {};
   my $signature = schema_type ($schema, 0, 1, $seen);
   $signature =~ s/^\{\n//;
   $signature =~ s/\n\}\z//;
   $signature = "  $signature" unless $signature =~ /^  /;
   my $description = $tool->{description} // "";
   $description =~ s/\r\n?/\n/g;
   $description =~ s/^/  /mg;

   join "\n", $tool->{name}, $signature, "  --", $description
}

sub tool_detail {
   my ($tool) = @_;
   join "\n", $tool->{name}, $tool->{description} // "", "inputSchema:",
      JSON::XS->new->canonical->pretty->encode ($tool->{inputSchema} || {})
}

sub tool_text {
   my ($req, $text) = @_;
   $req->reply ({ content => [{ type => "text", text => $text }] })
}

sub call_tool {
   my ($req, $name, $args) = @_;

   return $req->error ("Invalid tool call") unless defined $name && !ref $name && ref $args eq "HASH";
   if (my ($local) = grep exists $_->{tool}{$name}, @{$req->{server}{toolsets}}) {
      local $req->{tool} = $name;
      local $req->{args} = $args;
      return $local->call ($req)
   }

   my ($prefix, $tool) = $name =~ /\A([^.]+)\.(.+)\z/;
   $prefix = broker_alias $prefix if defined $prefix;
   my $client = $broker{$prefix};
   return $req->error ("Unknown tool '$name'") unless $client;

   if ($guarded{$prefix}) {
      local $req->{tool} = "$prefix.$tool";
      $req->require_permission ({
         action          => "call",
         reason          => "Call $prefix.$tool",
         sandbox_grants  => [],
         dimension_order => ["broker", "tool"],
         dimensions      => {
            broker => {
               label   => "Broker",
               value   => $prefix,
               choices => [
                  { id => "exact", label => "This broker: $prefix", match => $prefix },
                  { id => "any", label => "All brokers", match => "^" },
               ],
            },
            tool => {
               label   => "Tool",
               value   => $tool,
               choices => [
                  { id => "exact", label => "This tool: $tool", match => "^" . (quotemeta $tool) . "\\z" },
                  { id => "any", label => "All tools", match => "^" },
               ],
            },
         },
      });
   }

   AE::log trace => "multibroker $name";
   my %params = (%{$req->{params}}, name => $tool, arguments => $args);
   $params{_meta} = { %{$params{_meta} || {}} };
   $params{_meta}{"anyevent-mcp/user"} = $req->{user};
   my $caps = $params{_meta}{"io.modelcontextprotocol/clientCapabilities"};
   $caps = ref $caps eq "HASH" ? { %$caps } : {};
   my $native_forms = $req->{protocol_version} ge "2026"
      && ref $caps->{elicitation} eq "HASH"
      && (!keys %{$caps->{elicitation}} || ref $caps->{elicitation}{form} eq "HASH");
   my $local_forms = $ask_mode =~ /\A(?:helper|tty|yad|none)\z/ || $ask_mode eq "auto" && !$native_forms;
   if ($local_forms) {
      $caps->{elicitation} = { form => {} };
   } elsif ($req->{protocol_version} lt "2026") {
      delete $caps->{elicitation};
   }
   $caps->{extensions} = {
      %{ref $caps->{extensions} eq "HASH" ? $caps->{extensions} : {}},
      "anyevent-mcp/multibroker" => { version => 1 },
   };
   if ($local_forms) {
      if ($ask_mode eq "none") {
         delete $caps->{extensions}{$AnyEvent::MCP::Permissions::Ask::extension};
      } else {
         $caps->{extensions}{$AnyEvent::MCP::Permissions::Ask::extension} = { version => 1 };
      }
   }
   $params{_meta}{"io.modelcontextprotocol/clientCapabilities"} = $caps;
   my $token = $params{_meta}{progressToken};
   $progress{$prefix}{$token} = $req if defined $token && !ref $token;
   my $id;
   my $old_cancel = $req->{on_cancel};
   $req->{on_cancel} = sub {
      delete $progress{$prefix}{$token} if defined $token && !ref $token;
      $client->cancel ($id, $_[1]) if defined $id;
      $old_cancel->(@_) if $old_cancel;
   };
   my $done = sub {
      my ($success, $result) = @_;
      delete $progress{$prefix}{$token} if defined $token && !ref $token;

      return if $req->{finished};
      return $req->error ($result->{message}) unless $success;
      $req->reply ($result);
   };
   if ($local_forms || $req->{protocol_version} lt "2026") {
      $id = $client->call ($tool, $args, $done, %params);
   } else {
      $id = $client->rpc ("tools/call", \%params, $done);
   }
}

$toolset->tool (discover_brokers =>
   "Get instructions from all brokers by name: string; null if reachable but none; {error: MESSAGE} if unreachable.",
   { type => "object", properties => {} },
   readonly => 1, closedworld => 1,
   sub {
      my ($req) = @_;

      my @prefix = sort keys %broker;
      my %instructions;
      my %pending = map { $_ => 1 } @prefix;
      my $remaining = @prefix;
      my $finished;
      my $timer;
      my $finish = sub {
         return if $finished++;
         undef $timer;
         $instructions{$_} = { error => "Discovery timed out" } for keys %pending;
         $req->result (\%instructions) unless $req->{finished};
      };
      return $finish->() unless $remaining;

      $timer = AnyEvent->timer (after => 15, cb => sub { $finish->() });
      for my $prefix (@prefix) {
         my $client = $broker{$prefix};
         $client->connect (sub {
            return if $finished;
            my ($success, $result) = @_;
            if ($success) {
               $instructions{$prefix} = $hidden{$prefix}
                  ? "Hidden tools; use list-tools broker=$prefix.\n" . ($client->{instructions} // "")
                  : $client->{instructions};
            } else {
               AE::log warn => "$prefix: $result->{message}";
               $instructions{$prefix} = { error => $result->{message} };
            }
            delete $pending{$prefix};
            $finish->() unless --$remaining;
         });
      }
   },
);
$toolset->tool (search_tools =>
   "BM25 search full tool definitions; return up to 25 compact text signatures with nested arguments, constraints and descriptions. broker selects one, including hidden.",
   {
      type => "object",
      required => ["query"],
      properties => {
         query => { type => "string", description => "Keywords describing the desired operation" },
         broker => { type => "string", description => "Search one broker, including hidden; omit for visible brokers only." },
      },
      additionalProperties => JSON::XS::false,
   },
   readonly => 1, closedworld => 1,
   sub {
      my ($req, $args) = @_;
      for (keys %$args) {
         $_ eq "query" || $_ eq "broker" or return $req->error ("Unknown search-tools argument '$_'");
      }
      defined $args->{query} && !ref $args->{query} && $args->{query} =~ /[[:alnum:]]/
         or return $req->error ("search-tools requires a nonempty keyword query");
      my $name = $args->{broker};
      $name = broker_alias $name if defined $name && !ref $name;
      return $req->error ("Unknown broker '$name'") if defined $name && (ref $name || !exists $broker{$name});

      all_tools $req, sub {
         my ($tools, $matches) = search_tools $_[0], $args->{query};
         my %seen;
         my $text = join "\n\n", map tool_summary ($_, \%seen), @$tools;
         $text = "No matching tools." unless @$tools;
         $text .= "\n\n" . ($matches - @$tools) . " more matching tools; refine query."
            if $matches > @$tools;
         tool_text $req, $text;
      }, $name;
   },
);
$toolset->tool (list_tools =>
   "List complete compact text tool signatures; broker selects one downstream (including hidden). broker+name returns original JSON inputSchema. Native tools/list unchanged.",
   {
      type => "object",
      properties => {
         broker => { type => "string", description => "Downstream broker, including hidden; underscores may replace hyphens. Omit for visible brokers + local tools." },
         name => { type => "string", description => "One downstream tool's unqualified name; requires broker. Omit to list all tools." },
      },
      additionalProperties => JSON::XS::false,
   },
   readonly => 1, closedworld => 1,
   sub {
      my ($req, $args) = @_;

      for (keys %$args) {
         $_ eq "broker" || $_ eq "name" or return $req->error ("Unknown list-tools argument '$_'");
      }
      my $name = $args->{broker};
      $name = broker_alias $name if defined $name;
      return $req->error ("Unknown broker '$name'") if defined $name && !exists $broker{$name};

      my $tool = $args->{name};
      return $req->error ("name requires broker") if defined $tool && !defined $name;
      return $req->error ("Invalid tool name") if defined $tool && (ref $tool || !length $tool);

      all_tools $req, sub {
         my $tools = $_[0];
         $tools = [grep $_->{name} eq "$name.$tool", @$tools] if defined $tool;
         my %seen;
         my $text = join "\n\n", map {
            defined $tool ? tool_detail ($_) : tool_summary ($_, \%seen)
         } @$tools;
         tool_text $req, length $text ? $text : "No tools.";
      }, $name;
   },
);
$toolset->tool (call_tool =>
   "Call tool by prefixed name from list-tools. Use when not directly exposed; call loaded tools directly.",
   {
      type       => "object",
      required   => ["name"],
      properties => {
         name      => { type => "string" },
         arguments => { type => "object" },
      },
   },
   sub {
      my ($req, $args) = @_;

      return $req->error ("call-tool cannot call itself") if $args->{name} eq "call-tool";
      call_tool $req, $args->{name}, $args->{arguments} || {};
   },
);

sub log_request {
   my ($server, $req) = @_;

   # keep proxied calls at trace to avoid duplicating downstream activity logs.
   return if $req->{method} eq "tools/call" && $req->{tool} =~ /\A[^.]+\./;

   mcp_log_request $server, $req;
}

mcp_permissions (keys %guarded
   ? AnyEvent::MCP::Server::Permissions->new (
      name => "multibroker-$server_options->{name}",
      ask  => $ask_mode,
   )
   : undef);

mcp_config
   server_name    => "mcp-multibroker",
   server_version => $AnyEvent::MCP::VERSION,
   on_request => \&log_request,
   on_error => sub { AE::log error => "MCP dispatch $_[1]{method}: $_[2]" },
   short_instructions => "MCP tool router. search-tools ranks visible tools; broker=NAME includes hidden. Discovery returns compact text with complete parameter constraints. call-tool invokes a match.",
   instructions => <<'EOF';
Proxy MCP servers as PREFIX.TOOL. search-tools ranks full definitions from visible brokers, or one broker (including hidden), and returns up to 25 compact text signatures. list-tools returns compact signatures with complete nested arguments, bounds, defaults and descriptions, without truncation; broker=NAME name=TOOL retrieves the original inputSchema. '!' marks required arguments; '...' means arbitrary additional object properties; '--' introduces an inline argument description or the final multiline tool description. Repeated parameter descriptions may be omitted. 'name: <as before>' means the entire parameter schema matches its previous occurrence by name in this response. Discovery omits MCP annotations. call-tool invokes a prefixed tool name. discover-brokers lists all servers, including hidden ones. Tools may change.
EOF

# start selected stdio children now, before the upstream event loop starts.
# their asynchronous initialization completes once that loop is running.
# optional children can still be reconnected by a later MCP request.
mcp_tool_help ($server_options->{tool_help}, $toolset);
delete $server_options->{tool_help};
for my $prefix (sort keys %eager) {
   $broker{$prefix}->connect (sub {
      my ($success, $error) = @_;

      if (!$success && $required{$prefix}) {
         required_failure $prefix, "initialization failed: $error->{message}";
      }
      AE::log warn => "$prefix: eager startup failed: $error->{message}"
         unless $success;
   });
}

mcp_start
   %$server_options,
   ($listen ? (listen => 1) : ()),
   toolsets => [$toolset],
   on_extension => \&accept_extension,
   on_tools_list => sub {
      my ($server, $req) = @_;

      AE::log debug => "multibroker list-tools";
      all_tools $req, sub { $req->reply ({ tools => $_[0] }) };
   },
   on_tools_call => sub {
      my ($server, $req, $args) = @_;

      call_tool $req, $req->{tool}, $args;
   };

$shutting_down = 1;
$_->close for values %broker;

