bin/mcp-multibroker

filter: Statementstmt 81.0% 329 / 406 Branchbran 54.5% 145 / 266 Conditioncond 47.6% 93 / 195 MC/DCmcdc 28.4% 31 / 109 Subroutinesub 72.8% 43 / 59 Podpod n/a totaltotal 61.9% 641 / 1035 CC 189 SCAR 31.7
CC
189
Cov
65%
__ANON__
90.0
on_child_close
90.0
accept_extension
72.0
CRAP 23.8
« blib/lib/AnyEvent/MCP/Server/Connect.pm ↑ Summary lib/AnyEvent/MCP/IMAP/OAuth2.pm »
1 #!/opt/bin/perl
2  
3 =head1 NAME
4  
5 mcp-multibroker - combine MCP servers under tool name prefixes
6  
7 =head1 SYNOPSIS
8  
9 mcp-multibroker files 'stdio:mcp-fs /home/alice/src/project' \
10 search https://example.org/mcp/ --bearer TOKEN
11 mcp-multibroker vim --- mcp-vim --bind :: --- --required
12  
13 =head1 DESCRIPTION
14  
15 C<mcp-multibroker> combines several MCP servers behind one connection to
16 your MCP client. You can give an assistant access to filesystem tools,
17 Vim editors and other services by configuring them here, then connecting
18 the client to this broker.
19  
20 For each server, give a name prefix and an HTTP URL, a C<stdio:COMMAND>,
21 or C<--- PROGRAM ARG... ---> to start it as a subprocess. These are the downstream
22 servers. The multibroker starts or connects to them, obtains their tool
23 definitions and forwards tool calls and replies between them and your
24 client.
25  
26 The prefix identifies which server a tool belongs to. For example, a
27 filesystem server configured as C<files> has a tool named
28 C<files.read-lines>. Your client can ask the multibroker which servers and
29 tools are available, then call a tool by its prefixed name.
30  
31 The connection from your MCP client to the multibroker is the upstream
32 connection. It can use HTTP or stdin/stdout, independently of how the
33 downstream servers connect. See L<AnyEvent::MCP::Intro> for a complete
34 setup example.
35  
36 =head1 FIRST USE
37  
38 Configure a local MCP client to start a multibroker with two servers:
39  
40 mcp-multibroker --stdio \
41 files --- mcp-fs --name project /home/alice/src/project --- \
42 questions --- mcp-ask-user ---
43  
44 The client launches only the broker; it starts children as needed. Ask:
45  
46 Call discover-brokers and list-tools, then use files.workdirs
47 to show which project directories are configured.
48  
49 C<files> and C<questions> are routing prefixes, not child instance names
50 or permission profiles. Each child still applies its own permissions.
51 The broker selects stdio automatically for bundled AnyEvent::MCP children.
52 Third-party servers must support MCP over stdio in their own startup mode.
53 You can replace a child with any stdio-speaking MCP server by putting
54 its executable and arguments between the C<---> delimiters, or connect
55 an existing HTTP server by URL; see L</DOWNSTREAM SERVERS>.
56  
57 For HTTP clients, omit C<--stdio>, leave the broker running, and obtain
58 its upstream URL with C<--print-url> using the same listener settings.
59 For missing tools, try C<search-tools> with keywords, or
60 C<discover-brokers> for connection errors and C<list-tools> to refresh
61 discovery; your MCP client may also need to
62 refresh its cached list. C<--tool-help> only shows the broker's own
63 tools, not those of its children. Ordinary children start lazily. Use C<--eager>
64 after the child specification for services that accept independent
65 connections, such as Vim or browser brokers.
66  
67 =head1 TOOLS
68  
69 The broker exposes four tools of its own:
70  
71 =over
72  
73 =item discover-brokers
74  
75 Lists the configured downstream servers and their instructions by prefix.
76 An entry is a string of instructions, C<null> for a reachable server with
77 no instructions, or C<{error: MESSAGE}> for an unreachable server.
78 Hidden servers are listed, with instructions on how to discover their tools.
79  
80 =item search-tools
81  
82 Search complete tool definitions from all reachable downstream servers,
83 including hidden ones, but not the broker's own tools. Uses BM25 keyword
84 relevance, searching names, descriptions and argument names and
85 descriptions. Returns up to 25 full tool definitions, ranked by relevance.
86 For example, search for C<edit lines in vim buffer> to find an editor
87 operation without knowing its broker. Call a returned C<PREFIX.TOOL>
88 via C<call-tool>.
89  
90 =item list-tools
91  
92 Queries downstream servers for their tool definitions and refreshes the
93 combined list. An optional C<broker> argument selects one exact downstream
94 prefix, including hidden servers and excluding the multibroker's own tools.
95 Without C<broker>, hidden servers are omitted. Unknown broker names or
96 arguments are errors. Unreachable servers are omitted from tool listings
97 but reported by C<discover-brokers>.
98  
99 =item call-tool
100  
101 Calls a downstream tool by its C<PREFIX.TOOL> name with the supplied
102 arguments, including hidden servers. Calls to an unavailable server fail
103 as tool errors; calls are
104 not replayed after transport failures.
105  
106 =back
107  
108 A refreshed list is a snapshot of what is reachable at that point. It
109 includes configured servers and currently registered reverse connections.
110 A listed server might become unavailable before a later call.
111  
112 =head1 DOWNSTREAM SERVERS
113  
114 Each prefix identifies one downstream server. HTTP URLs may include a URL-path token,
115 or be followed by C<--bearer TOKEN>. C<bearer> and C<timeout> defaults
116 are read from C<[client PREFIX]> in the global configuration; the URL in
117 the command line overrides any configured C<url>. Stdio children receive
118 C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio> and
119 C<PERL_ANYEVENT_MCP_MULTIBROKER_ALIAS=PREFIX> in their environment.
120 The alias may be displayed in downstream permission prompts, without changing
121 the server's instance name or permission rules.
122  
123 For direct execution, use C<PREFIX --- PROGRAM ARG... --->:
124  
125 mcp-multibroker vim --- mcp-vim --bind :: --- --eager \
126 files --- mcp-fs '/home/alice/project with spaces' ---
127  
128 The next exact C<---> argument closes the list. Everything inside, including
129 C<-->, C<--eager> and C<--bearer>, is passed unchanged to the child. There is
130 no shell interpretation. Empty arguments are preserved; the program must be
131 nonempty. An empty list or missing closing delimiter is an error.
132  
133 A subprocess can also connect to an MCP server on another machine via SSH:
134  
135 mcp-multibroker remote-fs --- ssh remotehost mcp-fs --stdio --ask mcp /workdir ---
136  
137 C<--stdio> tells the remote C<mcp-fs> to use stdin/stdout for MCP. It must be
138 specified explicitly because the multibroker's environment variables are
139 not passed through SSH. C<--ask mcp> forwards permission prompts over MCP to
140 the local multibroker, instead of trying to display dialogs on the remote
141 host. The local broker then presents them according to its own C<--ask> mode
142 (normally using a local helper); see L</PERMISSION PROMPTS>.
143  
144 C<stdio:COMMAND> retains shell interpretation. Use it for shell syntax or
145 when a child needs a literal C<---> argument. Quoting C<'---'> in the
146 delimited form cannot escape the delimiter: shell quoting is already gone.
147  
148 Broker-wide options precede the first server entry. Downstream options
149 follow that server's URL or closing C<--->; Getopt::Long stops at the next
150 prefix. Options inside an argv list belong exclusively to the child.
151  
152 C<--hidden> after a server keeps its tools out of normal MCP C<tools/list>
153 and unfiltered C<list-tools> results. This reduces the initial tool list
154 for large or rarely used servers. C<discover-brokers> still lists it;
155 C<list-tools broker=PREFIX>
156 returns its definitions; C<search-tools> includes hidden tools, and
157 C<call-tool> still works. Hiding affects advertisement, not permissions.
158 C<--disable> after a server excludes it entirely: no child is started,
159 no HTTP connection is made, and its tools cannot be discovered or called.
160 The prefix stays reserved so a reverse connection cannot take its place.
161 This takes precedence over C<--eager> and C<--required>; remove the flag
162 to re-enable the server.
163  
164 C<--eager> after either stdio form starts that child at
165 multibroker startup rather than waiting for its first MCP use. This is useful
166 for children that also provide their own TCP service, such as C<mcp-vim>.
167 Other stdio children remain lazy. Eager startup attempts one connection and
168 logs failures; it does not continually restart failed children.
169 C<--required> implies C<--eager> and makes the multibroker exit with failure
170 if that child cannot initialize or later disconnects unexpectedly. A supervisor
171 can then restart the broker. An explicitly accepted managed idle shutdown is
172 not a failure; the child can be started again on the next use. Both options
173 apply only to spawned stdio children, never remote HTTP peers.
174  
175 =head2 Reverse connections
176  
177 The HTTP listener also accepts authenticated reverse MCP connections. It
178 can run with no configured downstream servers. With upstream stdio, add
179 C<--listen> to keep this listener active:
180  
181 mcp-multibroker --stdio --listen --bind 127.0.0.1:31740
182 mcp-multibroker --bind 127.0.0.1:31740 --print-url
183 mcp-fs --connect http://127.0.0.1:31740/TOKEN/files /home/alice/project
184  
185 Use the token returned by C<--print-url>. The connecting server extracts
186 the host, port, token and alias from this URL, sends
187 C<["mcp-connect", token, alias]> followed by a newline, then ordinary MCP
188 JSONL. The connection uses the HTTP listener but is not an HTTP request.
189 With C<--tls-cert> or C<--tls-key>, the same port also accepts TLS, and
190 C<--print-url> prints HTTPS first and HTTP second. Reverse connections using
191 C<https://> verify the listener certificate and hostname; C<http://> uses
192 plaintext.
193 It uses the same accepted tokens as HTTP. Authentication grants registration
194 under any free alias; configured or connected aliases cannot be replaced.
195  
196 The connecting program remains the MCP server. The multibroker attaches an
197 MCP client and discovers its tools immediately. Forms and cancellation follow
198 the same routes as other downstream connections. An unexpected disconnect
199 fails pending calls, removes the registration and starts a new connection
200 period. Refused TCP connections are retried every second, up to sixty times.
201 Other TCP setup failures and TLS verification failures log an error and stop;
202 there is no automatic downgrade to plaintext. No interrupted operation is
203 replayed. Plain HTTP endpoint URLs do not provide transport encryption;
204 use a trusted connection or tunnel as needed.
205  
206 =head2 Process lifetime
207  
208 Each downstream connection advertises C<anyevent-mcp/multibroker> version 1
209 in its client capabilities. A spawned stdio child can request managed idle
210 shutdown with C<anyevent-mcp/idle-exit>. When no calls are outstanding, the
211 broker may send C<anyevent-mcp/shutdown>; the child acknowledges before
212 exiting. This is optional and never makes HTTP children exit. Unexpected
213 disconnects are logged, not proactively restarted. A later use reconnects.
214  
215 =head1 PERMISSION PROMPTS
216  
217 C<--ask helper> (the default) answers downstream form challenges locally.
218 Ordinary forms use C<anyevent-mcp-form-elicitation>; permission requests keep their
219 specialised permission dialogs. C<--ask mcp> forwards modern challenges to
220 the upstream client. C<--ask auto> uses upstream form support when advertised,
221 otherwise the local helper. Both modes deliberately trust the upstream
222 client's user assertion when permission authority has been delegated to it.
223 The multibroker forwards the original authenticated user with every tool call,
224 even when a downstream saved permission rule resolves that request without
225 another prompt. A decline or cancel is never retried through another
226 interface. If a client advertises forms but silently declines them,
227 select C<helper> explicitly.
228  
229 C<--ask tty> and C<--ask yad> select only the built-in terminal or YAD
230 interface for both ordinary forms and permission dialogs. These modes
231 ignore custom helper variables and do not fall back to another interface.
232  
233 The broker advertises its local form support to downstream calls when it
234 will handle their forms itself. In C<mcp> mode it forwards the upstream
235 caller's capabilities instead. Local forms work for HTTP and stdio children,
236 including when the upstream caller cannot handle native input challenges.
237 Continuation tokens remain opaque; the broker sends the human response back
238 to the same downstream operation and returns its eventual result.
239  
240 Spawned stdio children default to C<--ask mcp>, delegating permissions to
241 the multibroker, which handles them according to its own C<--ask> mode.
242 An explicit child C<--ask> overrides this default. Independently running
243 servers keep their own configuration.
244 Spawned C<mcp-ask-user> instances normally delegate presentation to this broker.
245 Use C<--ask mcp> on a separately started C<mcp-ask-user> to delegate to its
246 connecting client, including a multibroker.
247  
248 Local permission and question dialogs share one queue. Set
249 C<PERL_ANYEVENT_MCP_ELICITATION_HELPER> to replace the form helper and
250 C<PERL_ANYEVENT_MCP_PERMISSION_HELPER> to replace the permission helper.
251 Cancelling a tool call cancels its downstream operation and pending local
252 prompt.
253 Downstream C<notifications/progress> are forwarded to the corresponding
254 upstream request by its progress token, including through HTTP children.
255  
256 =head1 CLIENT CONNECTION
257  
258 The upstream listener uses L<AnyEvent::MCP::Server::Simple/mcp_start>: HTTP
259 without stdout output by default, or stdio when run by another broker.
260 The service instance name defaults to C<default>. Repeated
261 C<--token TOKEN> options before the broker pairs configure credentials
262 accepted by the upstream HTTP listener. They are separate from C<--bearer>
263 after a downstream broker URL, which authenticates the client connection.
264 C<--name NAME>
265 selects C<[instance NAME]> in the global configuration, including its
266 credentials and optional C<bind> address. C<--bind ADDRESS[:PORT]> overrides
267 that address. The default is IPv4 loopback with a stable name-derived port
268 in 16384..32767. Port zero requests an ephemeral port.
269 C<--print-url> prints the credential-bearing URL without opening a listener
270 or starting children; it requires a nonzero port. Upstream stdio startup
271 skips HTTP listener configuration unless C<--listen> is specified; named HTTP
272 children still load their client defaults. Browser origins are unrestricted by default; HTTP requests
273 still require an accepted token. See L<AnyEvent::MCP::Intro> for examples.
274  
275 =head1 OPTIONS
276  
277 Shared upstream switches are documented in
278 L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.
279 Put broker-wide options before the first PREFIX/URL pair. Downstream
280 options must immediately follow the server they configure.
281  
282 =head2 Broker options
283  
284 =over
285  
286 =item --listen
287  
288 Keep the upstream HTTP/extension listener active alongside C<--stdio>
289 or C<--connect>. Without those, HTTP is already the default.
290 Applies to the broker, not its downstream servers.
291  
292 =item --ask MODE
293  
294 Select how downstream permission prompts are presented:
295 C<helper> (default), C<tty>, C<yad>, C<mcp>, C<auto>, or C<none>.
296 C<none> replies with a standard decline without invoking any UI.
297 Spawned stdio children delegate to the broker with their own default C<mcp>.
298 See L</PERMISSION PROMPTS>.
299  
300 =back
301  
302 =head2 Downstream options
303  
304 =over
305  
306 =item --bearer TOKEN
307  
308 Authenticate the preceding HTTP(S) child with a bearer token, not
309 the broker's upstream listener. Supply after the child URL;
310 invalid for stdio children.
311  
312 =item --hidden
313  
314 Omit the preceding child's tools from ordinary tool discovery,
315 including unfiltered C<list-tools>. Discover its definitions with
316 C<list-tools> specifying its C<broker> prefix. Its tools remain
317 callable by name. Applies to HTTP and stdio children.
318  
319 =item --disable
320  
321 Ignore the preceding downstream entry without removing it from the command
322 line. No startup, discovery or calls; the prefix remains reserved.
323 Overrides C<--eager> and C<--required>. Applies to HTTP and stdio children.
324  
325 =item --eager
326  
327 Start the preceding stdio child at broker startup instead of on
328 first use. Not available for HTTP children.
329  
330 =item --required
331  
332 Require the preceding stdio child to initialize and remain connected.
333 Implies C<--eager>; an unexpected disconnect causes the broker to exit.
334 Managed idle shutdown is permitted. Not available for HTTP children.
335  
336 =back
337  
338 =head2 Shared-option behavior
339  
340 =over
341  
342 =item --name NAME
343  
344 Select the upstream broker's instance (default C<default>).
345 Does not affect downstream prefixes or their instance names.
346  
347 =item --token TOKEN
348  
349 Authenticate clients of the upstream broker. To authenticate an
350 HTTP(S) child, use C<--bearer> after its URL instead.
351  
352 =item --tool-help
353  
354 Lists only the broker's own tools. Use its C<list-tools> tool to
355 discover individual downstream registries.
356  
357 =item --auto-allow TOOL[,ACTION[,CAPABILITY]]
358  
359 Matches the broker-visible tool names, not a downstream server's
360 independent permission checks.
361  
362 =back
363  
364 =cut
365  
366 28 ▶use common::sense;
Subroutine BEGIN: called CC=1 SCAR=0.0
367 28 ▶use Getopt::Long ();
Subroutine BEGIN: called CC=1 SCAR=0.0
368  
369 28 ▶use AnyEvent ();
Subroutine BEGIN: called CC=1 SCAR=0.0
370 28 ▶use AnyEvent::MCP::Client::HTTP ();
Subroutine BEGIN: called CC=1 SCAR=0.0
371 28 ▶use AnyEvent::MCP::Client::JSONL ();
Subroutine BEGIN: called CC=1 SCAR=0.0
372 28 ▶use AnyEvent::MCP::Permissions::Ask ();
Subroutine BEGIN: called CC=1 SCAR=0.0
373 28 ▶use AnyEvent::MCP::Helper ();
Subroutine BEGIN: called CC=1 SCAR=0.0
374 28 ▶use AnyEvent::MCP::Config ();
Subroutine BEGIN: called CC=1 SCAR=0.0
375 28 ▶use AnyEvent::MCP::Server::Toolset ();
Subroutine BEGIN: called CC=1 SCAR=0.0
376  
377 28 ▶use AnyEvent::MCP::Server::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
378  
379 28 AnyEvent::detect; # initialise child watchers before starting subprocesses.
380 28 $| = 1;
381  
382 28 my $usage = "Usage: $0 [OPTION]... PREFIX (URL | --- PROGRAM ARG... ---) [CHILD-OPTION] ...\n";
383 28 Getopt::Long::Configure ("require_order");
384 28 my $server_options = mcp_getoptions
385 {
386 usage => $usage,
387 path => "/",
388 description => "Combine MCP servers behind one endpoint, with tools named PREFIX.TOOL.\n"
389 . "Each server is HTTP(S), stdio:COMMAND, or --- PROGRAM ARG... ---; downstream options follow its entry.",
390 options => [
391 "Broker-wide options:",
392 ["--listen", "Keep the upstream HTTP listener active alongside stdio or --connect"],
393 "Downstream options (after the URL or closing ---):",
394 ["--eager", "Start the preceding stdio child at broker startup"],
395 ["--required", "Require stdio child; implies --eager, exit on failure"],
396 ["--bearer TOKEN", "Authenticate to the preceding HTTP child"],
397 ["--hidden", "Hide child's tools from default discovery; explicit list-tools and calls still work"],
398 ["--disable", "Exclude the preceding child entirely, keeping its prefix reserved"],
399 ],
400 examples => " $0 --ask auto files 'stdio:mcp-fs /home/alice/src/project'\n"
401 . " $0 files --- mcp-fs /home/alice/src/project --- --eager\n"
402 . " $0 vim --- mcp-vim --bind :: --- --required\n"
403 . " $0 remote https://example.org/mcp/ --bearer TOKEN\n"
404 . " $0 --name tools --print-url",
405 },
406 "listen" => \my $listen,
407 ;
408  
409 22 my $ask_mode = delete $server_options->{ask};
410  
411 $AnyEvent::Log::FILTER->level ("debug")
412 unless defined $ENV{PERL_ANYEVENT_VERBOSE}
413 22 ▶ || ($ENV{PERL_ANYEVENT_LOG} // "") =~ /(?:\A|\s)filter=/;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $ENV{"PERL_ANYEVENT_VERBOSE"} or ($ENV{"PERL_ANYEVENT_LOG"} // "") =~ /(?:\A|\s)filter=/u 1 21 22
Condition60%3/5
defined $ENV{"PERL_ANYEVENT_VERBOSE"} or ($ENV{"PERL_ANYEVENT_LOG"} // "") =~ /(?:\A|\s)filter=/u
l!l&&r!l&&!r
0211
$ENV{"PERL_ANYEVENT_LOG"} // ""
l!l
220
MC/DC0%0/2
defined $ENV{"PERL_ANYEVENT_VERBOSE"} or ($ENV{"PERL_ANYEVENT_LOG"} // "") =~ /(?:\A|\s)filter=/u
defined $ENV{"PERL_ANYEVENT_VERBOSE"} $ENV{"PERL_ANYEVENT_LOG"}
Truth table33%1/3
A or B
A= defined $ENV{"PERL_ANYEVENT_VERBOSE"}B= $ENV{"PERL_ANYEVENT_LOG"}
ABresult
1X1
011
000
414 22 ▶$ask_mode //= $ENV{PERL_ANYEVENT_MCP_PERMISSION_ASK} || "helper";
Condition100%4/4
$ask_mode //= $ENV{"PERL_ANYEVENT_MCP_PERMISSION_ASK"} || "helper"
l!l
139
$ENV{'PERL_ANYEVENT_MCP_PERMISSION_ASK'} || 'helper'
l!l
18
MC/DC100%1/1
$ask_mode //= $ENV{"PERL_ANYEVENT_MCP_PERMISSION_ASK"} || "helper"
$ask_mode
Truth table100%2/2
A
A= $ask_mode
Aresult
11
00
415 22 ▶$ask_mode =~ /\A(?:helper|tty|yad|auto|mcp|none)\z/
Branch: 1 branch
BranchTrueFalseTotal
$ask_mode =~ /\A(?:helper|tty|yad|auto|mcp|none)\z/u or die "--ask must be helper, tty, yad, auto, mcp, or none\n" 22 0 22
416 or die "--ask must be helper, tty, yad, auto, mcp, or none\n";
417  
418 22 my (%broker, %disabled, %stdio, %eager, %required, %hidden, %progress);
419 22 my $shutting_down;
420 22 my @prompts;
421 22 my $prompt;
422  
423 # keep local dialogs serial, including dialogs from different brokers.
424 sub next_prompt;
425 5 ▶sub ask_prompt {
Subroutine ask_prompt: called CC=1 SCAR=2.4
426 5 my ($req, $prepared, $done, $form) = @_;
427  
428 5 my $entry = { request => $req, prepared => $prepared, done => $done, form => $form };
429 5 push @prompts, $entry;
430  
431 5 my $old_cancel = $req->{on_cancel};
432 0 ▶ $req->{on_cancel} = sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
433 AE::log trace => "local prompt cancelled "
434 0 ▶ . (defined $entry->{started} ? sprintf ("after %.2fs", AE::now - $entry->{started}) : "while queued")
Branch: 2 branches
BranchTrueFalseTotal
defined $entry->{'started'} ? : 0 0 0
defined $_[1] ? : 0 0 0
435 . (defined $_[1] ? ": $_[1]" : "");
436 0 ▶ $entry->{job}->cancel if $entry->{job};
Branch: 1 branch
BranchTrueFalseTotal
if $entry->{"job"} 0 0 0
437 0 ▶ $old_cancel->(@_) if $old_cancel;
Branch: 1 branch
BranchTrueFalseTotal
if $old_cancel 0 0 0
438 5 };
439 5 next_prompt;
440 }
441  
442 10 ▶sub next_prompt {
Subroutine next_prompt: called CC=11 SCAR=27.6
443 10 ▶ return if $prompt;
Branch: 1 branch
BranchTrueFalseTotal
if $prompt 0 10 10
444 10 ▶ while (@prompts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@prompts) 5 5 10
445 5 my $entry = shift @prompts;
446 5 ▶ next if $entry->{request}{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $entry->{"request"}{"finished"} 0 5 5
447 5 $prompt = $entry;
448 $entry->{job} = $entry->{form}
449 ? AnyEvent::MCP::Helper->new (
450 helper => $ask_mode eq "tty" || $ask_mode eq "yad"
451 ? ["anyevent-mcp-form-elicitation", "--$ask_mode"]
452 5 ▶ : $ENV{PERL_ANYEVENT_MCP_ELICITATION_HELPER} || "anyevent-mcp-form-elicitation",
Branch: 3 branches
BranchTrueFalseTotal
$entry->{'form'} ? : 0 5 5
$ask_mode eq 'tty' || $ask_mode eq 'yad' ? : 0 0 0
$ask_mode eq 'tty' || $ask_mode eq 'yad' ? : 2 3 5
Condition37%3/8
$ask_mode eq "tty" or $ask_mode eq "yad"
l!l&&r!l&&!r
000
$ENV{"PERL_ANYEVENT_MCP_ELICITATION_HELPER"} or "anyevent-mcp-form-elicitation"
l!l
00
$ask_mode eq "tty" or $ask_mode eq "yad"
l!l&&r!l&&!r
113
MC/DC0%0/2
$ask_mode eq "tty" or $ask_mode eq "yad"
$ask_mode eq "tty" $ask_mode eq "yad"
MC/DC0%0/1
$ENV{"PERL_ANYEVENT_MCP_ELICITATION_HELPER"} or "anyevent-mcp-form-elicitation"
$ENV{"PERL_ANYEVENT_MCP_ELICITATION_HELPER"}
MC/DC100%2/2
$ask_mode eq "tty" or $ask_mode eq "yad"
$ask_mode eq "tty" $ask_mode eq "yad"
Truth table0%0/3
A or B
A= $ask_mode eq "tty"B= $ask_mode eq "yad"
ABresult
1X1
011
000
Truth table0%0/2
A
A= $ENV{"PERL_ANYEVENT_MCP_ELICITATION_HELPER"}
Aresult
11
00
Truth table100%3/3
A or B
A= $ask_mode eq "tty"B= $ask_mode eq "yad"
ABresult
1X1
011
000
453 timeout => 1800,
454 )
455 : AnyEvent::MCP::Permissions::Ask->new (
456 ($ask_mode eq "tty" || $ask_mode eq "yad"
457 ? (helper => ["anyevent-mcp-askpermission", "--$ask_mode"]) : ()),
458 );
459 5 $entry->{started} = AE::now;
460 5 ▶ AE::log trace => "local prompt started (" . ($entry->{form} ? "form" : "permission") . ")";
Branch: 1 branch
BranchTrueFalseTotal
$entry->{'form'} ? : 0 5 5
461 5 ▶ $entry->{job}->ask ($entry->{prepared}, sub {
Subroutine __ANON__: called CC=7 SCAR=21.8
462 5 my ($success, $result) = @_;
463  
464 5 ▶ unless ($entry->{request}{finished}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($entry->{"request"}{"finished"}) 5 0 5
465 my $outcome = $success
466 5 ▶ ? (ref $result eq "HASH" ? $result->{decision} || $result->{action} || "answered" : "answered")
Branch: 2 branches
BranchTrueFalseTotal
$success ? : 5 0 5
ref $result eq 'HASH' ? : 5 0 5
Condition40%2/5
$result->{"decision"} or $result->{"action"} or "answered"
l!l
50
$result->{"decision"} or $result->{"action"}
l!l&&r!l&&!r
500
MC/DC0%0/2
$result->{"decision"} or $result->{"action"} or "answered"
$result->{"decision"} $result->{"action"}
Truth table33%1/3
A or B
A= $result->{"decision"}B= $result->{"action"}
ABresult
1X1
011
000
467 : "failed: $result";
468 5 AE::log trace => sprintf "local prompt %s after %.2fs", $outcome, AE::now - $entry->{started};
469 }
470 5 undef $prompt;
471 5 delete $entry->{job};
472 5 ▶ $entry->{done}->($success, $result) unless $entry->{request}{finished};
Branch: 1 branch
BranchTrueFalseTotal
unless $entry->{"request"}{"finished"} 5 0 5
473 5 next_prompt;
474 5 });
475 return
476 5 }
477 }
478  
479 7 ▶sub on_input {
Subroutine on_input: called CC=12 SCAR=39.4
480 7 my ($client, $req) = @_;
481  
482 return $req->error (-32601, "Only form elicitation is supported locally")
483 7 ▶ unless $req->{method} eq "elicitation/create";
Branch: 1 branch
BranchTrueFalseTotal
unless $req->{"method"} eq "elicitation/create" 0 7 7
484 7 ▶ return $req->reply ({ action => "decline" }) if $ask_mode eq "none";
Branch: 1 branch
BranchTrueFalseTotal
if $ask_mode eq "none" 2 5 7
485  
486 5 my $meta = $req->{params}{_meta}{"anyevent-mcp/permission"};
487 5 ▶ unless (defined $meta) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $meta) 0 5 5
488 return $req->error (-32602, "Only form elicitation is supported locally")
489 0 ▶ if defined $req->{params}{mode} && $req->{params}{mode} ne "form";
Branch: 1 branch
BranchTrueFalseTotal
if defined $req->{"params"}{"mode"} and $req->{"params"}{"mode"} ne "form" 0 0 0
Condition0%0/3
defined $req->{"params"}{"mode"} and $req->{"params"}{"mode"} ne "form"
!ll&&!rl&&r
000
MC/DC0%0/2
defined $req->{"params"}{"mode"} and $req->{"params"}{"mode"} ne "form"
defined $req->{"params"}{"mode"} $req->{"params"}{"mode"} ne "form"
Truth table0%0/3
A and B
A= defined $req->{"params"}{"mode"}B= $req->{"params"}{"mode"} ne "form"
ABresult
0X0
100
111
490 defined $req->{params}{message} && !ref $req->{params}{message}
491 0 ▶ or return $req->error (-32602, "Form needs a message");
Branch: 1 branch
BranchTrueFalseTotal
defined $req->{"params"}{"message"} and not ref $req->{"params"}{"message"} or return $req->error(-32602, "Form needs a message") 0 0 0
Condition0%0/3
defined $req->{"params"}{"message"} and not ref $req->{"params"}{"message"}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $req->{"params"}{"message"} and not ref $req->{"params"}{"message"}
defined $req->{"params"}{"message"} not ref $req->{"params"}{"message"}
Truth table0%0/3
A and not(B)
A= defined $req->{"params"}{"message"}B= not ref $req->{"params"}{"message"}
ABresult
0X0
100
111
492 ask_prompt $req, {
493 0 %{$req->{params}},
494 message => "Server: $client->{name}\n\n$req->{params}{message}",
495 0 ▶ }, sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
496 0 my ($success, $response) = @_;
497  
498 0 ▶ return $req->error (-32603, $response) unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
499 0 ▶ my $action = ref $response eq "HASH" ? $response->{action} : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $response eq 'HASH' ? : 0 0 0
500 defined $action && !ref $action && $action =~ /\A(?:accept|decline|cancel)\z/
501 0 ▶ && ($action ne "accept" || ref $response->{content} eq "HASH")
Branch: 1 branch
BranchTrueFalseTotal
defined $action and not ref $action and $action =~ /\A(?:accept|decline|cancel)\z/u and $action ne "accept" || ref $response->{"content"} eq "HASH" or return $req->error(-32603, "Invalid form helper response") 0 0 0
Condition0%0/12
defined $action and not ref $action and $action =~ /\A(?:accept|decline|cancel)\z/u and $action ne "accept" || ref $response->{"content"} eq "HASH"
!ll&&!rl&&r
000
defined $action and not ref $action and $action =~ /\A(?:accept|decline|cancel)\z/u
!ll&&!rl&&r
000
defined $action and not ref $action
!ll&&!rl&&r
000
$action ne "accept" or ref $response->{"content"} eq "HASH"
l!l&&r!l&&!r
000
MC/DC0%0/5
defined $action and not ref $action and $action =~ /\A(?:accept|decline|cancel)\z/u and $action ne "accept" || ref $response->{"content"} eq "HASH"
defined $action not ref $action $action =~ /\A(?:accept|decline|cancel)\z/u $action ne "accept" ref $response->{"content"} eq "HASH"
Truth table0%0/6
A and not(B) and C and D or E
A= defined $actionB= not ref $actionC= $action =~ /\A(?:accept|decline|cancel)\z/uD= $action ne "accept"E= ref $response->{"content"} eq "HASH"
ABCDEresult
0XXXX0
10XXX0
110XX0
111000
1111X1
111011
502 or return $req->error (-32603, "Invalid form helper response");
503 $req->reply ({
504 action => $action,
505 0 ▶ ($action eq "accept" ? (content => $response->{content}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
$action eq 'accept' ? : 0 0 0
506 });
507 0 }, 1;
508 0 return;
509 }
510 return $req->error (-32601, "Invalid permission elicitation")
511 5 ▶ unless ref $meta eq "HASH" && $meta->{version} == 1 && ref $meta->{request} eq "HASH";
Branch: 1 branch
BranchTrueFalseTotal
unless ref $meta eq "HASH" and $meta->{"version"} == 1 and ref $meta->{"request"} eq "HASH" 0 5 5
Condition33%2/6
ref $meta eq "HASH" and $meta->{"version"} == 1 and ref $meta->{"request"} eq "HASH"
!ll&&!rl&&r
005
ref $meta eq "HASH" and $meta->{"version"} == 1
!ll&&!rl&&r
005
MC/DC0%0/3
ref $meta eq "HASH" and $meta->{"version"} == 1 and ref $meta->{"request"} eq "HASH"
ref $meta eq "HASH" $meta->{"version"} == 1 ref $meta->{"request"} eq "HASH"
Truth table25%1/4
A and B and C
A= ref $meta eq "HASH"B= $meta->{"version"} == 1C= ref $meta->{"request"} eq "HASH"
ABCresult
0XX0
10X0
1100
1111
512  
513 5 my $stage = $meta->{stage};
514  
515 ask_prompt $req, {
516 5 ▶ %{$meta->{request}},
Condition100%2/2
$meta->{'selection'} || {}
l!l
23
MC/DC100%1/1
$meta->{'selection'} || {}
$meta->{'selection'}
Truth table100%2/2
A
A= $meta->{'selection'}
Aresult
11
00
517 _permission_stage => $stage,
518 _permission_selection => $meta->{selection} || {},
519 5 ▶ }, sub {
Subroutine __ANON__: called CC=11 SCAR=33.1
520 5 my ($success, $decision) = @_;
521  
522 5 ▶ return $req->error (-32603, $decision) unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 5 5
523 5 my $valid = eval {
524 AnyEvent::MCP::Permissions::Ask::build ($meta->{request}, {
525 %$decision,
526 (ref $decision->{rule} eq "HASH"
527 0 ▶ ? (map { $_ => $decision->{rule}{$_} } qw(path)) : ()),
Branch: 1 branch
BranchTrueFalseTotal
ref $decision->{'rule'} eq 'HASH' ? : 0 5 5
528 (ref $decision->{rule} eq "HASH"
529 0 ? (map { (my $key = $_) =~ s/^match\./dim_/; $key => $decision->{rule}{$_} }
530 0 grep /^match\./, keys %{$decision->{rule}}) : ()),
531 }, $stage, $meta->{selection})
532 5 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
ref $decision->{'rule'} eq 'HASH' ? : 0 5 5
533 5 ▶ return $req->error (-32603, "Invalid permission helper decision: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 5 5
534 $req->reply ({
535 action => "accept",
536 content => {
537 decision => $valid->{decision},
538 (exists $valid->{sandbox_grants}
539 5 ▶ ? (sandbox_grants => join ",", @{$valid->{sandbox_grants}}) : ()),
Branch: 4 branches
BranchTrueFalseTotal
defined $valid->{'message'} ? : 0 5 5
exists $valid->{'lifetime'} ? : 0 5 5
ref $valid->{'rule'} eq 'HASH' && defined $valid->{'rule'}{'path'} ? : 0 5 5
ref $valid->{'rule'} eq 'HASH' ? : 0 5 5
Condition33%1/3
ref $valid->{"rule"} eq "HASH" and defined $valid->{"rule"}{"path"}
!ll&&!rl&&r
500
MC/DC0%0/2
ref $valid->{"rule"} eq "HASH" and defined $valid->{"rule"}{"path"}
ref $valid->{"rule"} eq "HASH" defined $valid->{"rule"}{"path"}
Truth table33%1/3
A and B
A= ref $valid->{"rule"} eq "HASH"B= defined $valid->{"rule"}{"path"}
ABresult
0X0
100
111
540 (defined $valid->{message} ? (message => $valid->{message}) : ()),
541 (exists $valid->{lifetime} ? (lifetime => $valid->{lifetime}) : ()),
542 (ref $valid->{rule} eq "HASH" && defined $valid->{rule}{path}
543 ? (path => $valid->{rule}{path}) : ()),
544 (ref $valid->{rule} eq "HASH"
545 0 ? (map { (my $key = $_) =~ s/^match\./dim_/; $key => $valid->{rule}{$_} }
546 0 ▶ grep /^match\./, keys %{$valid->{rule}}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
exists $valid->{'sandbox_grants'} ? : 5 0 5
547 },
548 });
549 5 };
550 }
551  
552 2 ▶sub on_child_notification {
Subroutine on_child_notification: called CC=11 SCAR=40.6
553 2 my ($prefix, $client, $method, $params) = @_;
554  
555 2 ▶ if ($method eq "notifications/progress" && ref $params eq "HASH") {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "notifications/progress" and ref $params eq "HASH") 2 0 2
Condition33%1/3
$method eq "notifications/progress" and ref $params eq "HASH"
!ll&&!rl&&r
002
MC/DC0%0/2
$method eq "notifications/progress" and ref $params eq "HASH"
$method eq "notifications/progress" ref $params eq "HASH"
Truth table33%1/3
A and B
A= $method eq "notifications/progress"B= ref $params eq "HASH"
ABresult
0X0
100
111
556 2 my $token = $params->{progressToken};
557 2 ▶ return unless defined $token && !ref $token;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $token and not ref $token 0 2 2
Condition33%1/3
defined $token and not ref $token
!ll&&!rl&&r
002
MC/DC0%0/2
defined $token and not ref $token
defined $token not ref $token
Truth table33%1/3
A and not(B)
A= defined $tokenB= not ref $token
ABresult
0X0
100
111
558 2 ▶ my $req = $progress{$prefix}{$token} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $req = $progress{$prefix}{$token} or return 2 0 2
559 $req->progress ($params->{progress}, $params->{total}, $params->{message})
560 2 ▶ unless $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
unless $req->{"finished"} 2 0 2
561 2 return;
562 }
563  
564 0 ▶ return unless $stdio{$prefix} && $method eq "anyevent-mcp/idle-exit";
Branch: 1 branch
BranchTrueFalseTotal
unless $stdio{$prefix} and $method eq "anyevent-mcp/idle-exit" 0 0 0
Condition0%0/3
$stdio{$prefix} and $method eq "anyevent-mcp/idle-exit"
!ll&&!rl&&r
000
MC/DC0%0/2
$stdio{$prefix} and $method eq "anyevent-mcp/idle-exit"
$stdio{$prefix} $method eq "anyevent-mcp/idle-exit"
Truth table0%0/3
A and B
A= $stdio{$prefix}B= $method eq "anyevent-mcp/idle-exit"
ABresult
0X0
100
111
565 0 ▶ return if $client->{idle_shutdown_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $client->{"idle_shutdown_pending"} 0 0 0
566 # the child offered to exit; only act while no broker calls need it.
567 0 ▶ return if keys %{$client->{operations}};
Branch: 1 branch
BranchTrueFalseTotal
if keys %{$$client{"operations"};} 0 0 0
568  
569 0 $client->{idle_shutdown_pending} = 1;
570 0 ▶ $client->rpc ("anyevent-mcp/shutdown", {}, sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
571 0 my ($success, $result) = @_;
572  
573 0 ▶ if ($success && $result->{accepted}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success and $result->{'accepted'}) { } 0 0 0
Condition0%0/3
$success and $result->{"accepted"}
!ll&&!rl&&r
000
MC/DC0%0/2
$success and $result->{"accepted"}
$success $result->{"accepted"}
Truth table0%0/3
A and B
A= $successB= $result->{"accepted"}
ABresult
0X0
100
111
574 0 $client->{idle_shutdown_expected} = 1;
575 } else {
576 AE::log debug => "$prefix: idle shutdown declined: "
577 0 ▶ . ($result->{message} || "child is busy");
Condition0%0/2
$result->{'message'} || 'child is busy'
l!l
00
MC/DC0%0/1
$result->{'message'} || 'child is busy'
$result->{'message'}
Truth table0%0/2
A
A= $result->{'message'}
Aresult
11
00
578 }
579 0 delete $client->{idle_shutdown_pending};
580 0 });
581 }
582  
583 # required children must not leave spawned peers running after broker failure.
584 0 ▶sub required_failure {
Subroutine required_failure: not called CC=2 SCAR=17.9
585 0 my ($prefix, $message) = @_;
586 0 AE::log error => "$prefix: required child $message";
587 0 $shutting_down = 1;
588 0 $_->close for values %broker;
589 0 exit 1;
590 }
591  
592 0 ▶sub on_child_close {
Subroutine on_child_close: not called CC=9 SCAR=45.0
593 0 my ($prefix, $client, $error) = @_;
594  
595 0 ▶ return if $shutting_down;
Branch: 1 branch
BranchTrueFalseTotal
if $shutting_down 0 0 0
596 0 ▶ if (delete $client->{idle_shutdown_expected}) {
Branch: 3 branches
BranchTrueFalseTotal
if (delete $client->{'idle_shutdown_expected'}) { } 0 0 0
elsif ($required{$prefix}) { } 0 0 0
elsif ($stdio{$prefix} or $error->{'pending'}) { } 0 0 0
597 0 mcp_log "$prefix: managed idle shutdown";
598 } elsif ($required{$prefix}) {
599 required_failure $prefix, "disconnected: $error->{message}"
600 0 ▶ . ($error->{pending} ? " ($error->{pending} outstanding requests)" : "");
Branch: 1 branch
BranchTrueFalseTotal
$error->{'pending'} ? : 0 0 0
601 ▶ } elsif ($stdio{$prefix} || $error->{pending}) {
Condition0%0/3
$stdio{$prefix} or $error->{"pending"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$stdio{$prefix} or $error->{"pending"}
$stdio{$prefix} $error->{"pending"}
Truth table0%0/3
A or B
A= $stdio{$prefix}B= $error->{"pending"}
ABresult
1X1
011
000
602 my $message = "$prefix: unexpected disconnect: $error->{message}"
603 0 ▶ . ($error->{pending} ? " ($error->{pending} outstanding requests)" : "");
Branch: 1 branch
BranchTrueFalseTotal
$error->{'pending'} ? : 0 0 0
604 0 ▶ AE::log warn => $message or mcp_log $message;
Branch: 1 branch
BranchTrueFalseTotal
&AE::log("warn", $message) or mcp_log($message) 0 0 0
605 } else {
606 0 mcp_log "$prefix: disconnected: $error->{message}";
607 }
608 0 delete $client->{idle_shutdown_pending};
609 }
610  
611 38 ▶sub broker_config {
Subroutine broker_config: called CC=1 SCAR=0.1
612 38 my ($prefix) = @_;
613  
614 (
615 name => $prefix,
616 client_info => { name => "mcp-multibroker", version => "$AnyEvent::MCP::VERSION" },
617 client_capabilities => {
618 elicitation => { form => {} },
619 extensions => { "anyevent-mcp/multibroker" => { version => 1 } },
620 },
621 on_request => \&on_input,
622 31 ▶ on_ready => sub { mcp_log "$prefix: connected" },
Subroutine __ANON__: called CC=1 SCAR=0.0
623 2 ▶ on_notification => sub { on_child_notification ($prefix, @_) },
Subroutine __ANON__: called CC=1 SCAR=0.0
624 0 ▶ on_close => sub { on_child_close ($prefix, @_) },
Subroutine __ANON__: not called CC=1 SCAR=6.9
625 )
626 38 }
627  
628 0 ▶sub accept_extension {
Subroutine accept_extension: not called CC=8 SCAR=42.8
629 0 my ($server, $handle, $hello) = @_;
630  
631 0 ▶ @$hello == 3 && $hello->[0] eq "mcp-connect"
Branch: 1 branch
BranchTrueFalseTotal
@$hello == 3 and $hello->[0] eq "mcp-connect" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[A-Za-z0-9_-]+\z/u or die "Invalid reverse MCP hello\n" 0 0 0
Condition0%0/12
@$hello == 3 and $hello->[0] eq "mcp-connect" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[A-Za-z0-9_-]+\z/u
!ll&&!rl&&r
000
@$hello == 3 and $hello->[0] eq "mcp-connect" and defined $hello->[2] and not ref $hello->[2]
!ll&&!rl&&r
000
@$hello == 3 and $hello->[0] eq "mcp-connect" and defined $hello->[2]
!ll&&!rl&&r
000
@$hello == 3 and $hello->[0] eq "mcp-connect"
!ll&&!rl&&r
000
MC/DC0%0/5
@$hello == 3 and $hello->[0] eq "mcp-connect" and defined $hello->[2] and not ref $hello->[2] and $hello->[2] =~ /\A[A-Za-z0-9_-]+\z/u
@$hello == 3 $hello->[0] eq "mcp-connect" defined $hello->[2] not ref $hello->[2] $hello->[2] =~ /\A[A-Za-z0-9_-]+\z/u
Truth table0%0/6
A and B and C and not(D) and E
A= @$hello == 3B= $hello->[0] eq "mcp-connect"C= defined $hello->[2]D= not ref $hello->[2]E= $hello->[2] =~ /\A[A-Za-z0-9_-]+\z/u
ABCDEresult
0XXXX0
10XXX0
110XX0
1110X0
111100
111111
632 && defined $hello->[2] && !ref $hello->[2] && $hello->[2] =~ /\A[A-Za-z0-9_-]+\z/
633 or die "Invalid reverse MCP hello\n";
634 0 my $prefix = $hello->[2];
635 0 ▶ !exists $broker{$prefix} && !$disabled{$prefix} or die "Broker alias '$prefix' is occupied\n";
Branch: 1 branch
BranchTrueFalseTotal
exists $broker{$prefix} || $disabled{$prefix} and die "Broker alias '${prefix}' is occupied\n" 0 0 0
Condition0%0/3
exists $broker{$prefix} or $disabled{$prefix}
l!l&&r!l&&!r
000
MC/DC0%0/2
exists $broker{$prefix} or $disabled{$prefix}
exists $broker{$prefix} $disabled{$prefix}
Truth table0%0/3
A or B
A= exists $broker{$prefix}B= $disabled{$prefix}
ABresult
1X1
011
000
636  
637 my $client = AnyEvent::MCP::Client::JSONL->new (
638 broker_config ($prefix),
639 0 ▶ on_close => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
640 0 on_child_close ($prefix, @_);
641 0 ▶ delete $broker{$prefix} if $broker{$prefix} == $_[0];
Branch: 1 branch
BranchTrueFalseTotal
if $broker{$prefix} == $_[0] 0 0 0
642 },
643 0 );
644 0 $broker{$prefix} = $client;
645 0 $client->attach ($handle);
646 0 ▶ $client->connect (sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
647 0 my ($success, $error) = @_;
648  
649 0 ▶ unless ($success) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($success) 0 0 0
650 0 AE::log warn => "$prefix: reverse MCP initialization failed: $error->{message}";
651 0 ▶ delete $broker{$prefix} if $broker{$prefix} == $client;
Branch: 1 branch
BranchTrueFalseTotal
if $broker{$prefix} == $client 0 0 0
652 0 $client->close;
653 }
654 0 });
655 }
656  
657 22 ▶while (@ARGV) {
Branch: 1 branch
BranchTrueFalseTotal
if (@ARGV) 38 22 60
658 38 ▶ @ARGV >= 2 or die $usage;
Branch: 1 branch
BranchTrueFalseTotal
@ARGV >= 2 or die $usage 38 0 38
659 38 my ($prefix, $url) = splice @ARGV, 0, 2;
660 38 ▶ $prefix =~ /\A[A-Za-z0-9_-]+\z/ or die "Invalid broker prefix '$prefix'\n";
Branch: 1 branch
BranchTrueFalseTotal
$prefix =~ /\A[A-Za-z0-9_-]+\z/u or die "Invalid broker prefix '${prefix}'\n" 38 0 38
661 38 ▶ (exists $broker{$prefix} || $disabled{$prefix}) and die "Duplicate broker prefix '$prefix'\n";
Branch: 1 branch
BranchTrueFalseTotal
exists $broker{$prefix} || $disabled{$prefix} and die "Duplicate broker prefix '${prefix}'\n" 0 38 38
Condition33%1/3
exists $broker{$prefix} or $disabled{$prefix}
l!l&&r!l&&!r
0038
MC/DC0%0/2
exists $broker{$prefix} or $disabled{$prefix}
exists $broker{$prefix} $disabled{$prefix}
Truth table33%1/3
A or B
A= exists $broker{$prefix}B= $disabled{$prefix}
ABresult
1X1
011
000
662  
663 38 my $command;
664  
665 38 ▶ if ($url eq "---") {
Branch: 2 branches
BranchTrueFalseTotal
if ($url eq '---') { } 1 37 38
elsif ($url =~ s/\Astdio://u) { } 21 16 37
666 1 my ($end) = grep $ARGV[$_] eq "---", 0 .. $#ARGV;
667 1 ▶ defined $end or die "Missing closing --- for '$prefix'\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $end or die "Missing closing --- for '${prefix}'\n" 1 0 1
668 1 $command = [splice @ARGV, 0, $end];
669 1 shift @ARGV;
670 1 ▶ @$command && length $command->[0] or die "Empty stdio argv for '$prefix'\n";
Branch: 1 branch
BranchTrueFalseTotal
@$command and length $command->[0] or die "Empty stdio argv for '${prefix}'\n" 1 0 1
Condition33%1/3
@$command and length $command->[0]
!ll&&!rl&&r
001
MC/DC0%0/2
@$command and length $command->[0]
@$command length $command->[0]
Truth table33%1/3
A and B
A= @$commandB= length $command->[0]
ABresult
0X0
100
111
671 } elsif ($url =~ s/\Astdio://) {
672 21 ▶ length $url or die "Empty stdio command for '$prefix'\n";
Branch: 1 branch
BranchTrueFalseTotal
length $url or die "Empty stdio command for '${prefix}'\n" 21 0 21
673 # preserve shell commands, but let ordinary programs receive TERM directly.
674 21 ▶ $command = $url =~ / ^\s*(?: exec\b | source\b | \.\s ) | = | ; | \( | \{ | \|\| | && /x
Branch: 1 branch
BranchTrueFalseTotal
$url =~ / ^\s*(?: exec\b | source\b | \.\s ) | = | ; | \( | \{ | \|\| | && /ux ? : 0 21 21
675 ? $url : "exec $url";
676 }
677  
678 38 my %config = broker_config $prefix;
679 38 my ($hide, $disable, $eager, $require);
680 Getopt::Long::GetOptionsFromArray (\@ARGV,
681 0 ▶ "eager" => sub { $eager = 1 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
682 2 ▶ "hidden" => sub { $hide = 1 },
Subroutine __ANON__: called CC=1 SCAR=0.0
683 0 ▶ "disable" => sub { $disable = 1 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
684 0 ▶ "required" => sub { $eager = $require = 1 },
Subroutine __ANON__: not called CC=1 SCAR=6.9
685 13 ▶ "bearer=s" => sub {
Subroutine __ANON__: called CC=4 SCAR=16.1
686 13 ▶ !defined $command && $url =~ m{\Ahttps?://} or die "Authentication options require an HTTP broker\n";
Branch: 1 branch
BranchTrueFalseTotal
not defined $command and $url =~ m[\Ahttps?://]u or die "Authentication options require an HTTP broker\n" 13 0 13
Condition33%1/3
not defined $command and $url =~ m[\Ahttps?://]u
!ll&&!rl&&r
0013
MC/DC0%0/2
not defined $command and $url =~ m[\Ahttps?://]u
not defined $command $url =~ m[\Ahttps?://]u
Truth table33%1/3
not(A) and B
A= not defined $commandB= $url =~ m[\Ahttps?://]u
ABresult
0X0
100
111
687 13 ▶ length $_[1] or die "Missing bearer token for '$prefix'\n";
Branch: 1 branch
BranchTrueFalseTotal
length $_[1] or die "Missing bearer token for '${prefix}'\n" 13 0 13
688 13 $config{bearer} = $_[1];
689 },
690 38 ▶ ) or die $usage;
Branch: 1 branch
BranchTrueFalseTotal
&Getopt::Long::GetOptionsFromArray(\@ARGV, "eager", sub { $eager = 1; } , "hidden", sub { $hide = 1; } , "disable", sub { $disable = 1; } , "required", sub { $eager = $require = 1; } , "bearer=s", sub { not defined $command and $url =~ m[\Ahttps?://]u or die "Authentication options require an HTTP broker\n"; length $_[1] or die "Missing bearer token for '${prefix}'\n"; $config{"bearer"} = $_[1]; } ) or die $usage 38 0 38
691  
692 38 ▶ defined $command || $url =~ m{\Ahttps?://} or die "Invalid broker URL '$url'\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $command or $url =~ m[\Ahttps?://]u or die "Invalid broker URL '${url}'\n" 38 0 38
Condition66%2/3
defined $command or $url =~ m[\Ahttps?://]u
l!l&&r!l&&!r
22160
MC/DC0%0/2
defined $command or $url =~ m[\Ahttps?://]u
defined $command $url =~ m[\Ahttps?://]u
Truth table66%2/3
A or B
A= defined $commandB= $url =~ m[\Ahttps?://]u
ABresult
1X1
011
000
693 38 ▶ if ($disable) {
Branch: 1 branch
BranchTrueFalseTotal
if ($disable) 0 38 38
694 0 $disabled{$prefix} = 1;
695 0 mcp_log "$prefix: disabled";
696 0 next;
697 }
698 38 ▶ defined $command || !$require or die "--required requires a stdio broker ('$prefix')\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $command or not $require or die "--required requires a stdio broker ('${prefix}')\n" 38 0 38
Condition66%2/3
defined $command or not $require
l!l&&r!l&&!r
22160
MC/DC0%0/2
defined $command or not $require
defined $command not $require
Truth table66%2/3
A or not(B)
A= defined $commandB= not $require
ABresult
1X1
011
000
699 38 ▶ defined $command || !$eager or die "--eager requires a stdio broker ('$prefix')\n";
Branch: 1 branch
BranchTrueFalseTotal
defined $command or not $eager or die "--eager requires a stdio broker ('${prefix}')\n" 38 0 38
Condition66%2/3
defined $command or not $eager
l!l&&r!l&&!r
22160
MC/DC0%0/2
defined $command or not $eager
defined $command not $eager
Truth table66%2/3
A or not(B)
A= defined $commandB= not $eager
ABresult
1X1
011
000
700 38 ▶ $hidden{$prefix} = 1 if $hide;
Branch: 1 branch
BranchTrueFalseTotal
if $hide 2 36 38
701 38 ▶ $eager{$prefix} = 1 if $eager;
Branch: 1 branch
BranchTrueFalseTotal
if $eager 0 38 38
702 38 ▶ $required{$prefix} = 1 if $require;
Branch: 1 branch
BranchTrueFalseTotal
if $require 0 38 38
703  
704 38 ▶ if (defined $command) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $command) { } 22 16 38
705 22 $broker{$prefix} = AnyEvent::MCP::Client::JSONL->new (
706 %config, command => $command,
707 env => {
708 PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL => "stdio",
709 PERL_ANYEVENT_MCP_MULTIBROKER_ALIAS => $prefix,
710 PERL_ANYEVENT_MCP_PERMISSION_ASK => "mcp",
711 },
712 );
713 22 $stdio{$prefix} = 1;
714 } else {
715 16 $broker{$prefix} = AnyEvent::MCP::Client::HTTP->new (%config, url => $url);
716 }
717 }
718  
719 22 my $toolset = AnyEvent::MCP::Server::Toolset->new;
720  
721 64 ▶sub broker_alias {
Subroutine broker_alias: called CC=3 SCAR=11.0
722 64 my ($name) = @_;
723 64 ▶ return $name if exists $broker{$name} || $disabled{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $broker{$name} or $disabled{$name} 59 5 64
Condition66%2/3
exists $broker{$name} or $disabled{$name}
l!l&&r!l&&!r
5905
MC/DC50%1/2
exists $broker{$name} or $disabled{$name}
exists $broker{$name} $disabled{$name}
Truth table66%2/3
A or B
A= exists $broker{$name}B= $disabled{$name}
ABresult
1X1
011
000
724 5 $name =~ tr/_/-/;
725 5 $name
726 }
727  
728 30 ▶sub all_tools {
Subroutine all_tools: called CC=6 SCAR=18.0
729 30 my ($req, $done, $name, $include_hidden) = @_;
730  
731 30 ▶ my @tools = defined $name ? () : map @{$_->list}, @{$req->{server}{toolsets}};
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 7 23 30
732 30 ▶ my @prefix = defined $name ? ($name) : grep $include_hidden || !$hidden{$_}, sort keys %broker;
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 7 23 30
Condition100%3/3
$include_hidden || !$hidden{$_}
l!l&&r!l&&!r
13274
MC/DC100%2/2
$include_hidden || !$hidden{$_}
$include_hidden !$hidden{$_}
Truth table100%3/3
A || not(B)
A= $include_hiddenB= !$hidden{$_}
ABresult
1X1
011
000
733 30 my @results;
734 30 my %pending = map { $_ => 1 } @prefix;
735 30 my $remaining = @prefix;
736 30 my $finished;
737 my $timer;
738 30 ▶ my $finish = sub {
Subroutine __ANON__: called CC=5 SCAR=16.4
739 30 ▶ return if $finished++;
Branch: 1 branch
BranchTrueFalseTotal
if $finished++ 0 30 30
740 30 undef $timer;
741 30 ▶ push @tools, @{$_ || []} for @results;
Condition100%2/2
$_ || []
l!l
461
MC/DC100%1/1
$_ || []
$_
Truth table100%2/2
A
A= $_
Aresult
11
00
742 30 ▶ $done->(\@tools) unless $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
unless $req->{"finished"} 30 0 30
743 30 };
744 30 ▶ return $finish->() unless $remaining;
Branch: 1 branch
BranchTrueFalseTotal
unless $remaining 0 30 30
745  
746 0 ▶ $timer = AnyEvent->timer (after => 15, cb => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
747 0 AE::log warn => "Tool discovery timed out: " . join ", ", sort keys %pending;
748 0 $finish->();
749 30 });
750 30 for my $i (0 .. $#prefix) {
751 47 my $prefix = $prefix[$i];
752 47 my $client = $broker{$prefix};
753 47 ▶ $client->tools (sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
754 47 ▶ return if $finished;
Branch: 1 branch
BranchTrueFalseTotal
if $finished 0 47 47
755 47 my ($success, $result) = @_;
756 47 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) { } 46 1 47
757 46 $results[$i] = [map { +{ %$_, name => "$prefix.$_->{name}" } } @$result];
758 } else {
759 1 AE::log warn => "$prefix: $result->{message}";
760 }
761 47 delete $pending{$prefix};
762 47 ▶ $finish->() unless --$remaining;
Branch: 1 branch
BranchTrueFalseTotal
unless --$remaining 30 17 47
763 47 });
764 }
765 }
766  
767 # Tool definitions are small enough to score directly on each search.
768 # Flatten argument names and descriptions recursively, ignoring schema mechanics.
769 738 ▶sub schema_search_text {
Subroutine schema_search_text: called CC=8 SCAR=21.2
770 738 my ($value, $text) = @_;
771 738 ▶ if (ref $value eq "HASH") {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $value eq 'HASH') { } 389 349 738
elsif (ref $value eq 'ARRAY') { } 0 349 349
772 389 ▶ push @$text, $value->{description} if defined $value->{description} && !ref $value->{description};
Branch: 1 branch
BranchTrueFalseTotal
if defined $value->{"description"} and not ref $value->{"description"} 83 306 389
Condition66%2/3
defined $value->{"description"} and not ref $value->{"description"}
!ll&&!rl&&r
306083
MC/DC50%1/2
defined $value->{"description"} and not ref $value->{"description"}
defined $value->{"description"} not ref $value->{"description"}
Truth table66%2/3
A and not(B)
A= defined $value->{"description"}B= not ref $value->{"description"}
ABresult
0X0
100
111
773 389 ▶ push @$text, keys %{$value->{properties}} if ref $value->{properties} eq "HASH";
Branch: 1 branch
BranchTrueFalseTotal
if ref $value->{"properties"} eq "HASH" 93 296 389
774 389 schema_search_text ($_, $text) for values %$value;
775 } elsif (ref $value eq "ARRAY") {
776 0 schema_search_text ($_, $text) for @$value;
777 }
778 }
779  
780 8 ▶sub search_tools {
Subroutine search_tools: called CC=22 SCAR=31.2
781 8 my ($tools, $query) = @_;
782  
783 216 ▶ my $words = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
784 216 my ($text) = @_;
785 216 $text =~ s/([a-z0-9])([A-Z])/$1 $2/g; # inputSchema -> input Schema
786 216 grep length, split /[^[:alnum:]]+/, lc $text;
787 8 };
788  
789 # Query terms are a set: repeating a word in the request has no extra weight.
790 8 my %query = map { $_ => 1 } $words->($query);
791 8 ▶ return ([], 0) unless %query;
Branch: 1 branch
BranchTrueFalseTotal
unless %query 0 8 8
792  
793 # Build per-tool term frequencies (tf), document lengths and the number
794 # of tools containing each query term (df). No persistent index needed.
795 8 my (@documents, %df, $total_length);
796 8 for my $tool (@$tools) {
797 # The broker's own tools are already exposed. Search qualified
798 # downstream names (PREFIX.TOOL) only.
799 248 ▶ next unless $tool->{name} =~ /\./;
Branch: 1 branch
BranchTrueFalseTotal
unless $tool->{"name"} =~ /\./u 40 208 248
800 208 my @text = ($tool->{name}, $tool->{description});
801 208 ▶ schema_search_text ($tool->{inputSchema}, \@text) if $tool->{inputSchema};
Branch: 1 branch
BranchTrueFalseTotal
if $tool->{"inputSchema"} 208 0 208
802 208 ▶ my @words = $words->(join " ", grep defined && !ref, @text);
Condition33%1/3
defined $_ && !ref($_)
!ll&&!rl&&r
00587
MC/DC0%0/2
defined $_ && !ref($_)
defined $_ !ref($_)
Truth table33%1/3
A && not(B)
A= defined $_B= !ref($_)
ABresult
0X0
100
111
803 208 my %tf;
804 208 ++$tf{$_} for @words;
805 208 ++$df{$_} for grep exists $tf{$_}, keys %query;
806 208 $total_length += @words;
807 208 push @documents, [$tool, \%tf, scalar @words];
808 }
809  
810 # Okapi BM25, with positive IDF, k1=1.2 for frequency saturation and
811 # b=0.75 for length normalization. Thus 2.2 = k1+1 and .25 = 1-b.
812 # Sum each matching query term's contribution; nonmatches score zero.
813 8 my $n = @documents;
814 8 ▶ my $avg = $total_length / ($n || 1);
Condition50%1/2
$n || 1
l!l
80
MC/DC0%0/1
$n || 1
$n
Truth table50%1/2
A
A= $n
Aresult
11
00
815 8 my @scored;
816 8 for my $doc (@documents) {
817 208 my ($tool, $tf, $length) = @$doc;
818 208 my $score = 0;
819 208 for my $term (keys %query) {
820 232 ▶ my $f = $tf->{$term} || next;
Condition100%2/2
$tf->{$term} || (next)
l!l
66166
MC/DC100%1/1
$tf->{$term} || (next)
$tf->{$term}
Truth table100%2/2
A
A= $tf->{$term}
Aresult
11
00
821 66 my $idf = log (1 + ($n - $df{$term} + .5) / ($df{$term} + .5));
822 66 ▶ $score += $idf * $f * 2.2 / ($f + 1.2 * (.25 + .75 * $length / ($avg || 1)));
Condition50%1/2
$avg || 1
l!l
660
MC/DC0%0/1
$avg || 1
$avg
Truth table50%1/2
A
A= $avg
Aresult
11
00
823 }
824 208 ▶ push @scored, [$score, $tool] if $score > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $score > 0 63 145 208
825 }
826 8 ▶ @scored = sort { $b->[0] <=> $a->[0] || $a->[1]{name} cmp $b->[1]{name} } @scored;
Condition66%2/3
$main::b->[0] <=> $main::a->[0] || $main::a->[1]{'name'} cmp $main::b->[1]{'name'}
l!l&&r!l&&!r
9640
MC/DC0%0/2
$main::b->[0] <=> $main::a->[0] || $main::a->[1]{'name'} cmp $main::b->[1]{'name'}
$main::b->[0] <=> $main::a->[0] $main::a->[1]{'name'} cmp $main::b->[1]{'name'}
Truth table66%2/3
A || B
A= $main::b->[0] <=> $main::a->[0]B= $main::a->[1]{'name'} cmp $main::b->[1]{'name'}
ABresult
1X1
011
000
827 8 ▶ my @ranked = map $_->[1], @scored[0 .. ($#scored < 24 ? $#scored : 24)];
Branch: 1 branch
BranchTrueFalseTotal
$#scored < 24 ? : 6 2 8
828 8 my (@found, @sizes);
829 # Reserve room for all ranked summaries first, then upgrade to complete
830 # definitions in relevance order while the 64 KiB budget permits.
831 8 for my $tool (@ranked) {
832 58 my ($broker, $name) = $tool->{name} =~ /\A([^.]+)\.(.+)\z/;
833 58 ▶ my $description = $tool->{description} // "";
Condition50%1/2
$tool->{"description"} // ""
l!l
580
MC/DC0%0/1
$tool->{"description"} // ""
$tool->{"description"}
Truth table50%1/2
A
A= $tool->{"description"}
Aresult
11
00
834 58 ▶ $description = substr ($description, 0, 1024) . "..."
Branch: 1 branch
BranchTrueFalseTotal
if length $description > 1024 0 58 58
835 if length $description > 1024;
836 my $summary = {
837 name => $tool->{name},
838 58 description => $description,
839 schema_omitted => JSON::XS::true,
840 retrieve => { tool => "list-tools", arguments => { broker => $broker, name => $name } },
841 };
842 58 push @found, $summary;
843 58 push @sizes, length JSON::XS::encode_json ($summary);
844 }
845 8 my $bytes = length JSON::XS::encode_json ({ tools => \@found, total_matches => scalar @scored });
846 8 for my $i (0 .. $#ranked) {
847 58 my $size = length JSON::XS::encode_json ($ranked[$i]);
848 58 ▶ next if $size > 8192 || $bytes + $size - $sizes[$i] > 65536;
Branch: 1 branch
BranchTrueFalseTotal
if $size > 8192 or $bytes + $size - $sizes[$i] > 65536 10 48 58
Condition100%3/3
$size > 8192 or $bytes + $size - $sizes[$i] > 65536
l!l&&r!l&&!r
1948
MC/DC100%2/2
$size > 8192 or $bytes + $size - $sizes[$i] > 65536
$size > 8192 $bytes + $size - $sizes[$i] > 65536
Truth table100%3/3
A or B
A= $size > 8192B= $bytes + $size - $sizes[$i] > 65536
ABresult
1X1
011
000
849 48 $bytes += $size - $sizes[$i];
850 48 $found[$i] = $ranked[$i];
851 }
852 8 (\@found, scalar @scored)
853 }
854  
855 100 ▶sub call_tool {
Subroutine call_tool: called CC=21 SCAR=31.3
856 100 my ($req, $name, $args) = @_;
857  
858 100 ▶ return $req->error ("Invalid tool call") unless defined $name && !ref $name && ref $args eq "HASH";
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and not ref $name and ref $args eq "HASH" 0 100 100
Condition33%2/6
defined $name and not ref $name and ref $args eq "HASH"
!ll&&!rl&&r
00100
defined $name and not ref $name
!ll&&!rl&&r
00100
MC/DC0%0/3
defined $name and not ref $name and ref $args eq "HASH"
defined $name not ref $name ref $args eq "HASH"
Truth table25%1/4
A and not(B) and C
A= defined $nameB= not ref $nameC= ref $args eq "HASH"
ABCresult
0XX0
10X0
1100
1111
859 100 ▶ if (my ($local) = grep exists $_->{tool}{$name}, @{$req->{server}{toolsets}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my($local) = grep(exists $_->{"tool"}{$name}, @{$$req{"server"}{"toolsets"};})) 44 56 100
860 44 local $req->{tool} = $name;
861 44 local $req->{args} = $args;
862 44 return $local->call ($req)
863 }
864  
865 56 my ($prefix, $tool) = $name =~ /\A([^.]+)\.(.+)\z/;
866 56 ▶ $prefix = broker_alias $prefix if defined $prefix;
Branch: 1 branch
BranchTrueFalseTotal
if defined $prefix 56 0 56
867 56 my $client = $broker{$prefix};
868 56 ▶ return $req->error ("Unknown tool '$name'") unless $client;
Branch: 1 branch
BranchTrueFalseTotal
unless $client 1 55 56
869  
870 55 AE::log trace => "multibroker $name";
871 55 my %params = (%{$req->{params}}, name => $tool, arguments => $args);
872 55 ▶ $params{_meta} = { %{$params{_meta} || {}} };
Condition100%2/2
$params{'_meta'} || {}
l!l
532
MC/DC100%1/1
$params{'_meta'} || {}
$params{'_meta'}
Truth table100%2/2
A
A= $params{'_meta'}
Aresult
11
00
873 55 $params{_meta}{"anyevent-mcp/user"} = $req->{user};
874 55 my $caps = $params{_meta}{"io.modelcontextprotocol/clientCapabilities"};
875 55 ▶ $caps = ref $caps eq "HASH" ? { %$caps } : {};
Branch: 1 branch
BranchTrueFalseTotal
ref $caps eq 'HASH' ? : 53 2 55
876 my $native_forms = $req->{protocol_version} ge "2026"
877 && ref $caps->{elicitation} eq "HASH"
878 55 ▶ && (!keys %{$caps->{elicitation}} || ref $caps->{elicitation}{form} eq "HASH");
Condition77%7/9
$req->{'protocol_version'} ge '2026' && ref $caps->{'elicitation'} eq 'HASH' && (!keys(%{$$caps{'elicitation'};}) || ref $caps->{'elicitation'}{'form'} eq 'HASH')
!ll&&!rl&&r
39016
$req->{"protocol_version"} ge 2026 and ref $caps->{"elicitation"} eq "HASH"
!ll&&!rl&&r
23716
not keys %{$$caps{"elicitation"};} or ref $caps->{"elicitation"}{"form"} eq "HASH"
l!l&&r!l&&!r
6100
MC/DC50%2/4
$req->{'protocol_version'} ge '2026' && ref $caps->{'elicitation'} eq 'HASH' && (!keys(%{$$caps{'elicitation'};}) || ref $caps->{'elicitation'}{'form'} eq 'HASH')
$req->{"protocol_version"} ge 2026 ref $caps->{"elicitation"} eq "HASH" not keys %{$$caps{"elicitation"};} ref $caps->{"elicitation"}{"form"} eq "HASH"
Truth table80%4/5
A and B && not(C) or D
A= $req->{"protocol_version"} ge 2026B= ref $caps->{"elicitation"} eq "HASH"C= not keys %{$$caps{"elicitation"};}D= ref $caps->{"elicitation"}{"form"} eq "HASH"
ABCDresult
0XXX0
10XX0
11000
111X1
11011
879 55 ▶ my $local_forms = $ask_mode =~ /\A(?:helper|tty|yad|none)\z/ || $ask_mode eq "auto" && !$native_forms;
Condition83%5/6
$ask_mode =~ /\A(?:helper|tty|yad|none)\z/u || $ask_mode eq 'auto' && !$native_forms
l!l&&r!l&&!r
15238
$ask_mode eq "auto" and not $native_forms
!ll&&!rl&&r
3802
MC/DC66%2/3
$ask_mode =~ /\A(?:helper|tty|yad|none)\z/u || $ask_mode eq 'auto' && !$native_forms
$ask_mode =~ /\A(?:helper|tty|yad|none)\z/u $ask_mode eq "auto" not $native_forms
Truth table75%3/4
A || B and not(C)
A= $ask_mode =~ /\A(?:helper|tty|yad|none)\z/uB= $ask_mode eq "auto"C= not $native_forms
ABCresult
1XX1
0111
00X0
0100
880 55 ▶ if ($local_forms) {
Branch: 2 branches
BranchTrueFalseTotal
if ($local_forms) { } 17 38 55
elsif ($req->{'protocol_version'} lt '2026') { } 2 36 38
881 17 $caps->{elicitation} = { form => {} };
882 } elsif ($req->{protocol_version} lt "2026") {
883 2 delete $caps->{elicitation};
884 }
885 $caps->{extensions} = {
886 55 ▶ %{ref $caps->{extensions} eq "HASH" ? $caps->{extensions} : {}},
Branch: 1 branch
BranchTrueFalseTotal
ref $caps->{'extensions'} eq 'HASH' ? : 0 55 55
887 "anyevent-mcp/multibroker" => { version => 1 },
888 };
889 55 $params{_meta}{"io.modelcontextprotocol/clientCapabilities"} = $caps;
890 55 my $token = $params{_meta}{progressToken};
891 55 ▶ $progress{$prefix}{$token} = $req if defined $token && !ref $token;
Branch: 1 branch
BranchTrueFalseTotal
if defined $token and not ref $token 4 51 55
Condition66%2/3
defined $token and not ref $token
!ll&&!rl&&r
5104
MC/DC50%1/2
defined $token and not ref $token
defined $token not ref $token
Truth table66%2/3
A and not(B)
A= defined $tokenB= not ref $token
ABresult
0X0
100
111
892 55 my $id;
893 55 my $old_cancel = $req->{on_cancel};
894 1 ▶ $req->{on_cancel} = sub {
Subroutine __ANON__: called CC=5 SCAR=19.2
895 1 ▶ delete $progress{$prefix}{$token} if defined $token && !ref $token;
Branch: 1 branch
BranchTrueFalseTotal
if defined $token and not ref $token 0 1 1
Condition33%1/3
defined $token and not ref $token
!ll&&!rl&&r
100
MC/DC0%0/2
defined $token and not ref $token
defined $token not ref $token
Truth table33%1/3
A and not(B)
A= defined $tokenB= not ref $token
ABresult
0X0
100
111
896 1 ▶ $client->cancel ($id, $_[1]) if defined $id;
Branch: 1 branch
BranchTrueFalseTotal
if defined $id 1 0 1
897 1 ▶ $old_cancel->(@_) if $old_cancel;
Branch: 1 branch
BranchTrueFalseTotal
if $old_cancel 0 1 1
898 55 };
899 55 ▶ my $done = sub {
Subroutine __ANON__: called CC=5 SCAR=16.2
900 55 my ($success, $result) = @_;
901 55 ▶ delete $progress{$prefix}{$token} if defined $token && !ref $token;
Branch: 1 branch
BranchTrueFalseTotal
if defined $token and not ref $token 4 51 55
Condition66%2/3
defined $token and not ref $token
!ll&&!rl&&r
5104
MC/DC50%1/2
defined $token and not ref $token
defined $token not ref $token
Truth table66%2/3
A and not(B)
A= defined $tokenB= not ref $token
ABresult
0X0
100
111
902  
903 55 ▶ return if $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"finished"} 1 54 55
904 54 ▶ return $req->error ($result->{message}) unless $success;
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 54 54
905 54 $req->reply ($result);
906 55 };
907 55 ▶ if ($local_forms || $req->{protocol_version} lt "2026") {
Branch: 1 branch
BranchTrueFalseTotal
if ($local_forms or $req->{'protocol_version'} lt '2026') { } 19 36 55
Condition100%3/3
$local_forms or $req->{"protocol_version"} lt 2026
l!l&&r!l&&!r
17236
MC/DC100%2/2
$local_forms or $req->{"protocol_version"} lt 2026
$local_forms $req->{"protocol_version"} lt 2026
Truth table100%3/3
A or B
A= $local_formsB= $req->{"protocol_version"} lt 2026
ABresult
1X1
011
000
908 19 $id = $client->call ($tool, $args, $done, %params);
909 } else {
910 36 $id = $client->rpc ("tools/call", \%params, $done);
911 }
912 }
913  
914 $toolset->tool (discover_brokers =>
915 "Get instructions from all brokers by name: string; null if reachable but none; {error: MESSAGE} if unreachable.",
916 { type => "object", properties => {} },
917 8 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.1
918 8 my ($req) = @_;
919  
920 8 my @prefix = sort keys %broker;
921 8 my %instructions;
922 8 my %pending = map { $_ => 1 } @prefix;
923 8 my $remaining = @prefix;
924 8 my $finished;
925 my $timer;
926 8 ▶ my $finish = sub {
Subroutine __ANON__: called CC=4 SCAR=14.5
927 8 ▶ return if $finished++;
Branch: 1 branch
BranchTrueFalseTotal
if $finished++ 0 8 8
928 8 undef $timer;
929 8 $instructions{$_} = { error => "Discovery timed out" } for keys %pending;
930 8 ▶ $req->result (\%instructions) unless $req->{finished};
Branch: 1 branch
BranchTrueFalseTotal
unless $req->{"finished"} 8 0 8
931 8 };
932 8 ▶ return $finish->() unless $remaining;
Branch: 1 branch
BranchTrueFalseTotal
unless $remaining 0 8 8
933  
934 0 ▶ $timer = AnyEvent->timer (after => 15, cb => sub { $finish->() });
Subroutine __ANON__: not called CC=1 SCAR=1.2
935 8 for my $prefix (@prefix) {
936 18 my $client = $broker{$prefix};
937 18 ▶ $client->connect (sub {
Subroutine __ANON__: called CC=6 SCAR=18.0
938 18 ▶ return if $finished;
Branch: 1 branch
BranchTrueFalseTotal
if $finished 0 18 18
939 18 my ($success, $result) = @_;
940 18 ▶ if ($success) {
Branch: 1 branch
BranchTrueFalseTotal
if ($success) { } 17 1 18
941 $instructions{$prefix} = $hidden{$prefix}
942 ? "Hidden tools; use list-tools broker=$prefix.\n" . ($client->{instructions} // "")
943 17 ▶ : $client->{instructions};
Branch: 1 branch
BranchTrueFalseTotal
$hidden{$prefix} ? : 2 15 17
Condition50%1/2
$client->{"instructions"} // ""
l!l
20
MC/DC0%0/1
$client->{"instructions"} // ""
$client->{"instructions"}
Truth table50%1/2
A
A= $client->{"instructions"}
Aresult
11
00
944 } else {
945 1 AE::log warn => "$prefix: $result->{message}";
946 1 $instructions{$prefix} = { error => $result->{message} };
947 }
948 18 delete $pending{$prefix};
949 18 ▶ $finish->() unless --$remaining;
Branch: 1 branch
BranchTrueFalseTotal
unless --$remaining 8 10 18
950 18 });
951 }
952 },
953 22 );
954 $toolset->tool (search_tools =>
955 "Search all brokers by BM25 relevance; returns up to 25 ranked tools within 64 KiB. Large schemas are summarized; fetch one using list-tools broker=NAME name=TOOL, then invoke with call-tool.",
956 {
957 type => "object",
958 required => ["query"],
959 properties => {
960 query => { type => "string", description => "Keywords describing the desired operation" },
961 },
962 additionalProperties => JSON::XS::false,
963 },
964 9 ▶ sub {
Subroutine __ANON__: called CC=6 SCAR=18.7
965 9 my ($req, $args) = @_;
966 9 for (keys %$args) {
967 9 ▶ $_ eq "query" or return $req->error ("Unknown search-tools argument '$_'");
Branch: 1 branch
BranchTrueFalseTotal
$_ eq "query" or return $req->error("Unknown search-tools argument '${_}'") 9 0 9
968 }
969 9 ▶ defined $args->{query} && !ref $args->{query} && $args->{query} =~ /[[:alnum:]]/
Branch: 1 branch
BranchTrueFalseTotal
defined $args->{"query"} and not ref $args->{"query"} and $args->{"query"} =~ /[[:alnum:]]/u or return $req->error("search-tools requires a nonempty keyword query") 8 1 9
Condition50%3/6
defined $args->{"query"} and not ref $args->{"query"} and $args->{"query"} =~ /[[:alnum:]]/u
!ll&&!rl&&r
018
defined $args->{"query"} and not ref $args->{"query"}
!ll&&!rl&&r
009
MC/DC33%1/3
defined $args->{"query"} and not ref $args->{"query"} and $args->{"query"} =~ /[[:alnum:]]/u
defined $args->{"query"} not ref $args->{"query"} $args->{"query"} =~ /[[:alnum:]]/u
Truth table50%2/4
A and not(B) and C
A= defined $args->{"query"}B= not ref $args->{"query"}C= $args->{"query"} =~ /[[:alnum:]]/u
ABCresult
0XX0
10X0
1100
1111
970 or return $req->error ("search-tools requires a nonempty keyword query");
971  
972 8 ▶ all_tools $req, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
973 8 my ($tools, $matches) = search_tools $_[0], $args->{query};
974 8 $req->result ({ tools => $tools, total_matches => $matches });
975 8 }, undef, 1;
976 },
977 22 );
978 $toolset->tool (list_tools =>
979 "List tools; broker selects one downstream, including hidden ones; name selects one tool in that broker. Omit both for local + visible brokers.",
980 {
981 type => "object",
982 properties => {
983 broker => { type => "string", description => "Downstream broker, including hidden; underscores may replace hyphens. Omit for visible brokers + local tools." },
984 name => { type => "string", description => "One downstream tool's unqualified name; requires broker. Omit to list all tools." },
985 },
986 additionalProperties => JSON::XS::false,
987 },
988 17 ▶ sub {
Subroutine __ANON__: called CC=12 SCAR=25.0
989 17 my ($req, $args) = @_;
990  
991 17 for (keys %$args) {
992 13 ▶ $_ eq "broker" || $_ eq "name" or return $req->error ("Unknown list-tools argument '$_'");
Branch: 1 branch
BranchTrueFalseTotal
$_ eq "broker" or $_ eq "name" or return $req->error("Unknown list-tools argument '${_}'") 12 1 13
Condition100%3/3
$_ eq "broker" or $_ eq "name"
l!l&&r!l&&!r
931
MC/DC100%2/2
$_ eq "broker" or $_ eq "name"
$_ eq "broker" $_ eq "name"
Truth table100%3/3
A or B
A= $_ eq "broker"B= $_ eq "name"
ABresult
1X1
011
000
993 }
994 16 my $name = $args->{broker};
995 16 ▶ $name = broker_alias $name if defined $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $name 8 8 16
996 16 ▶ return $req->error ("Unknown broker '$name'") if defined $name && !exists $broker{$name};
Branch: 1 branch
BranchTrueFalseTotal
if defined $name and not exists $broker{$name} 1 15 16
Condition100%3/3
defined $name and not exists $broker{$name}
!ll&&!rl&&r
871
MC/DC100%2/2
defined $name and not exists $broker{$name}
defined $name not exists $broker{$name}
Truth table100%3/3
A and not(B)
A= defined $nameB= not exists $broker{$name}
ABresult
0X0
100
111
997  
998 15 my $tool = $args->{name};
999 15 ▶ return $req->error ("name requires broker") if defined $tool && !defined $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tool and not defined $name 1 14 15
Condition100%3/3
defined $tool and not defined $name
!ll&&!rl&&r
1221
MC/DC100%2/2
defined $tool and not defined $name
defined $tool not defined $name
Truth table100%3/3
A and not(B)
A= defined $toolB= not defined $name
ABresult
0X0
100
111
1000 14 ▶ return $req->error ("Invalid tool name") if defined $tool && (ref $tool || !length $tool);
Branch: 1 branch
BranchTrueFalseTotal
if defined $tool and ref $tool || !length($tool) 0 14 14
Condition50%3/6
defined $tool and ref $tool || !length($tool)
!ll&&!rl&&r
1220
ref $tool or not length $tool
l!l&&r!l&&!r
002
MC/DC0%0/3
defined $tool and ref $tool || !length($tool)
defined $tool ref $tool not length $tool
Truth table50%2/4
A and B or not(C)
A= defined $toolB= ref $toolC= not length $tool
ABCresult
0XX0
1000
11X1
1011
1001  
1002 14 ▶ all_tools $req, sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1003 14 my $tools = $_[0];
1004 14 ▶ $tools = [grep $_->{name} eq "$name.$tool", @$tools] if defined $tool;
Branch: 1 branch
BranchTrueFalseTotal
if defined $tool 2 12 14
1005 14 $req->result ({ tools => $tools });
1006 14 }, $name;
1007 },
1008 22 );
1009 $toolset->tool (call_tool =>
1010 "Call tool by prefixed name from list-tools. Use when not directly exposed; call loaded tools directly.",
1011 {
1012 type => "object",
1013 required => ["name"],
1014 properties => {
1015 name => { type => "string" },
1016 arguments => { type => "object" },
1017 },
1018 },
1019 8 ▶ sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1020 8 my ($req, $args) = @_;
1021  
1022 8 ▶ return $req->error ("call-tool cannot call itself") if $args->{name} eq "call-tool";
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"name"} eq "call-tool" 1 7 8
1023 7 ▶ call_tool $req, $args->{name}, $args->{arguments} || {};
Condition100%2/2
$args->{'arguments'} || {}
l!l
34
MC/DC100%1/1
$args->{'arguments'} || {}
$args->{'arguments'}
Truth table100%2/2
A
A= $args->{'arguments'}
Aresult
11
00
1024 },
1025 22 );
1026  
1027 125 ▶sub log_request {
Subroutine log_request: called CC=3 SCAR=11.0
1028 125 my ($server, $req) = @_;
1029  
1030 # keep proxied calls at trace to avoid duplicating downstream activity logs.
1031 125 ▶ return if $req->{method} eq "tools/call" && $req->{tool} =~ /\A[^.]+\./;
Branch: 1 branch
BranchTrueFalseTotal
if $req->{"method"} eq "tools/call" and $req->{"tool"} =~ /\A[^.]+\./u 49 76 125
Condition100%3/3
$req->{"method"} eq "tools/call" and $req->{"tool"} =~ /\A[^.]+\./u
!ll&&!rl&&r
324449
MC/DC100%2/2
$req->{"method"} eq "tools/call" and $req->{"tool"} =~ /\A[^.]+\./u
$req->{"method"} eq "tools/call" $req->{"tool"} =~ /\A[^.]+\./u
Truth table100%3/3
A and B
A= $req->{"method"} eq "tools/call"B= $req->{"tool"} =~ /\A[^.]+\./u
ABresult
0X0
100
111
1032  
1033 76 mcp_log_request $server, $req;
1034 }
1035  
1036 22 mcp_permissions undef; # downstream permission elicitation is handled by the broker
1037  
1038 mcp_config
1039 server_name => "mcp-multibroker",
1040 server_version => $AnyEvent::MCP::VERSION,
1041 on_request => \&log_request,
1042 0 ▶ on_error => sub { AE::log error => "MCP dispatch $_[1]{method}: $_[2]" },
Subroutine __ANON__: not called CC=1 SCAR=6.9
1043 22 short_instructions => "MCP tool router. search-tools ranks visible and hidden tools; large schemas are summarized. list-tools broker=NAME name=TOOL retrieves one complete definition. call-tool invokes a match.",
1044 instructions => <<'EOF';
1045 Proxy MCP servers as PREFIX.TOOL. search-tools ranks tools across all brokers, including hidden ones, returning up to 25 definitions within 64 KiB; oversized schemas are summarized with retrieval instructions. list-tools broker=NAME name=TOOL retrieves one complete definition; omit name to retrieve all tools for a broker. call-tool invokes a returned prefixed tool name. discover-brokers lists servers. Tools may change.
1046 EOF
1047  
1048 # start selected stdio children now, before the upstream event loop starts.
1049 # their asynchronous initialization completes once that loop is running.
1050 # optional children can still be reconnected by a later MCP request.
1051 22 mcp_tool_help ($server_options->{tool_help}, $toolset);
1052 21 delete $server_options->{tool_help};
1053 21 for my $prefix (sort keys %eager) {
1054 0 ▶ $broker{$prefix}->connect (sub {
Subroutine __ANON__: not called CC=4 SCAR=30.0
1055 0 my ($success, $error) = @_;
1056  
1057 0 ▶ if (!$success && $required{$prefix}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $success and $required{$prefix}) 0 0 0
Condition0%0/3
not $success and $required{$prefix}
!ll&&!rl&&r
000
MC/DC0%0/2
not $success and $required{$prefix}
not $success $required{$prefix}
Truth table0%0/3
not(A) and B
A= not $successB= $required{$prefix}
ABresult
0X0
100
111
1058 0 required_failure $prefix, "initialization failed: $error->{message}";
1059 }
1060 0 ▶ AE::log warn => "$prefix: eager startup failed: $error->{message}"
Branch: 1 branch
BranchTrueFalseTotal
unless $success 0 0 0
1061 unless $success;
1062 0 });
1063 }
1064  
1065 mcp_start
1066 %$server_options,
1067 ($listen ? (listen => 1) : ()),
1068 toolsets => [$toolset],
1069 on_extension => \&accept_extension,
1070 8 ▶ on_tools_list => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1071 8 my ($server, $req) = @_;
1072  
1073 8 AE::log debug => "multibroker list-tools";
1074 8 ▶ all_tools $req, sub { $req->reply ({ tools => $_[0] }) };
Subroutine __ANON__: called CC=1 SCAR=0.0
1075 },
1076 93 ▶ on_tools_call => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
1077 93 my ($server, $req, $args) = @_;
1078  
1079 93 call_tool $req, $req->{tool}, $args;
1080 21 ▶ };
Branch: 1 branch
BranchTrueFalseTotal
$listen ? : 0 21 21
1081  
1082 21 $shutting_down = 1;
1083 21 $_->close for values %broker;
1084  
« blib/lib/AnyEvent/MCP/Server/Connect.pm ↑ Summary lib/AnyEvent/MCP/IMAP/OAuth2.pm »