AnyEvent-MCP
view release on metacpan or search on metacpan
t/c15_getoptions.t view on Meta::CPAN
local @ARGV = ("--name", "example");
my $options = mcp_getoptions ({ path => "/custom/", auth => "none" });
is $options->{path}, "/custom/", "custom endpoint path is returned for startup";
is $options->{auth}, "none", "explicit unauthenticated mode passed to startup";
}
{
local @ARGV = ("--bad-option");
my $error;
{
local *STDERR;
open STDERR, ">", "/dev/null" or die "open /dev/null: $!";
eval { mcp_getoptions ({ usage => "custom usage\n" }) };
$error = $@;
}
like $error, qr/custom usage/, "usage shown on invalid options";
}
{
local @ARGV = ("--ask", "none");
my $options = mcp_getoptions;
is $options->{ask}, "none", "shared --ask none is parsed";
}
{
local @ARGV = ("--ask", "none");
my $error;
{
local *STDERR;
open STDERR, ">", "/dev/null" or die $!;
eval { mcp_getoptions ({ without => ["ask"] }) };
$error = $@;
}
like $error, qr/Usage:/, "individually excluded common option is rejected";
}
{
local @ARGV = ();
my $error = eval { mcp_getoptions ({ without => ["not-an-option"] }); 1 };
like $@, qr/Unknown common option/, "misspelled common option exclusion is rejected";
}
{
local @ARGV = ("--name", "example");
my $options = mcp_getoptions;
is_deeply $options, { name => "example" }, "no unnecessary option defaults";
}
my $dir = File::Temp::tempdir (CLEANUP => 1);
local $ENV{XDG_CONFIG_HOME} = $dir;
my $config = AnyEvent::MCP::Config->new (file => "$dir/anyevent-mcp/global.ini")->load->ensure_secret;
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 (
'mcp_getoptions ({ path => "/custom/", print_url_extra => sub { '
. 'my $http = shift; print "ws://$http->{host}:$http->{port}/\n"; } });',
"--bind", "127.0.0.1:31740", "--token", "first", "--print-url");
is $status, 0, "application-specific URL printing succeeds";
is $out, "http://127.0.0.1:31740/first/custom/\nws://127.0.0.1:31740/\n",
"supplementary URL follows normal credentialed endpoint";
($status, $out, $err) = command ($script, "--name", "demo", "--bind", ":31740",
"--token", "first", "--tls-key", "combined.pem", "--print-url");
is $status, 0, "combined TLS PEM URL discovery succeeds";
is $out, "https://127.0.0.1:31740/first/custom/\nhttp://127.0.0.1:31740/first/custom/\n",
"TLS URL discovery prints HTTPS first and HTTP second";
is $err, "", "TLS URL discovery has no diagnostics";
($status, $out) = command ($script, "--name", "demo", "--help");
is $status, 0, "standard --help succeeds";
my ($excluded_status, $excluded_help) = command ('mcp_getoptions ({ without => ["ask", "set"] });', "--help");
ok !$excluded_status && $excluded_help !~ /--ask MODE/ && $excluded_help !~ /--set KEY=VALUE/
&& $excluded_help =~ /--name NAME/,
"individual common-option exclusions also suppress their help entries";
like $out, qr/\Ausage in subprocess\n\nCommon options:\n/,
"shared help includes usage and common option heading";
like $out, qr/--name NAME\s+Select named configuration/,
"common --name option documented";
like $out, qr/--token TOKEN\s+Set an accepted token/,
"common repeatable token option documented";
like $out, qr/-s, --set KEY=VALUE\s+Override a trusted instance setting/,
"shared short and long configuration override documented";
unlike $out, qr/--listen/, "common parser does not advertise --listen";
($status, $out, $err) = command ($script, "--listen");
ok $status && $err =~ /Unknown option: listen/, "common parser rejects --listen";
my $rich = 'my $extra; mcp_getoptions ({'
. 'usage => "Usage: fixture [OPTION]...\\n", '
. 'description => "A test server.", '
. 'option_heading => "Fixture options:", '
. 'options => [["--extra VALUE", "A configurable value"]], '
. 'examples => " fixture --extra yes"}, '
. '"extra=s" => \\$extra);';
($status, $out, $err) = command ($rich, "--help");
ok !$status && !$err && $out =~ /Fixture options:.*--extra VALUE.*A configurable value/s
&& $out =~ /Examples:\n fixture --extra yes/, "caller option descriptions and examples appear";
($status, $out, $err) = command ($script, "--name", "demo", "--bind", ":0", "--print-url");
ok $status && $err =~ /port is not known/, "ephemeral port cannot be printed offline";
open my $fh, ">>", "$dir/anyevent-mcp/global.ini" or die $!;
print {$fh} "\n[instance named]\npath = /named/\n[instance mail\@doom.example+test]\npath = /mailbox/\n";
close $fh or die $!;
t/c15_getoptions.t view on Meta::CPAN
is_deeply [$configured->auto_rules ("other")], [
["allow", "*,read,workdir-read"],
["allow", "*,write,workdir-write"],
["deny", "*,exec,*"],
], "program-level permission rules sorted by key";
is_deeply [$configured->auto_rules ("named")], [
["allow", "*,read,workdir-read"],
["deny", "*,write,workdir-write"],
["allow", "tabs"],
], "instance overrides, removes, and adds inherited permission rules";
$configured->{section}{"instance named"}{"auto-rule.40"} = "bad";
eval { $configured->auto_rules ("named") };
like $@, qr/Invalid configured automatic permission rule/, "invalid configured rule rejected";
}
my $auto_probe = q{
require AnyEvent::MCP::Server::Permissions;
my $options = mcp_getoptions;
my $p = AnyEvent::MCP::Server::Permissions->new (
sandbox_grants => {
"workdir-read" => [],
"workdir-write" => ["workdir-read"],
},
auto_rules => [["deny", "*,inspect"]],
);
mcp_permissions $p;
mcp_start %$options, auth => "none", port => 0, on_start => sub {
print join (" ", map {
$p->check ({ action => $_->[0], sandbox_grants => $_->[1], reason => "test" }, $_->[2])->{decision}
} (["read", ["workdir-write"], "x"], ["write", ["workdir-write"], "x"],
["exec", [], "x"], ["inspect", [], "tabs"])), "\n";
$_[0]->close;
};
};
my ($autostatus, $autoout, $autoerr) = command ($auto_probe, "--name", "named");
ok !$autostatus && !$autoerr && $autoout eq "ask deny ask allow\n",
"mcp_start loads ordered instance defaults and leaves unmatched requests to prompting";
($autostatus, $autoout, $autoerr) = command ($auto_probe, "--name", "named",
"--auto-allow=*,write,*");
ok !$autostatus && !$autoerr && $autoout eq "ask allow ask allow\n",
"CLI rule takes precedence over named program/instance defaults";
mcp_start
name => "explicit_no_auth",
auth => "none", port => 0,
on_start => sub {
$started = 1;
$mode = $_[0]{auth};
$_[0]->close;
};
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 {
unlike $help, qr/--listen/, "$program does not advertise --listen";
}
like $help, qr/--bind ADDRESS/, "$program retains configurable bind address";
like $help, qr/Filesystem options:/, "filesystem options documented"
if $program eq "mcp-fs";
if ($program eq "mcp-multibroker") {
like $help, qr/\nCommon options:.*?--ask MODE\b/s,
"multibroker --ask is documented as a shared upstream option";
like $help, qr/\nDownstream options \(after the URL or closing ---\):\n\s+--eager\b.*\n\s+--bearer TOKEN\b/s,
"multibroker --eager and --bearer are explicitly downstream options";
unlike $help, qr/Downstream options[^\n]*\n\s+--ask MODE\b/,
"multibroker --ask is not mislabeled as a downstream option";
}
}
my $tool_probe = q{
mcp_tool "sample" => "Explain this tool.", {
type => "object",
properties => {
path => { type => "string", description => "Selected path" },
choice => { type => "string", enum => ["a", "b"], default => "a" },
ids => { type => "array", items => { type => "integer" } },
target => { anyOf => [{ type => "integer" }, { type => "string" }] },
},
required => ["path", "target"],
}, sub {};
my $opts = mcp_getoptions;
mcp_start %$opts;
};
($status, $out, $err) = command ($tool_probe, "--tool-help");
is $status, 0, "tool-help exits without starting server";
like $out, qr/\Asample\n Explain this tool\./,
"tool-help reads actual registered description";
like $out, qr/path string required\n Selected path/,
"tool-help prints required argument and its description";
like $out, qr/choice string optional \(default: "a"; values: a, b\)/,
"tool-help prints defaults and allowed values";
like $out, qr/ids array\[integer\] optional/,
"tool-help formats array element types";
like $out, qr/target integer\|string required/,
"tool-help prints union types";
is $err, "", "tool-help does not start a listener or produce diagnostics";
my %tool_name = (
"mcp-fs" => "workdirs", "mcp-vim" => "targets",
"mcp-webbrowser" => "tabs", "mcp-ask-user" => "ask-user",
"mcp-multibroker" => "discover-brokers",
);
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 = {
method => "tools/call", tool => "file-patch",
args => { path => "lib/Foo.pm" },
on_reply => sub {},
};
mcp_log_request (undef, $req);
mcp_log_request (undef, $req); # permission retry
$req->{on_reply}->($req, {
isError => 1, content => [{ text => "hunk failed\nadditional detail" }],
});
mcp_log_request (undef, {
method => "tools/call", tool => "path-op",
args => {workdir => 4, path => "foo", unlink => JSON::XS::true,
rmdir => JSON::XS::false, mkpath => "0700", symlink => "x" x 200, chmod => "0600", rename => "bar"},
on_reply => sub {},
});
mcp_log_request (undef, {
method => "tools/call", tool => "ex",
args => { target => "editor", command => "echo 1\n" . ("x" x 300) },
on_reply => sub {},
});
mcp_log_request (undef, {
method => "tools/call", tool => "exec",
args => {workdir => 1, argv => ["perl", "-e", "print qq(hello\nworld)", "x" x 140, "ignored"]},
on_reply => sub {},
});
mcp_log_request (undef, {
method => "tools/call", tool => "vcs-status",
args => {workdir => 1, cwd => "src", backend => "cvs",
files => ["Changes", "space name", "two\nlines", "x" x 140, "omitted"]},
on_reply => sub {},
});
mcp_log_request (undef, {
method => "tools/call", tool => "vcs-diff",
args => {workdir => 1, backend => "git", files => []},
on_reply => sub {},
});
mcp_log_request (undef, {
method => "tools/call", tool => "vcs-log",
args => {workdir => 2, backend => "hg", files => ['quote"name']},
on_reply => sub {},
});
mcp_log_request (undef, {
method => "tools/call", tool => "grep",
args => {workdir => 1, path => "t", pattern => "foo\n" . ("y" x 200)},
on_reply => sub {},
});
mcp_log_request (undef, {
method => "tools/call", tool => "request",
args => {},
on_reply => sub {},
t/c15_getoptions.t view on Meta::CPAN
unlike $err, qr/: GET 404 /, "ordinary not-found requests are silent at warn level";
like $err, qr/MCP HTTP remote=192\.0\.2\.1:1234: POST 401 uri="\/mcp\/"\n/,
"rejected bearer token logs the public MCP path, not the Authorization header";
like $err, qr/MCP HTTP remote=192\.0\.2\.1:1234: POST 400 uri="\/<token>\/mcp\/"\n/,
"invalid JSON request redacts its valid URL token";
like $err, qr/MCP HTTP remote=192\.0\.2\.1:1234: - 400\n/,
"malformed HTTP request logged without method";
is scalar (() = $err =~ /MCP HTTP remote=/g), 3, "only non-404 HTTP errors appear at warn level";
unlike $err, qr/real-token|wrong-token|guess-token|not-for-logs|\/health/,
"HTTP warning log omits credentials, URL token guesses, query parameters and successful routes";
{
local $ENV{PERL_ANYEVENT_LOG} = "filter=trace";
($status, $out, $err) = command ($http_probe);
}
is $status, 0, "trace HTTP rejection log probe exits cleanly";
like $err, qr/MCP HTTP remote=192\.0\.2\.1:1234: GET 404 uri="\/<token>\/mcp\/"\n/,
"unrecognized URL token is redacted while endpoint path remains visible";
like $err, qr/: GET 404 uri="\/robots\.txt"\n/,
"unrelated request path remains visible without its query parameters";
like $err, qr/: GET 404 uri="\/<token>\/not-mcp\/"\n/,
"configured token is redacted even on the wrong endpoint";
like $err, qr/: GET 404 uri="\[non-path URI\]"\n/,
"absolute-form HTTP target is not logged as a potentially credential-bearing URL";
like $err, qr/: GET 404 uri="\/"\n/,
"GET / is logged at trace like other missing paths";
is scalar (() = $err =~ /MCP HTTP remote=/g), 9, "trace includes all failed requests but not successful responses";
is scalar (() = $err =~ /: GET 404 uri="\/"\n/g), 2,
"GET / is quiet even when / is the actual MCP POST endpoint";
unlike $err, qr/real-token|wrong-token|guess-token|not-for-logs|\/health/,
"HTTP log omits credentials, URL token guesses, query parameters and successful routes";
my $http_for_logs = AnyEvent::MCP::Server::HTTP->new (tokens => ["real-token"]);
is $http_for_logs->_log_uri ("/guess-token/mcp"), '"/<token>/mcp"',
"missing final endpoint slash does not expose an unrecognized URL token";
my $root_auth = AnyEvent::MCP::Server::HTTP->new (path => "/", tokens => ["real-token"]);
is $root_auth->_log_uri ("/real-token"), '"/<token>"',
"actual token-only endpoint hides configured URL credential";
is $root_auth->_log_uri ("/robots.txt"), '"/robots.txt"',
"token-only endpoint still reports unrelated probe paths";
is $root_auth->_log_uri ("/guess-token"), '"/guess-token"',
"unknown single path is not blindly classified as a token";
my $long_path = "/" . ("x" x 200);
is $http_for_logs->_log_uri ($long_path), '"' . substr ($long_path, 0, 160) . '..."',
"HTTP warning path is bounded before logging";
($status, $out, $err) = command ($log_probe, "--quiet");
is $status, 0, "--quiet exits normally";
unlike $err, qr/file-patch|path-op|ex target=/, "--quiet suppresses activity and tool errors";
like $err, qr/error main: diagnostic failure/, "--quiet leaves normal diagnostics alone";
{
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;
( run in 1.429 second using v1.01-cache-2.11-cpan-60884a8df76 )