view release on metacpan or search on metacpan
- return 404 to GET / even when / is the MCP POST endpoint; drop
the unhelpful connection object address from HTTP rejection logs
while retaining the remote address and sanitized URI.
- reuse the latest saved per-dimension scope as the next permission
rule editor's default where offered, otherwise keep the original
conservative choice; native, YAD and terminal forms agree.
- handle the common token-only HTTP endpoint in warning logs:
redact known tokens without misclassifying unrelated paths.
- include bounded, JSON-escaped request paths in rejected HTTP request
warnings; omit queries and redact configured and attempted URL tokens.
- show captured helper status, stderr and stdout when the permission
UI test fails, and report remote file-patch results and file content
when the mock remote filesystem test fails (CPAN Testers diagnostics).
0.82 Fri 06 Nov 2026 15:53:46 CET
- add a first-permission-dialog walkthrough to Intro.pod, explaining
one-time versus persistent grants, rule scopes and exec stdin risks;
correct its description of logical workdir IDs.
- add common repeatable -s/--set KEY=VALUE process-local overrides
for trusted instance configuration, after program/instance defaults.
- key remote mcp-fs host permissions by --host alone, independent of
default, or all hosts), retaining old unscoped saved rules.
Workdir scopes remain plain paths, independent of host.
- omit single-choice permission scope selectors from native, YAD and
terminal rule dialogs, automatically retaining the sole match in
saved rules without broadening their applicability.
- log rejected HTTP requests (status 400 and above) with method,
status and peer information, without leaking URL tokens; demote
ordinary connection/TLS errors to trace.
- do not warn on routine GET / requests; keep the normal 404
response without exposing a server-identification page.
- preserve mcp-vim subprocess stderr when its JSONL initialization
fails, instead of hiding the failure behind EOF and SIGPIPE.
- bootstrap remote mcp-fs over a short Perl command, streaming the
launcher source over stdin. Avoid rsh command length limits and
preserve worker input across exec by using exact sysread.
- format mcp-fs sandbox grants, tools, trusted configuration keys
and permission action classes as individually searchable POD items.
- give the mock remote filesystem test its running Perl interpreter
explicitly, rather than assuming it is in a fixed Unix PATH.
- avoid locale-dependent TCP error strings in reverse-connection tests,
and skip mcp-imap provider CLI tests when optional fork modules
yet.
Choose stdio or HTTP
Use stdio when your MCP client runs on the same machine and can launch a
server process. Configure the client to start the following command:
mcp-fs --stdio --name code /home/alice/src/project
The client starts this process and uses its stdin/stdout for MCP. You do
not start a second copy in a terminal, and there is no listener URL or
HTTP token to configure. Diagnostics go to stderr.
Clients that take a command and an argument array need these values:
command: mcp-fs
arguments: --stdio, --name, code, /home/alice/src/project
These describe separate arguments, not one shell command string. Use an
absolute executable path if the client cannot find "mcp-fs". See "CLIENT
EXAMPLES" for examples of particular clients.
the tunnel ID. Creation and visibility depend on the Platform and
ChatGPT workspace permissions. The tunnel client's CLI and supported
configuration forms can vary between releases; the examples above use
the direct runtime CLI rather than its optional profile setup. See
Secure MCP Tunnel
<https://developers.openai.com/api/docs/guides/secure-mcp-tunnels> for
obtaining a tunnel, runtime, credentials and connecting it to ChatGPT.
TROUBLESHOOTING
The server does not start
Read stderr or the client's server log. Missing Perl modules, a missing
workdir, unsuitable utilities or an unavailable bubblewrap executable
can fail startup. Confirm that the client launches the same executable
and arguments you intended, with the expected "PATH" and Perl
installation.
For a local sandbox check, run from the project directory:
mcp-fs --exec-cmd workdir-read -- ls
This runs "ls" with the named grants and trusted baseline mounts,
requested IMAP scope and saved "user" name. Copy the complete redirected
address-bar URL after authorization, even when the browser displays an
unreachable loopback page.
If the server warns that it cannot save the master secret, another
process may derive a different token. Check write access to the global
configuration. Do not replace an existing secret simply to add a
setting.
Connected, but there are no tools
Inspect the server's stderr for omitted utilities. mcp-fs's "workdirs"
tool reports configuration even when a utility-dependent tool is absent.
For a multibroker, call "discover-brokers" to see individual connection
errors, then "list-tools" to refresh definitions.
A third-party child might require initialization or features this client
implementation does not support. See AnyEvent::MCP::Client and its
transport documentation for limitations.
There is no approval dialog
First check whether the tool was denied by a saved rule or is waiting
for the client's own approval. An allowed operation needs no server
prompt.
The default helper runs on the server machine. A background service may
have neither a usable display nor "/dev/tty", even though your
interactive shell has both. Supply the appropriate display environment,
a usable helper, or "--ask auto" with a modern client supporting form
elicitation. "--ask mcp" reports an error if that support is absent.
Setting an asking mode cannot make an unsupported client display a form.
Check stderr and the tool error instead of assuming a missing dialog is
an approval.
It asks again after I chose allow
Allow-once covers one tool invocation, including its permission retries.
The next invocation asks again. Use allow-always to save a rule.
Inspect the saved rule's action, workdir and grants. Listing names and
reading contents are different actions. A rule for one exact workdir
spelling will not match a differently spelled startup argument. A
request for extra authority, such as networking, does not match a
bin/anyevent-mcp-askpermission view on Meta::CPAN
edits the optional denial reason. Closing the dialog, cancelling or an unavailable
terminal denies once. Rule management remains separate:
C<anyevent-mcp manage-rules NAME> or C<anyevent-mcp edit-rules NAME>.
=head1 HELPER PROTOCOL
The helper reads one permission request on stdin and writes one JSON
decision on stdout. Servers invoke it through
L<AnyEvent::MCP::Permissions::Ask>, which describes the helper interface
and how to select a replacement helper. YAD's stderr is suppressed;
startup failure is detected from its exit status.
=head1 OPTIONS
=over
=item --manage-rules FILE
Open YAD rule list for FILE in evaluation order. Delete or reorder selected
rules. File lock protects updates; changes fail if list changed elsewhere.
bin/anyevent-mcp-form-elicitation view on Meta::CPAN
Reads one UTF-8 JSON object containing MCP form elicitation parameters:
C<mode> (optional, C<form>), C<message> and C<requestedSchema>. It displays
the form using YAD, or uses C</dev/tty> if YAD cannot start. It writes one
ordinary MCP response to stdout:
{"action":"accept","content":{"answer":"Some text"}}
{"action":"decline"}
{"action":"cancel"}
Exit status zero means a valid response, including decline or cancel.
Nonzero means invalid input or a helper failure; diagnostics go to stderr.
Closing a working dialog cancels the question and does not open another
prompt. Without YAD or a terminal the helper fails rather than inventing
an answer.
Forms contain at most 32 fields. Supported field types are strings,
single-select string enums (C<enum> or titled C<oneOf> values), booleans,
numbers and integers. Titles, descriptions, defaults, required fields,
string length limits and numeric bounds are supported. Unsupported schema
features, including string formats, nested objects, multi-select arrays and
URL elicitation, produce an error.
starting a listener, run C<mcp-fs --tool-help /home/alice/src/project>.
Once connected, ask the assistant:
Show the configured workdirs and list my project's top-level files.
Read its README if present. Do not change files or run commands.
C<workdirs> shows the available paths without a worker. Listing requests
C<inspect> permission, and reading a file requests C<read>. Allow each once
to try them. Approval is specific to the requested action and sandbox grants.
If no dialog appears, inspect the tool error and server stderr: the helper
needs a YAD display or usable terminal. See L</PERMISSIONS>.
For a separate sandbox check without MCP, change to your project directory
and run:
mcp-fs --exec-cmd workdir-read -- ls
This uses the current directory as the workdir. It tests the sandbox,
not client connectivity or permission prompting.
Run an argv array, not a shell command string. To use shell syntax,
explicitly invoke a shell in that array.
=back
For C<exec>, C<stdin_encoding> selects C<utf-8> (default), C<latin1>
or C<base64>. The 4 MiB limit applies to the resulting stdin bytes.
The C<argv> elements are Unicode MCP strings encoded as UTF-8 for the
operating system; they cannot represent arbitrary non-UTF-8 argv bytes.
Stdout and stderr are decoded as UTF-8, with a raw capture limit of
1 MiB per stream; use the byte-range tools for binary file contents.
Its optional C<sandbox_grants> B<replaces> the default C<workdir-read>
grant rather than adding to it. Explicitly passing an empty array
therefore asks for no grants. Command exit codes are normal tool results,
not transport errors. On timeout, output collection stops and
C<truncated> is true; C<exit> and C<signal> still describe the reaped child.
Perl is required for normal server operation; missing optional GNU utilities
can cause their tools to be omitted. The command requested by C<exec>
is resolved when the worker runs; it need not be present when the server
Maximum returned UTF-8 bytes per stream, default 65536, maximum 1048576.
Clipping does not leave an incomplete UTF-8 character. Stderr has its own
budget, so a large stdout does not hide diagnostics.
=back
The command runs once and is drained to completion, subject to its timeout.
Raw capture is bounded to 1 MiB per stream, independently of the returned
output limits. C<capture_truncated> means bytes were omitted before filtering
or collection ended on timeout: matches in that omitted output are unknown.
C<stdout_truncated>, C<stderr_truncated> and the combined C<truncated> flag
also account for returned-output limits.
Changing presentation options does not change the command's permission
subject. C<exit>, C<signal> and C<timed_out> always describe the original
command, including a diff exit code indicating differences. A filter error
makes the tool result an error and adds C<filter_error>, while retaining that
command status. The command may already have completed; do not rerun it
merely because its output filter failed.
=head2 Version control
C<--auto-allow '*,read,workdir-read'> approves only those two actions
within read-only workdir authority. C<--auto-allow '*,*,workdir-write'>
approves any action requiring at most workdir-write authority,
including reads.
=back
Rules reside in C<$XDG_CONFIG_HOME/anyevent-mcp/rules/fs-NAME.ini>,
or the corresponding C<$HOME/.config> path. The rules filename shares the
service-instance name but has an C<fs> namespace. The default instance uses
C<rules/fs-default.ini>. The rules path is printed on stderr when starting
HTTP; normal startup leaves stdout untouched.
Local and remote instances with the same C<--name> intentionally share
the same rule profile. Permission requests include a host dimension: C<local>
for local execution, or C<remote HOST> using C<--host> independently of
C<--rsh>. New persistent rules default to this host, but may match all hosts.
The workdir matcher is simply the logical path, independent of host. Existing
rules lacking C<match.host> continue to apply across local and remote hosts;
only newly saved host-specific rules restrict this.
Use different instance names or C<match.host> to separate approvals for
different hosts. Unscoped rules apply across hosts sharing the profile.
($find, $grep, $patch, $perl, $sed) = @program{qw(find grep patch perl sed)};
warn "$_: not detected or wrong version\n"
for grep !$program{$_}, qw(find grep patch sed);
%vcs_program = map { ($_ => $program{$_}) } qw(git svn cvs hg);
AE::log warn => "bubblewrap unavailable, running without sandbox"
if $sandbox_mode eq "auto" && !$bwrap;
AnyEvent::detect; # proc_spawn creates child watchers after they might have died
# spawn stdin/stdout and stderr handles; proc_destroy closes them and terminates the child.
# the independent child watcher remains alive until the child is reaped.
sub proc_spawn {
my ($program, @argv) = @_;
my $remote_input;
if ($remote) {
$remote_input = $remote_launcher . fs_remote_frame ($bwrap ? AnyEvent::MCP::utf8enc $home : "", $program, @argv);
($program, @argv) = (@rsh, $host, $remote_command);
} elsif (@exec_prefix) {
($program, @argv) = (@exec_prefix, $program, @argv);
return $done->($proc->{status})
if defined $proc->{status};
$proc->{done} = $done;
}
# run a one-shot subprocess, leaving output interpretation to the caller.
# the stream callbacks consume rbuf and may return true to terminate the child.
sub proc_run {
my ($req, $command, $input, $timeout, $on_stdout, $on_stderr, $done) = @_;
my $io = proc_spawn @$command;
my $err = $io->{proc_err};
my $proc = $io->{proc};
my ($open, $timed_out, $failure, $timer) = (2);
my $complete = sub {
return if $open || !defined $proc->{status};
my $cb = $done or return;
undef $done;
my $stop = sub {
undef $timer;
delete $req->{on_cancel};
$open = 0;
proc_destroy $io;
$complete->();
};
$req->{on_cancel} = $stop;
for my $stream ([$io, $on_stdout], [$err, $on_stderr]) {
my ($handle, $consume) = @$stream;
my $closed;
my $finish = sub {
return if $closed++;
--$open;
$complete->();
};
my $read = sub {
my ($handle, $eof) = @_;
my $stop = eval { $consume->($handle, $eof) };
};
proc_on_exit $proc, $complete;
}
# run a subprocess and collect bounded output.
sub fs_run {
my ($req, $command, $input, $timeout, $byte_limit, $line_limit, $done) = @_;
my ($truncated, $line_truncated);
my ($stdout, $stderr) = ("", "");
my $capture = sub {
my ($target, $data, $lines) = @_;
return if $lines and $line_truncated;
return unless length $data;
my $remaining = $byte_limit - (length $stdout) - (length $stderr);
$truncated = 1 if length $data > $remaining;
$$target .= substr $data, 0, $remaining
if $remaining > 0;
if ($lines and $line_limit and ($$target =~ tr/\n//) > $line_limit) {
my $end = -1;
$end = index $$target, "\n", $end + 1
for 1 .. $line_limit;
substr $$target, $end + 1, length $$target, "";
$truncated = $line_truncated = 1;
proc_run $req, $command, $input, $timeout,
sub {
my ($handle) = @_;
my $stop = $capture->(\$stdout, $handle->{rbuf}, 1);
$handle->{rbuf} = "";
$stop
},
sub {
my ($handle) = @_;
$capture->(\$stderr, $handle->{rbuf}, 0);
$handle->{rbuf} = "";
0
},
sub {
my ($status, $timed_out, $failure) = @_;
return $done->(0, $failure) if $failure;
$done->(1, +{
stdout => $stdout,
stderr => $stderr,
exit => $status >> 8,
signal => $status & 127,
timed_out => $timed_out ? JSON::XS::true : JSON::XS::false,
truncated => $truncated || $timed_out ? JSON::XS::true : JSON::XS::false,
});
};
}
my $perl_slave = q{#perl
binmode STDIN;
$io->{rbuf_max} = (1 << 20) + 4096;
$io->{perl_key} = $key;
weaken (my $this = $io);
my $idle_destroy = sub {
my $io = $this or return;
undef $perl_worker if $perl_worker && $perl_worker == $io;
proc_destroy $io;
};
my $idle_stderr = sub { $_[0]{rbuf} = "" };
$io->{perl_idle} = sub {
my ($io) = @_;
my $err = $io->{proc_err};
$io ->on_eof ($idle_destroy);
$io ->on_error ($idle_destroy);
$err->on_eof ($idle_destroy);
$err->on_error ($idle_destroy);
$err->on_read ($idle_stderr );
$io ->on_read ($idle_destroy);
};
proc_on_exit $io->{proc}, sub {
my $io = $this or return;
$io->{perl_on_exit}->($_[0]) if $io->{perl_on_exit};
$idle_destroy->() if $perl_worker && $perl_worker == $io;
};
}
my $err = $io->{proc_err};
my $timer;
my $stderr = "";
my $finish = sub {
my ($failure, $payload) = @_;
my $cb = $done or return;
undef $done;
undef $timer;
delete $req->{on_cancel};
delete $io->{perl_on_exit};
if ($failure || defined $io->{proc}{status}) {
$perl_worker = $io;
$io->{perl_idle}->($io);
return if $req->{finished};
return $cb->(0, $error) if defined $error;
$cb->(1, \@response);
};
$io->{perl_on_exit} = sub {
my ($status) = @_;
$finish->("sandbox perl failed (exit " . ($status >> 8)
. ", signal " . ($status & 127) . "): $stderr\n");
};
$req->{on_cancel} = sub { $finish->("sandbox perl cancelled\n") };
$io->on_eof (sub { $finish->("short perl response\n") });
$io->on_error (sub { $finish->("sandbox perl stdout: $_[2]\n") if $_[1] });
$err->on_read (sub {
$stderr .= substr $_[0]{rbuf}, 0, 65536 - length $stderr
if length $stderr < 65536;
$_[0]{rbuf} = "";
});
$err->on_eof (sub { $finish->("sandbox perl stderr closed\n") });
$err->on_error (sub { $finish->("sandbox perl stderr: $_[2]\n") if $_[1] });
$timer = AE::timer $timeout, 0, sub { $finish->("sandbox perl timed out\n") };
my $ok = eval {
$io->push_read (packstring => "N", sub {
my ($io, $payload) = @_;
return $finish->("unexpected sandbox perl output\n")
if length $io->{rbuf};
$finish->(undef, $payload);
});
};
sub fs_result;
# command output options affect presentation, never argv or permission scope.
my %output_schema = (
grep => { type => "string", description => "Optional PCRE stdout line filter after capture; no shell." },
max_lines => { type => "integer", minimum => 1, maximum => 100000, default => 2000,
description => "Max stdout lines after filtering." },
max_bytes => { type => "integer", minimum => 1, maximum => 1048576, default => 65536,
description => "Max returned UTF-8 bytes per stream; stderr unfiltered." },
);
sub fs_output_options {
my ($args) = @_;
my %options = (max_lines => $args->{max_lines} // 2000, max_bytes => $args->{max_bytes} // 65536);
for my $name (qw(max_lines max_bytes)) {
$options{$name} =~ /\A[0-9]+\z/ && $options{$name} >= 1
&& $options{$name} <= $output_schema{$name}{maximum}
or die "invalid $name\n";
my $cwd = Cwd::getcwd ();
defined $cwd && ($workdir eq "/" || $cwd eq $workdir || (index $cwd, "$workdir/") == 0)
or die "VCS cwd must resolve within the selected workdir\n";
exec {$ARGV[0]} @ARGV;
die "VCS exec: $!\n";
}, $workdir_bytes, (AnyEvent::MCP::utf8enc $cwd), @$argv] if defined $cwd;
my @command = ((fs_sandbox $workdir, $grants),
$bwrap ? @$argv
: ($remote ? $perl : $^X, "-e", 'chdir shift or die "chdir: $!"; exec @ARGV; die "exec: $!";', $workdir_bytes, @$argv));
my ($stdout, $stderr) = ("", "");
my ($stdout_cut, $stderr_cut);
my $capture = sub {
my ($handle, $out, $cut) = @_;
my $remaining = 1048576 - length $$out;
$$cut = 1 if length $handle->{rbuf} > $remaining;
$$out .= substr $handle->{rbuf}, 0, $remaining if $remaining > 0;
$handle->{rbuf} = "";
0
};
proc_run $req, \@command, $input, $timeout,
sub { $capture->($_[0], \$stdout, \$stdout_cut) },
sub { $capture->($_[0], \$stderr, \$stderr_cut) },
sub {
my ($status, $timed_out, $failure) = @_;
return $req->error ($failure) if $failure;
my $result = {
exit => $status >> 8, signal => $status & 127,
timed_out => $timed_out ? JSON::XS::true : JSON::XS::false,
capture_truncated => $stdout_cut || $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false,
};
my $finish = sub {
my $ok = eval {
$stdout_cut = 1 if length $stdout > $options->{max_bytes};
$stderr_cut = 1 if length $stderr > $options->{max_bytes};
my $out = fs_output_text (substr ($stdout, 0, $options->{max_bytes}), $stdout_cut);
my $err = fs_output_text (substr ($stderr, 0, $options->{max_bytes}), $stderr_cut);
my @lines = split /(?<=\n)/, $out;
if (@lines > $options->{max_lines}) {
splice @lines, $options->{max_lines};
$out = join "", @lines;
$stdout_cut = 1;
}
@$result{qw(stdout stderr)} = ($out, $err);
$result->{stdout_truncated} = $stdout_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
$result->{stderr_truncated} = $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
$result->{truncated} = $stdout_cut || $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
1
};
return $req->error ($@) unless $ok;
$req->reply (fs_result $result, exists $result->{filter_error});
};
return $finish->() unless exists $options->{grep};
{
my $ok = eval { $stdout = AnyEvent::MCP::utf8enc (fs_output_text $stdout, $stdout_cut); 1 };
return $req->error ($@) unless $ok;
}
# regex execution stays in a timed worker, outside the broker's event loop.
my @filter = ((fs_sandbox $workdir, $grants), $grep, "-aP", "--", $options->{grep});
fs_run $req, \@filter, $stdout, 5, 1048576, 0, sub {
my ($success, $filtered) = @_;
if (!$success || $filtered->{exit} > 1 || $filtered->{signal} || $filtered->{timed_out}) {
my $error = $success ? $filtered->{stderr} : $filtered;
$error = eval { fs_output_text (substr ($error, 0, 4096), 1) } || "no diagnostic";
$result->{filter_error} = "stdout filter failed: $error";
$stdout = "";
$stdout_cut = 1;
} else {
$stdout = $filtered->{stdout};
$stdout_cut ||= $filtered->{truncated};
}
$finish->();
};
my $needle = AnyEvent::MCP::utf8enc $args->{name};
$needle =~ s/([\\*?\[])/\\$1/g;
push @command, "!", "-type", "d", "-name", "*$needle*";
} else {
push @command, "-maxdepth", "1";
}
push @command, "-printf", q{%y\0%s\0%p\0};
my (@record, $seen, $truncated, $failure);
my $stderr = "";
proc_run $req, \@command, "", 30,
sub {
my ($handle, $eof) = @_;
while (!$failure and !$truncated
and $handle->{rbuf} =~ s/\A([^\0]*)\0([^\0]*)\0([^\0]*)\0//s) {
my ($type, $size, $raw_path) = ($1, $2, $3);
my $full_path = eval { AnyEvent::MCP::utf8dec $raw_path };
push @record, [$type, $size, $full_path];
}
$failure ||= "incomplete $tool output\n"
if $eof && length $handle->{rbuf} && !$truncated;
$handle->{rbuf} = "" if $failure or $truncated;
$failure || $truncated
},
sub {
my ($handle) = @_;
my $remaining = 65536 - length $stderr;
$stderr .= substr $handle->{rbuf}, 0, $remaining if $remaining > 0;
$handle->{rbuf} = "";
0
},
sub {
my ($status, $timed_out, $io_failure) = @_;
return if $req->{finished};
my $result;
my $ok = eval {
die "$tool timed out\n" if $timed_out;
die $failure || $io_failure if $failure || $io_failure;
if (($status >> 8 or $status & 127) and !$truncated) {
my $error = eval { AnyEvent::MCP::utf8dec $stderr };
$error = "non-UTF-8 error output" if $@;
die "$tool failed (exit " . ($status >> 8) . ", signal " . ($status & 127) . "): $error\n";
}
$result = fs_text_result (format_path_listing $path, \@record, $truncated);
1
};
if ($ok) {
$req->reply ($result);
fs_run $req, \@command, "", 30, $remaining, 0, sub {
my ($success, $value) = @_;
return $req->error ($value)
unless $success;
my $body;
my $ok = eval {
die "read-lines timed out\n" if $value->{timed_out};
if ($value->{exit} or $value->{signal}) {
my $stderr = AnyEvent::MCP::utf8dec $value->{stderr};
die "read-lines failed (exit $value->{exit}, signal $value->{signal}): $stderr\n";
}
if ($args->{linenums} && length $value->{stdout}) {
my $line = $start;
$value->{stdout} =~ s/^/$line++ . ":"/gme;
if (length $value->{stdout} > $remaining) {
substr ($value->{stdout}, $remaining) = "";
$value->{truncated} = 1;
}
}
$body = $encoding eq "utf-8" ? AnyEvent::MCP::utf8dec $value->{stdout}
my $write_error;
{
print $write $diff
or $write_error = "write patch: $!";
close $write;
}
my $status = $?;
unlink $errname
or return undef, "unlink patch stderr: $!";
defined sysseek $errfh, 0, 0
or return undef, "seek patch stderr: $!";
my $output = do { local $/; <$errfh> };
$output = "" unless defined $output;
$output =~ s/\s+\z//;
return undef, $write_error
if $write_error and !$status;
$status, $output
};
fs_run $req, \@command, "", 30, 1024 * 1024, $limit, sub {
my ($success, $result) = @_;
return $req->error ($result)
unless $success;
my $response;
my $ok = eval {
my $stdout = AnyEvent::MCP::utf8dec $result->{stdout};
my $stderr = AnyEvent::MCP::utf8dec $result->{stderr};
if (($result->{exit} or $result->{signal})
and !$result->{truncated} and !$result->{timed_out}) {
die "grep failed (exit $result->{exit}, signal $result->{signal}): $stderr\n";
}
$response = {
stdout => $stdout,
stderr => $stderr,
timed_out => $result->{timed_out},
truncated => $result->{truncated},
};
1
};
return $req->error ($@)
unless $ok;
$req->reply (fs_result $response);
};
$req->reply (fs_result { result => \@result });
};
}
;
mcp_tool exec =>
"Run argv " . ($bwrap ? "in bubblewrap. " : "UNSANDBOXED with full host-user privileges. ")
. ($bwrap ? "Private /tmp by default (gone after exec); use for temp files/IPC. shared-tmp exposes HOST /tmp (sockets/services). Request ONLY for HOST /tmp, NOT ordinary temp/IPC. " : "")
. "stdin_encoding: utf-8 (default), latin1 or base64; max 4 MiB decoded. "
. "stdout/stderr UTF-8, captured to 1 MiB each; max_lines/max_bytes bound response. Optional grep: PCRE stdout filter after capture; stderr unfiltered. Reports capture truncation. "
. "Explicit sandbox_grants replace default workdir-read. Exit/signal/timeout are normal results, not tool errors. No command-prefix safety classification. Timeout >300 s requires "
. "long-running grant; max six hours.",
{
type => "object",
properties => {
%output_schema,
workdir => $workdir_schema,
argv => {
type => "array",
items => { type => "string" },
}
;
# fixed operations accept filenames, never caller-supplied VCS options or shell code.
for my $operation (qw(diff status log)) {
mcp_tool "vcs-$operation" =>
"Run $operation via Git, SVN, CVS or Mercurial in workdir. "
. "Explicit backend; cwd within workdir (default .). "
. "files relative to cwd; must stay in workdir; never options. "
. "Dedicated permission plus workdir-read; CVS and SVN log also need ssh-agent/network. "
. "Returns exit/signal, bounded stdout/stderr, truncation flags. "
. "grep filters stdout via PCRE after 1 MiB capture; max_lines/max_bytes bound output. "
. "Trusts VCS client/config; sandbox enforces approved filesystem/network grants.",
{
type => "object",
properties => {
workdir => $workdir_schema,
cwd => { type => "string", default => ".",
description => "cwd relative to workdir; empty = .; must stay inside. Mount boundary unchanged." },
backend => { type => "string", enum => [qw(git svn cvs hg)] },
files => { type => "array", items => { type => "string" }, default => [] },
. "Inactive mappings expire after seven days; IDs may be reused; stale paths fail. "
. "Paths relative to selected workdir. "
. "workdir-read/write grant only selected workdir; all-workdirs-read/write grant every workdir. "
. "all-workdirs-read + workdir-write: read all, write selected only. "
. "Absolute paths in other workdirs need all-workdirs grants; other absolute paths need home/world grants or shared-tmp for host tmp. "
. "Multi-path stat stays in selected workdir; rename across paths needs combined grants and may fail EXDEV at mount boundary. "
. "Symlinks resolve inside granted mounts; overlapping workdir access unspecified. "
. "Trusted mounts add baseline authority; world-read keeps writable exceptions, world-write ignores them. "
. "exec requires useful reason and explicit sandbox_grants when needed. "
. "Prefer vcs-diff/vcs-status/vcs-log for working copies: explicit backend, fixed argv, automatic grants. "
. "exec/VCS: grep filters stdout via PCRE after capture; max_lines/max_bytes bound output; stderr unfiltered. "
. "capture_truncated means possible unseen matches.\n";
mcp_start %$server_options, (stdio => $stdio);
lib/AnyEvent/MCP/Client/JSONL.pm view on Meta::CPAN
command => [$program, @args],
env => { PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL => "stdio" },
);
=head1 DESCRIPTION
Use this transport when the MCP server is a subprocess or an already
connected byte stream. It reads one JSON-RPC message per line, so stdout
on a conventional stdio transport must contain protocol messages only.
The C<command> mode here connects the child's stdin and stdout to a
socketpair; diagnostic output belongs on stderr. A stray banner or log
message on the protocol stream can break the connection.
An argument array executes the program directly; a command string runs
through a shell. Prefer the array form when no shell syntax is needed.
The process starts on the first connection, not when the client object
is constructed.
=head1 FIRST CALL
To invoke a bundled server as a subprocess:
lib/AnyEvent/MCP/Client/JSONL.pm view on Meta::CPAN
Accepts the common L<AnyEvent::MCP::Client> options and these transport
options:
=over
=item command => [$program, $arg...]
=item command => $shell_command
Argument array for direct execution, or a string run through C</bin/sh -c>.
The child inherits stderr. No command runs until connecting.
Omit this option when using C<attach> instead.
=item env => { %environment }
Child environment overrides. Unspecified variables are inherited from
the parent; the parent environment is unchanged.
=item handle => { %handle }
L<AnyEvent::Handle> options. The filehandle and read/error/EOF callbacks
lib/AnyEvent/MCP/Helper.pm view on Meta::CPAN
);
$job->ask ($input, sub {
my ($success, $result) = @_;
...
});
=head1 DESCRIPTION
Runs an executable (or an argument array, never a shell command), writes one
UTF-8 JSON value to its stdin and closes that input. A successful helper
writes one JSON value to stdout and exits zero. Diagnostics use stderr.
C<ask ($input, $done)> calls C<$done-E<gt>($success, $result)> once. On failure,
C<$result> is an error string. One exchange may be active per object.
C<timeout> defaults to 300 seconds and C<max_size> to 1 MiB of output.
C<cancel ($reason)> terminates the helper and completes with failure.
The independent child watcher reaps the helper after cancellation too.
This module handles processes and bytes, not the meaning of the JSON.
It is the transport for local form and permission helpers: an MCP server
or multibroker can ask a human without blocking its AnyEvent loop.
lib/AnyEvent/MCP/Intro.pod view on Meta::CPAN
=head2 Choose stdio or HTTP
Use B<stdio> when your MCP client runs on the same machine and can launch
a server process. Configure the client to start the following command:
mcp-fs --stdio --name code /home/alice/src/project
The client starts this process and uses its stdin/stdout for MCP.
You do not start a second copy in a terminal, and there is no listener
URL or HTTP token to configure. Diagnostics go to stderr.
Clients that take a command and an argument array need these values:
command: mcp-fs
arguments: --stdio, --name, code, /home/alice/src/project
These describe separate arguments, not one shell command string.
Use an absolute executable path if the client cannot find C<mcp-fs>.
See L</CLIENT EXAMPLES> for examples of particular clients.
lib/AnyEvent/MCP/Intro.pod view on Meta::CPAN
workspace permissions. The tunnel client's CLI and supported configuration
forms can vary between releases; the examples above use the direct runtime
CLI rather than its optional profile setup. See
L<Secure MCP Tunnel|https://developers.openai.com/api/docs/guides/secure-mcp-tunnels>
for obtaining a tunnel, runtime, credentials and connecting it to ChatGPT.
=head1 TROUBLESHOOTING
=head2 The server does not start
Read stderr or the client's server log. Missing Perl modules, a missing
workdir, unsuitable utilities or an unavailable bubblewrap executable can
fail startup. Confirm that the client launches the same executable and
arguments you intended, with the expected C<PATH> and Perl installation.
For a local sandbox check, run from the project directory:
mcp-fs --exec-cmd workdir-read -- ls
This runs C<ls> with the named grants and trusted baseline mounts, without
MCP or saved permission rules. A failure here can identify a bubblewrap
lib/AnyEvent/MCP/Intro.pod view on Meta::CPAN
requested IMAP scope and saved C<user> name. Copy the complete redirected
address-bar URL after authorization, even when the browser displays an
unreachable loopback page.
If the server warns that it cannot save the master secret, another process
may derive a different token. Check write access to the global configuration.
Do not replace an existing secret simply to add a setting.
=head2 Connected, but there are no tools
Inspect the server's stderr for omitted utilities. mcp-fs's C<workdirs>
tool reports configuration even when a utility-dependent tool is absent.
For a multibroker, call C<discover-brokers> to see individual connection
errors, then C<list-tools> to refresh definitions.
A third-party child might require initialization or features this client
implementation does not support. See L<AnyEvent::MCP::Client> and its
transport documentation for limitations.
=head2 There is no approval dialog
First check whether the tool was denied by a saved rule or is waiting for
the client's own approval. An allowed operation needs no server prompt.
The default helper runs on the server machine. A background service may
have neither a usable display nor C</dev/tty>, even though your interactive
shell has both. Supply the appropriate display environment, a usable helper,
or C<--ask auto> with a modern client supporting form elicitation.
C<--ask mcp> reports an error if that support is absent.
Setting an asking mode cannot make an unsupported client display a form.
Check stderr and the tool error instead of assuming a missing dialog is
an approval.
=head2 It asks again after I chose allow
Allow-once covers one tool invocation, including its permission retries.
The next invocation asks again. Use allow-always to save a rule.
Inspect the saved rule's action, workdir and grants. Listing names and
reading contents are different actions. A rule for one exact workdir
spelling will not match a differently spelled startup argument.
lib/AnyEvent/MCP/Server/JSONL.pm view on Meta::CPAN
use AnyEvent;
use AnyEvent::MCP::Server::JSONL;
my $server = AnyEvent::MCP::Server::JSONL->new (
toolsets => [$tools],
);
$server->accept (\*STDIN, \*STDOUT);
AE::cv->recv;
C<$tools> is an L<AnyEvent::MCP::Server::Toolset>. Keep stdout reserved
for MCP messages and write diagnostics to stderr. The application is
responsible for its event loop and termination. If you do not need to
manage those details, use L<AnyEvent::MCP::Server::Simple/mcp_stdio>.
The matching client transport is L<AnyEvent::MCP::Client::JSONL>.
=head1 METHODS
=over
=item $handle = $server->accept ($fh, $fh_out)
lib/AnyEvent/MCP/Server/Simple.pm view on Meta::CPAN
Inspect the common options with:
perl echo-mcp --help
For a client launching a local subprocess, configure:
perl /absolute/path/to/echo-mcp --stdio
The client must launch the process itself. Stdin and stdout carry MCP,
so starting the program in a terminal and typing text at it is not a test
of the echo tool. Print diagnostics to stderr, not stdout.
You can make a first call without an AI client. Save this as C<try-echo>
in the same directory as C<echo-mcp>:
use common::sense;
use AnyEvent;
use AnyEvent::MCP::Client::JSONL;
my $client = AnyEvent::MCP::Client::JSONL->new (
command => [$^X, "./echo-mcp", "--stdio"],
lib/AnyEvent/MCP/Server/Simple.pm view on Meta::CPAN
=item on_request => $callback->($server, $req)
Synchronous hook before each dispatch attempt. For example, refresh
database state here. This does not replace dispatch or receive a
completion callback, and permission retries can invoke it again.
=item on_start => $callback->($server)
Called after the transport is ready, before entering the event loop.
Use it for startup information or installing watchers. Stdout carries
protocol messages in stdio mode; print diagnostics to stderr.
The callback must not block.
=item idle_exit => $seconds
Optional positive idle time for spawned stdio servers. With a multibroker
advertising C<anyevent-mcp/multibroker> version 1, Simple requests shutdown
once no MCP requests have been active for that long. The broker can ignore
the request. An application may veto shutdown with C<on_idle_shutdown>;
Simple retries after the configured interval if it is declined. HTTP servers,
ordinary clients and servers without this option are unaffected.
t/c02_config.t view on Meta::CPAN
ok !$@, "user-selected configuration permissions are accepted";
sub command {
my @args = @_;
my $err = Symbol::gensym;
my $pid = IPC::Open3::open3 (my $in, my $out, $err,
$^X, "-Ilib", "bin/anyevent-mcp", "--config", $file, @args);
close $in;
local $/;
my $stdout = <$out>;
my $stderr = <$err>;
waitpid $pid, 0;
($? >> 8, $stdout, $stderr)
}
my ($status, $output) = command ("password", "agni", "alice");
ok $status, "Basic password command is removed";
($status, $output) = command ("token", "agni");
ok $status && !$output, "token command removed";
($status, $output) = command ("url", "agni");
ok $status && !$output, "URL command removed";
($status, $output) = command ("--help");
ok !$status && $output =~ /Usage: anyevent-mcp/, "help command";
t/c06_multibroker.t view on Meta::CPAN
[$^X, "-Ilib", "bin/mcp-multibroker", @auth_options, ($cli ? ("--bind=127.0.0.1:$port") : ()), "--print-url"],
">" => \$url, "2>" => \$url_error,
);
$cv->recv == 0 or die "multibroker --print-url: $url_error\n";
}
chomp $url;
$url =~ s/\s+# user [^\n]*\z//;
my $pid;
END { kill TERM => $pid if $pid }
my $server_cv;
my ($stdout, $stderr);
{
local %ENV = (
%ENV,
PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL => "",
XDG_CONFIG_HOME => "$dir/http_config/$cli",
);
$server_cv = AnyEvent::Util::run_cmd (
[$^X, "-Ilib", "bin/mcp-multibroker", @auth_options, ($cli ? ("--bind=127.0.0.1:$port") : ()), child => $command[-1]],
"<" => "/dev/null", ">" => \$stdout, "2>" => \$stderr, '$$' => \$pid, close_all => 1,
);
}
$server_cv->cb (sub { undef $pid });
my $http_failures = 0;
my $http_diag = sub {
my ($step, $value) = @_;
++$http_failures;
print STDERR "multibroker HTTP cli=$cli $step: ", JSON::XS::encode_json ($value), "\n";
};
ok $url =~ m{\Ahttp://127\.0\.0\.1:}, "--bind overrides configured address"
t/c06_multibroker.t view on Meta::CPAN
$http_diag->("second token", [$success, $result]) unless $http_ok;
$web->close;
}
ok -f "$dir/http_config/$cli/anyevent-mcp/global.ini", "default HTTP startup stores its master secret";
kill TERM => $pid if $pid;
my ($ended, $exit) = wait_for (sub {
my ($done) = @_;
$server_cv->cb (sub { undef $pid; $done->(1, $_[0]->recv) });
});
ok !$stdout, "HTTP broker startup keeps stdout empty";
print STDERR "multibroker HTTP cli=$cli server exit=$exit stderr: ",
JSON::XS::encode_json (substr ($stderr // "", 0, 4096)), "\n" if $http_failures;
}
t/c13_vim_stdio.t view on Meta::CPAN
my $kind = $use_env ? "multibroker environment" : "explicit --stdio";
my ($pid, $in, $out, $err, $port) = start_child ($use_env);
my $init = rpc ($in, $out, 1, "initialize", {
protocolVersion => "2025-11-25",
capabilities => {}, clientInfo => { name => "stdio-test", version => "0" },
});
unless ($init) {
close $in;
my $exit = wait_exit ($pid);
my $stderr = do { local $/; <$err> };
diag "$kind: mcp-vim child exit=$exit, stderr: " . ($stderr // "");
fail "$kind: JSONL initialize response";
close $out;
close $err;
next;
}
is $init->{id}, 1, "$kind: JSONL initialize response";
ok !$init->{error} && $init->{result}{serverInfo},
"$kind: valid MCP server metadata";
t/c15_getoptions.t view on Meta::CPAN
sub command {
my ($script, @argv) = @_;
my $err = Symbol::gensym;
my $pid = IPC::Open3::open3 (my $in, my $out, $err,
$^X, "-Ilib", "-MAnyEvent::MCP::Server::Simple",
"-e", $script,
"--", @argv);
close $in;
local $/;
my $stdout = <$out>;
my $stderr = <$err>;
waitpid $pid, 0;
($? >> 8, $stdout // "", $stderr // "")
}
my $script = 'mcp_getoptions ({ usage => "usage in subprocess\n", path => "/custom/" });';
my ($status, $out, $err) = command ($script, "--name", "demo", "--bind", ":31740",
"--token", "first", "--token", "second", "--print-url");
is $status, 0, "shared print-url exits without starting a listener";
is $out, "http://127.0.0.1:31740/first/custom/\n", "print-url uses first CLI token and effective URL";
is $err, "", "print-url has no diagnostics";
($status, $out, $err) = command (
t/c15_getoptions.t view on Meta::CPAN
ok $started && $mode eq "none", "Simple supports deliberate auth none without inherited tokens";
for my $program (qw(mcp-fs mcp-ask-user mcp-multibroker mcp-vim),
$have_websocket ? "mcp-webbrowser" : ()) {
my $err = Symbol::gensym;
my $pid = IPC::Open3::open3 (my $in, my $out, $err,
$^X, "-Ilib", "bin/$program", "--help");
close $in;
local $/;
my $help = <$out> // "";
my $stderr = <$err> // "";
waitpid $pid, 0;
is $? >> 8, 0, "$program --help exits successfully";
like $help, qr/\AUsage: .+\n/, "$program has GNU-style synopsis";
like $help, qr/\nCommon options:\n.*--token TOKEN/s,
"$program includes shared MCP options";
like $help, qr/\nExamples:\n/, "$program includes practical examples"
unless $program eq "mcp-webbrowser";
if ($program eq "mcp-multibroker") {
like $help, qr/--listen/, "$program advertises its optional HTTP listener";
} else {
t/c15_getoptions.t view on Meta::CPAN
);
delete $tool_name{"mcp-webbrowser"} unless $have_websocket;
for my $program (sort keys %tool_name) {
my $error = Symbol::gensym;
my @extra = $program eq "mcp-fs" ? ("--sandbox", "none", ".") : ();
my $pid = IPC::Open3::open3 (my $in, my $stdout, $error,
$^X, "-Ilib", "bin/$program", "--tool-help", @extra);
close $in;
local $/;
my $output = <$stdout> // "";
my $stderr = <$error> // "";
waitpid $pid, 0;
ok !$? && $output =~ /\A\Q$tool_name{$program}\E\n/ && $output =~ / [a-z_-]+ /,
"$program prints registered tools with arguments and exits";
}
local $ENV{PERL_ANYEVENT_LOG} = ""; # test the default logger, not the harness filter.
my $log_probe = q{
use JSON::XS ();
my $options = mcp_getoptions;
my $req = {
t/c15_getoptions.t view on Meta::CPAN
{
local $ENV{PERL_ANYEVENT_LOG} = "log=file=$dir/activity.log";
($status, $out, $err) = command ($log_probe . q{
my $cv = AE::cv;
my $timer = AE::timer 0.2, 0, sub { $cv->send };
$cv->recv;
}, "--name", "redirect");
}
is $status, 0, "explicit AnyEvent::Log redirection succeeds";
is $err, "", "log=file sends activity and diagnostics away from stderr";
open my $fh, "<", "$dir/activity.log" or die $!;
local $/;
my $redirected = <$fh>;
close $fh;
like $redirected, qr/redirect\[\d+\] file-patch path=lib\/Foo.pm/,
"activity uses existing AnyEvent::Log file destination";
like $redirected, qr/redirect\[\d+\] error main: diagnostic failure/,
"diagnostics use the same existing AnyEvent::Log file destination";
done_testing;
t/c27_users.t view on Meta::CPAN
local $ENV{XDG_CONFIG_HOME} = $dir;
my $file = "$dir/anyevent-mcp/global.ini";
my $config = AnyEvent::MCP::Config->new (file => $file)->load->ensure_secret;
sub run {
my @cmd = @_;
my $err = Symbol::gensym;
my $pid = IPC::Open3::open3 (undef, my $out, $err, $^X, "-Ilib", @cmd);
local $/;
my $stdout = <$out> // "";
my $stderr = <$err> // "";
waitpid $pid, 0;
($? >> 8, $stdout, $stderr)
}
sub cli {
run "bin/anyevent-mcp", "--config", $file, @_
}
my ($help_status, $help_text, $help_errors) = cli "--help";
is $help_status, 0, "user management help succeeds: $help_errors";
like $help_text, qr/--program NAME.*select \[program NAME\]/,
"help explains program scope";
$result = call find => { path => "", name => "rea" };
ok !$result->{isError} && $result->{content}[0]{text} =~ /\tread\n/,
"empty find path selects workdir";
$result = call grep => { path => ".", pattern => "two" };
ok $result->{structuredContent}{stdout} =~ /read:2:two/, "grep worker result";
$result = call grep => { path => "", pattern => "two" };
ok !$result->{isError} && $result->{structuredContent}{stdout} =~ /read:2:two/,
"empty grep path selects workdir";
$result = call grep => { path => "read", pattern => "absent-grep-pattern-2026" };
ok !$result->{isError} && $result->{structuredContent}{stdout} eq ""
&& $result->{structuredContent}{stderr} eq "",
"grep no match in one existing file is a successful empty result";
$result = call grep => { path => ".", pattern => "absent-grep-pattern-2026" };
ok !$result->{isError} && $result->{structuredContent}{stdout} eq "",
"grep no matches in a directory is a successful empty result";
$result = call grep => { path => "read", pattern => q{^absent-grep-pattern-2026$}, mode => "pcre" };
ok !$result->{isError} && $result->{structuredContent}{stdout} eq "",
"PCRE grep no matches is a successful empty result";
$result = call grep => { path => "read", pattern => "[", mode => "pcre" };
ok $result->{isError} && $result->{content}[0]{text} =~ /grep failed/,
"malformed grep PCRE remains an error";
# output selection is shared by arbitrary exec and fixed VCS operations.
my $output_argv = [$^X, "-e", 'print "one\nkeep two\nkeep three\nlast"; print STDERR "unfiltered\n"; exit 7'];
SKIP: {
skip "extended GNU grep output tests (PERL_ANYEVENT_MCP_TESTS=1)", 4
unless ($ENV{PERL_ANYEVENT_MCP_TESTS} || 0) >= 1;
skip "GNU grep is unavailable", 4 unless $utility{grep};
$result = call exec => { argv => $output_argv, reason => "filter output", grep => "^keep", max_lines => 1 };
ok $result->{structuredContent}{stdout} eq "keep two\n"
&& $result->{structuredContent}{stderr} eq "unfiltered\n", "exec filters stdout only before the line limit";
ok $result->{structuredContent}{exit} == 7 && $result->{structuredContent}{stdout_truncated}
&& !$result->{structuredContent}{capture_truncated}, "postfilter limits preserve original exit status and capture completeness";
my $output_subject = $prompts[-1]{dimensions}{subject}{value};
$result = call exec => { argv => $output_argv, reason => "different output filter", grep => "^absent" };
ok $result->{structuredContent}{stdout} eq "" && $result->{structuredContent}{exit} == 7,
"no grep matches is distinct from command success";
ok $prompts[-1]{dimensions}{subject}{value} eq $output_subject, "output options do not change the executable permission subject";
}
$result = call exec => { argv => [$^X, "-e", 'print "abcdef"; print STDERR "uvwxyz"'],
reason => "independent byte budgets", max_bytes => 3 };
my $valid = $result->{structuredContent}{stdout} eq "abc" && $result->{structuredContent}{stderr} eq "uvw"
&& $result->{structuredContent}{stdout_truncated} && $result->{structuredContent}{stderr_truncated};
ok $valid,
"stdout and stderr have independent return budgets";
diag JSON::XS::encode_json $result unless $valid;
$result = call exec => { argv => [$^X, "-e", 'binmode STDOUT; print "\xc3\xa4\xc3\xa4"'],
reason => "UTF-8 clipping", max_bytes => 3 };
ok !$result->{isError} && $result->{structuredContent}{stdout} eq "\x{e4}" && $result->{structuredContent}{truncated},
"byte clipping preserves a complete UTF-8 prefix";
SKIP: {
skip "extended GNU grep output tests (PERL_ANYEVENT_MCP_TESTS=1)", 2
unless ($ENV{PERL_ANYEVENT_MCP_TESTS} || 0) >= 1;
skip "GNU grep is unavailable", 2 unless $utility{grep};
$result = call exec => { argv => [$^X, "-e", 'print "x" x 1100000; print STDERR "visible\n"; exit 9'],
reason => "bounded capture before filtering", grep => "^absent" };
ok $result->{structuredContent}{stdout} eq "" && $result->{structuredContent}{stderr} eq "visible\n"
&& $result->{structuredContent}{capture_truncated} && $result->{structuredContent}{exit} == 9,
"capture truncation is explicit even when no captured line matches";
$result = call exec => { argv => $output_argv, reason => "invalid filter", grep => "(" };
ok $result->{isError} && $result->{structuredContent}{filter_error}
&& $result->{structuredContent}{exit} == 7, "filter failure retains the original command status";
}
my $before_output = @prompts;
$result = call exec => { argv => $output_argv, reason => "invalid limit", max_bytes => 0 };
ok $result->{isError} && @prompts == $before_output, "invalid output limits fail before permission or execution";
my $before_vcs = read_file "$dir/vcs.log";
$result = call "vcs-status" => { backend => "git", files => [""] };
ok $result->{isError} && read_file ("$dir/vcs.log") eq $before_vcs,
"empty VCS filename remains invalid";
$result = call "vcs-status" => { backend => "git", cwd => "../home" };
ok $result->{isError} && read_file ("$dir/vcs.log") eq $before_vcs,
"lexical cwd escape is rejected before execution";
symlink "$dir/home", "$dir/work/external-cwd" or die $!;
$result = call "vcs-status" => { backend => "git", cwd => "external-cwd" };
ok $result->{structuredContent}{exit} != 0 && read_file ("$dir/vcs.log") eq $before_vcs
&& $result->{structuredContent}{stderr} =~ /cwd must resolve within/,
"worker rejects resolved cwd escape before starting VCS";
symlink "sub", "$dir/work/internal-cwd" or die $!;
$result = call "vcs-status" => { backend => "git", cwd => "internal-cwd" };
ok !$result->{isError} && read_file ("$dir/vcs-cwd.log") eq "$dir/work/sub",
"internal cwd symlink is allowed";
$before_vcs = read_file "$dir/vcs.log";
$result = call "vcs-status" => { backend => "git", cwd => "missing-cwd" };
ok $result->{structuredContent}{exit} != 0 && read_file ("$dir/vcs.log") eq $before_vcs,
"missing cwd cannot start VCS";
$result = call "vcs-diff" => { backend => "cvs", files => ["../outside"] };
$prompts_before = @prompts;
$result = call exec => { argv => $hex_stdin, stdin => $too_large_stdin,
stdin_encoding => "base64", reason => "reject decoded oversize" };
ok $result->{isError} && @prompts == $prompts_before
&& $result->{content}[0]{text} =~ /stdin exceeds 4 MiB/,
"stdin size limit applies to decoded bytes before permission";
$result = call exec => { argv => [$^X, "-e", 'print "diff\n"; warn "message\n"; exit 1'], reason => "nonzero is data" };
$valid = !$result->{isError} && $result->{structuredContent}{exit} == 1
&& $result->{structuredContent}{stdout} eq "diff\n"
&& $result->{structuredContent}{stderr} eq "message\n";
ok $valid,
"nonzero command exit returns ordinary structured data";
diag JSON::XS::encode_json $result unless $valid;
$result = call exec => {
argv => [$^X, "-e", q{
defined (my $pid = fork) or die $!;
exit 7 if $pid;
select undef, undef, undef, 0.1;
print "late stdout\n";
print STDERR "late stderr\n";
}],
reason => "test output after child exit",
};
$valid = !$result->{isError} && $result->{structuredContent}{exit} == 7
&& $result->{structuredContent}{stdout} eq "late stdout\n"
&& $result->{structuredContent}{stderr} eq "late stderr\n";
ok $valid,
"completion waits for both output streams after the child exits";
diag JSON::XS::encode_json $result unless $valid;
$result = call exec => {
argv => [$^X, "-e", q{
close STDIN;
close STDOUT;
close STDERR;
select undef, undef, undef, 0.1;
exit 9;
}],
reason => "test child exit after output closes",
};
$valid = !$result->{isError} && $result->{structuredContent}{exit} == 9
&& $result->{structuredContent}{stdout} eq ""
&& $result->{structuredContent}{stderr} eq "";
ok $valid,
"completion waits for child status after both output streams close";
diag JSON::XS::encode_json $result unless $valid;
$result = call exec => { argv => [$^X, "-e", 'kill TERM => $$'], reason => "signal is data" };
ok !$result->{isError} && $result->{structuredContent}{signal} == 15,
"signal termination returns an ordinary process result";
SKIP: {
skip "extended command timeout test (PERL_ANYEVENT_MCP_TESTS=1)", 1
unless ($ENV{PERL_ANYEVENT_MCP_TESTS} || 0) >= 1;
$result = call exec => {
argv => [$^X, "-e", '$| = 1; print "before timeout\n"; print STDERR "before timeout\n"; sleep 30'],
timeout => 1, reason => "test timeout abandons output",
};
ok !$result->{isError} && $result->{structuredContent}{timed_out}
&& $result->{structuredContent}{truncated}
&& $result->{structuredContent}{exit} == 0
&& $result->{structuredContent}{signal} == 9
&& $result->{structuredContent}{stdout} eq "before timeout\n"
&& $result->{structuredContent}{stderr} eq "before timeout\n",
"timeout returns captured output as truncated with the real child status";
}
my $sandbox = read_file "$dir/sandbox.log";
ok $sandbox =~ /--unshare-net/ && $sandbox =~ /--ro-bind/ && $sandbox =~ /--disable-userns/
&& $sandbox !~ /\/run\/anyevent-mcp\.pm/,
"sandbox retains isolation flags without mounting application source";
ok $sandbox =~ /"--setenv","PERL_BADLANG","0"/,
"sandbox suppresses Perl warnings if the requested UTF-8 locale is unavailable";
$req->reply ({
action => "accept", content => {
decision => "allow-once",
sandbox_grants => join ",", @{$full_grant ? $request->{sandbox_grants} : ["workdir-write"]},
},
});
};
my @captured_server = (
$^X, "-Ilib", "-e",
'open STDERR, ">>", shift @ARGV or die $!; do shift @ARGV; die $@ if $@;',
"$dir/unsandboxed.stderr", "$root/bin/mcp-fs", "--name", "default", "--quiet",
);
$client = AnyEvent::MCP::Client::JSONL->new (
command => [@captured_server, "--stdio", "--ask", "mcp",
"--sandbox=none", "--bwrap", "$dir/nonexistent-bwrap", "$dir/work"],
env => \%env, client_capabilities => { elicitation => { form => {} } },
on_request => $direct_answer,
);
$result = call "file-write" => { path => "direct-test", data => MIME::Base64::encode_base64 ("ok", "") };
ok $result->{isError} && !-e "$dir/work/direct-test",
"unsandboxed file-write rejects insufficient sandbox grants";
$full_grant = 1;
$result = call exec => { argv => $direct_argv, sandbox_grants => [], reason => "direct test" };
ok !$result->{isError} && $result->{structuredContent}{stdout} eq "direct" && -f "$dir/work/direct-exec-ran",
"unsandboxed exec runs after full approval even with a narrow client request";
$client->close;
# Persist exactly this command with the full authority direct execution receives.
my @saved_command = (
$^X, "-Ilib", "-e",
'open STDERR, ">>", shift @ARGV or die $!; do shift @ARGV; die $@ if $@;',
"$dir/saved.stderr", "$root/bin/mcp-fs", "--name", "saved-max",
"--stdio", "--ask", "mcp", "--sandbox=none", "$dir/work",
);
my $saved_argv = [$^X, "-e", 'open my $fh, ">", $ARGV[0] or die $!; print {$fh} "saved"; print "saved"', "$dir/work/saved-max"];
my @save_stages;
$client = AnyEvent::MCP::Client::JSONL->new (
command => \@saved_command, env => \%env,
client_capabilities => { elicitation => { form => {} } },
on_request => sub {
my ($client, $req) = @_;
my $meta = $req->{params}{_meta}{"anyevent-mcp/permission"};
command => [$^X, "-e",
'open STDERR, ">", shift @ARGV or die $!; exec {$ARGV[0]} @ARGV; die $!;',
"$dir/failing-startup-$mode", $^X, "-Ilib", "bin/mcp-fs", "--stdio", "--ask", "mcp",
"--sandbox=$mode", "--bwrap", "$dir/failing-bwrap", "$dir/work"],
env => \%env, client_capabilities => { elicitation => { form => {} } },
on_request => $direct_answer,
);
my ($listed) = wait_for (sub { $client->tools ($_[0]) });
ok !$listed && !-e "$dir/work/fallback-exec-$mode",
"$mode fails startup when sandbox Perl cannot run, without direct fallback";
my $stderr = read_file "$dir/failing-startup-$mode";
like $stderr, qr/\Adeliberate bubblewrap failure\nPerl 'perl' cannot run in the worker environment\n\z/,
"$mode captures and checks the expected startup diagnostics without printing them";
$client->close;
}
$client = AnyEvent::MCP::Client::JSONL->new (
command => [@captured_server, "--stdio", "--ask", "mcp",
"--sandbox=auto", "--bwrap", "$dir/nonexistent-bwrap", "$dir/work"],
env => \%env, client_capabilities => { elicitation => { form => {} } },
on_request => $direct_answer,
);
$result = call "file-write" => { path => "auto-test", data => MIME::Base64::encode_base64 ("auto", "") };
ok !$result->{isError} && read_file ("$dir/work/auto-test") eq "auto"
&& $direct_requests[-1]{sandbox_implementation} =~ /UNSANDBOXED/,
"auto mode without bubblewrap requests full authority and runs directly";
$client->close;
my $unsandboxed_stderr = read_file "$dir/unsandboxed.stderr";
unlike $unsandboxed_stderr, qr/SANDBOX NONE|bubblewrap unavailable/,
"explicit none and default-filtered auto modes produce no sandbox warning";
my @warn_server = @captured_server;
$warn_server[4] = "$dir/auto-warning.stderr";
$client = AnyEvent::MCP::Client::JSONL->new (
command => [@warn_server, "--stdio", "--ask", "mcp",
"--sandbox=auto", "--bwrap", "$dir/nonexistent-bwrap", "$dir/work"],
env => { %env, PERL_ANYEVENT_LOG => "filter=warn log=warn" },
client_capabilities => { elicitation => { form => {} } },
on_request => $direct_answer,
);
$result = call workdirs => {};
$client->close;
like read_file ("$dir/auto-warning.stderr"), qr/warn .*bubblewrap unavailable, running without sandbox/,
"auto fallback emits a warning when logging warnings is enabled";
my $old_sandbox_log = read_file "$dir/sandbox.log";
$client = AnyEvent::MCP::Client::JSONL->new (
command => [$^X, "-Ilib", "bin/mcp-fs", "--stdio", "--ask", "mcp",
"--sandbox=auto", "--bwrap", "$dir/bwrap", "$dir/work"],
env => \%env, client_capabilities => { elicitation => { form => {} } },
on_request => $direct_answer,
);
$result = call "file-read" => { path => "auto-test" };
my ($url, $url_error);
{
local %ENV = (%ENV, %env, PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL => "");
my $cv = AnyEvent::Util::run_cmd (
[$^X, "-Ilib", "bin/mcp-fs", "--name", "default", "--bind", $bind, "--print-url"],
">" => \$url, "2>" => \$url_error,
);
$cv->recv == 0 or die "mcp-fs --print-url: $url_error\n";
}
chomp $url;
my ($http_pid, $stderr, $stdout);
END { kill TERM => $http_pid if $http_pid }
my $server_cv;
{
local %ENV = (%ENV, %env, PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL => "");
$server_cv = AnyEvent::Util::run_cmd (
[$^X, "-Ilib", "bin/mcp-fs", "--name", "default", "--bind", $bind,
"--bwrap", "$dir/bwrap", "$dir/work"],
"<" => "/dev/null", ">" => \$stdout, "2>" => \$stderr, '$$' => \$http_pid, close_all => 1,
);
}
my $ready;
for (1 .. 1500) {
$ready = IO::Socket::INET->new (PeerAddr => "127.0.0.1", PeerPort => $port, Proto => "tcp", Timeout => 1);
last if $ready;
Time::HiRes::sleep (0.02);
}
$ready or die "filesystem listener did not start: $!\n";
close $ready;
my $web = AnyEvent::MCP::Client::HTTP->new (url => $url);
($success, $result) = wait_for (sub { $web->call (workdirs => {}, $_[0]) });
ok $success && $result->{structuredContent}{workdirs}{1} eq "$dir/work", "explicitly discovered HTTP URL is usable";
$web->close;
kill TERM => $http_pid;
$server_cv->recv;
undef $http_pid;
ok !$stdout, "filesystem HTTP startup keeps stdout empty";
ok $stderr =~ /Permission rules: \Q$dir\E\/config\/anyevent-mcp\/rules\/fs-default\.ini/,
"HTTP startup identifies the live permission rule file";
# Program mounts are merged with named-instance overrides; no implicit /opt.
File::Path::mkpath (["$dir/shared", "$dir/only", "$dir/suppressed", "$dir/optional"], 0, 0700);
write_file "$dir/config/anyevent-mcp/global.ini", <<EOF;
[program mcp-fs]
prepend-path = $dir/bin
mount.aa = ro:$dir/suppressed
mount.bb = rw:$dir/shared
mount-try.missing = ro:$dir/optional-later
t/e11_permission_ui.t view on Meta::CPAN
my $status = AnyEvent::Util::run_cmd (
[$^X, "-Ilib", "-MPOSIX", "-e",
'defined POSIX::setsid () or die $!; do shift @ARGV; die $@ if $@;',
"./bin/anyevent-mcp-askpermission", @prompt_options],
"<" => \$input, ">" => \$output, "2>" => \$error,
)->recv;
is $status, 0, "helper returns a decision successfully";
my $decision = eval { JSON::XS::decode_json $output };
my $decode_error = $@;
diag "permission helper status=", (defined $status ? $status : "undef"),
" stderr=", $json->encode ($error), " stdout=", $json->encode ($output),
" decode error=", $decode_error
if !defined $status || $status != 0 || $decode_error;
die $decode_error if $decode_error;
$decision
}
is +(AnyEvent::MCP::Server::Permissions->new)->{ask}, "helper", "approval defaults to a local helper";
my $decision = prompt $request, { status => 4, output => "Do it, wrong file\x1f\n" };
is_deeply $decision, { decision => "allow-once", sandbox_grants => ["write"] },
"allow-once uses requested grants and discards denial reason";
t/e12_vim_startup.t view on Meta::CPAN
qa!
VIM
close $fh or die "$script: $!";
my $errors = "$dir/vim-errors";
my $error = Symbol::gensym;
my $pid = IPC::Open3::open3 (my $input, my $output, $error,
$vim, "-Nu", "NONE", "-i", "NONE", "-n", "-es", "-S", $script, "--", $errors);
close $input;
local $/;
my $stdout = <$output>;
my $stderr = <$error>;
waitpid $pid, 0;
my $status = $?;
open $fh, "<", $errors or die "$errors: $!";
my $messages = <$fh> // "";
close $fh;
skip $messages, 2 if !$status && $messages =~ /\ASKIP:/;
is $status, 0, "real Vim loads the plugin and exercises unrestricted Ex RPC";
diag $stdout, $stderr if $status;
is $messages, "", "real Vim captures messages, changes state, propagates errors and retains partial effects";
}
done_testing;
t/e14_multibroker_eager.t view on Meta::CPAN
($exit_status, $error_text) = $broker_exit->(
http => "http://127.0.0.1:12345/", "--required"
);
ok defined $exit_status && $exit_status != 0
&& $error_text =~ /--required requires a stdio broker/,
"HTTP children cannot be marked required";
# A flag after a broker pair belongs to that pair, not to the entire command.
# --eager is invalid for HTTP and must not silently enable any stdio peer.
my $stderr = Symbol::gensym;
my $pid = IPC::Open3::open3 (my $in, my $out, $stderr,
$^X, "-Ilib", "bin/mcp-multibroker",
http => "http://127.0.0.1:12345/", "--eager",
);
close $in;
local $/;
my $diagnostic = <$stderr>;
my $status = waitpid ($pid, 0);
ok $status == $pid && ($? >> 8) != 0
&& $diagnostic =~ /--eager requires a stdio broker/,
"HTTP --eager is rejected with useful error";
close $out;
close $stderr;
# Disabled entries stay in argv but never produce clients, even with eager
# or required set before --disable. They are also absent from explicit discovery.
my $disabled_marker = "$dir/disabled";
my $enabled_marker = "$dir/enabled";
$client = AnyEvent::MCP::Client::JSONL->new (
command => [$^X, "-Ilib", "bin/mcp-multibroker",
off => "---", $^X, "-Ilib", $child, $disabled_marker, "---",
"--eager", "--required", "--disable",
off_http => "http://127.0.0.1:1/", "--required", "--disable",
t/e14_multibroker_eager.t view on Meta::CPAN
"legacy shell form can pass the reserved delimiter as an argument";
$client->close;
for my $case (
[["child", "---", "---"], qr/Empty stdio argv/],
[["child", "---", "", "---"], qr/Empty stdio argv/],
[["child", "---", $^X], qr/Missing closing ---/],
[["child", "---", $^X, "---", "--bearer", "token"], qr/Authentication options require an HTTP broker/],
[["child", "---", $^X, "---", "--unknown-child-option"], qr/Unknown option/],
) {
my $stderr = Symbol::gensym;
my $pid = IPC::Open3::open3 (my $in, my $out, $stderr,
$^X, "-Ilib", "bin/mcp-multibroker", "--stdio", @{$case->[0]});
close $in;
local $/;
my $diagnostic = <$stderr>;
my $status = waitpid ($pid, 0);
ok $status == $pid && ($? >> 8) != 0 && $diagnostic =~ $case->[1],
"malformed argv entry or misplaced downstream option is rejected";
close $out;
close $stderr;
}
SKIP: {
skip "extended idle lifetime tests (PERL_ANYEVENT_MCP_TESTS=1)", 7 unless ($ENV{PERL_ANYEVENT_MCP_TESTS} || 0) >= 1;
my $idle = "$dir/idle";
my $idle_command = $command->($idle) . " 0.05";
$client = AnyEvent::MCP::Client::JSONL->new (
command => [$^X, "-Ilib", "bin/mcp-multibroker", idle => $idle_command],
env => {
t/e19_local_forms.t view on Meta::CPAN
$client->close;
}
# Independently running HTTP servers delegate to the broker too.
my $listener = IO::Socket::INET->new (
LocalAddr => "127.0.0.1", LocalPort => 0, Proto => "tcp", Listen => 1,
) or die $!;
my $port = $listener->sockport;
close $listener;
my ($pid, $stdout, $stderr);
my $server;
{
local %ENV = (%ENV, %env);
$server = AnyEvent::Util::run_cmd (
[$^X, "-Ilib", "bin/mcp-ask-user", "--ask", "mcp", "--bind", "127.0.0.1:$port", "--token", "form-test"],
"<" => "/dev/null", ">" => \$stdout, "2>" => \$stderr, '$$' => \$pid,
);
}
my $ready;
for (1 .. 1500) {
$ready = IO::Socket::INET->new (PeerAddr => "127.0.0.1", PeerPort => $port, Proto => "tcp");
last if $ready;
Time::HiRes::sleep (0.02);
}
ok $ready, "standalone HTTP question server is listening";
close $ready if $ready;
t/e21_connect.t view on Meta::CPAN
ok rejected (["mcp-connect", "cookie", "remote"]), "occupied alias is rejected";
($success, $result) = wait_for (sub { $upstream->call ("remote.disconnect", {}, $_[0]) });
ok !$success || $result->{isError}, "disconnect fails the outstanding call";
wait_alias "remote";
($success, $result) = wait_for (sub { $upstream->call ("remote.echo", { value => 43 }, $_[0]) });
ok $success && $result->{structuredContent}{value} == 43, "reverse server reconnects under the same alias";
is $slow_calls, 1, "disconnected operations are never replayed";
File::Path::mkpath ("$dir/work", 0, 0700);
my ($pid, $stdout, $stderr);
my $child = AnyEvent::Util::run_cmd (
[$^X, "-Ilib", "bin/mcp-fs", "--connect", "$url/files", "--sandbox", "none", "$dir/work"],
"<" => "/dev/null", ">" => \$stdout, "2>" => \$stderr, '$$' => \$pid,
);
wait_alias "files";
($success, $result) = wait_for (sub { $upstream->call ("files.workdirs", {}, $_[0]) });
ok $success && grep ($_ eq "$dir/work", values %{$result->{structuredContent}{workdirs}}),
"mcp-fs --connect works through shared startup";
kill TERM => $pid;
$child->recv;
is $stdout, "", "reverse server does not emit protocol on stdout";
File::Path::mkpath ("$dir/config/anyevent-mcp/rules", 0, 0700);
t/e21_connect.t view on Meta::CPAN
skip "WebSocket modules not installed", 2 unless eval {
require AnyEvent::WebSocket::Server;
require AnyEvent::WebSocket::Message;
1
};
open my $rules, ">", "$dir/config/anyevent-mcp/rules/webbrowser-default.ini" or die $!;
print {$rules} "[rule]\ndecision=allow\naction=read\nsandbox-grants=\n";
close $rules or die $!;
$child = AnyEvent::Util::run_cmd (
[$^X, "-Ilib", "bin/mcp-webbrowser", "--connect", "$url/browser", "--bind", "127.0.0.1:0"],
"<" => "/dev/null", ">" => \$stdout, "2>" => \$stderr, '$$' => \$pid,
);
wait_alias "browser";
($success, $result) = wait_for (sub { $upstream->call ("browser.tabs", {}, $_[0]) });
ok $success && !@{$result->{structuredContent}{tabs}},
"mcp-webbrowser --connect serves MCP while retaining its browser listener";
kill TERM => $pid;
$child->recv;
unlike $stderr, qr/EV: error|already finished|Can't call/, "reverse browser shutdown has no callback errors";
}
$downstream->close;
$web->close;
$upstream->close;
done_testing;
t/e26_tls.t view on Meta::CPAN
use File::Temp ();
use JSON::XS ();
eval { require AnyEvent::TLS; require Net::SSLeay; 1 }
or plan skip_all => "TLS support unavailable";
my $dir = File::Temp::tempdir (CLEANUP => 1);
my ($cert, $key, $combined) = map "$dir/$_", qw(cert.pem key.pem combined.pem);
my $generated;
{
open my $saved_stderr, ">&", \*STDERR or die $!;
open STDERR, ">", "/dev/null" or die $!;
$generated = system ("openssl", "req", "-quiet", "-x509", "-newkey", "rsa:2048", "-noenc",
"-days", "1", "-keyout", $key, "-out", $cert, "-subj", "/CN=localhost",
"-addext", "subjectAltName=DNS:localhost",
"-addext", "basicConstraints=critical,CA:TRUE");
open STDERR, ">&", $saved_stderr or die $!;
}
$generated == 0
or plan skip_all => "openssl certificate generation unavailable";
open my $combined_out, ">:raw", $combined or die $!;
for my $path ($key, $cert) {
open my $in, "<:raw", $path or die $!;
local $/;
print {$combined_out} <$in>;
}