AnyEvent-MCP

 view release on metacpan or  search on metacpan

t/c15_getoptions.t  view on Meta::CPAN

use common::sense;
use Test::More;
use File::Temp ();
use IPC::Open3 ();
use Symbol ();
use Getopt::Long ();
use AnyEvent::MCP::Config ();
use AnyEvent::MCP::Server::Simple;
use AnyEvent::MCP::Server::HTTP ();

Getopt::Long::Configure ("require_order");
my $have_websocket = eval {
   require AnyEvent::WebSocket::Server;
   require AnyEvent::WebSocket::Message;
   1
};

{
   local @ARGV = ("--name", "demo", "--bind", ":31740", "--token", "first",
      "--token", "second", "--stdio", "--custom", "yes", "positional");
   my $custom;
   my $options = mcp_getoptions ({ usage => "usage example\n" }, "custom=s" => \$custom);
   is $options->{name}, "demo", "shared name";
   is $options->{bind}, ":31740", "shared bind";
   is_deeply $options->{tokens}, ["first", "second"], "repeatable ordered tokens";
   ok $options->{stdio}, "shared stdio";
   is $custom, "yes", "Getopt::Long application option";
   is_deeply \@ARGV, ["positional"], "require_order leaves positional arguments";
}

{
   local @ARGV = ("--tls-cert", "certificate.pem", "--tls-key", "private.pem");
   my $options = mcp_getoptions;
   is $options->{tls_cert}, "certificate.pem", "shared TLS certificate option";
   is $options->{tls_key}, "private.pem", "shared TLS key option";
}

{
   local @ARGV = ("--name", "memory", "--custom-instructions", "Use for lasting memories.");
   my $options = mcp_getoptions;
   is $options->{custom_instructions}, "Use for lasting memories.",
      "common custom-instructions option returns instance purpose";
}

{
   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 $!;
($status, $out, $err) = command ('mcp_getoptions;', "--name", "named",
   "--bind", ":31740", "--token", "static", "--print-url");
is $status, 0, "named endpoint URL discovery succeeds";
is $out, "http://127.0.0.1:31740/static/named/\n",
   "shared print-url retains named server path";
($status, $out, $err) = command ('mcp_getoptions;', "--name", "mail\@doom.example+test",
   "--bind", ":31740", "--token", "static", "--print-url");
is $status, 0, "email-like name accepted by shared option parser";
is $out, "http://127.0.0.1:31740/static/mailbox/\n",
   "email-like name selects its configured path";

($status, $out, $err) = command ('mcp_getoptions;', "--name", "named",
   "--set", "path=/overridden/", "--bind", ":31740",
   "--token", "static", "--print-url");
is $status, 0, "--set overrides instance configuration for URL discovery";
is $out, "http://127.0.0.1:31740/static/overridden/\n",
   "shared configuration override affects the effective endpoint path";

my $set_probe = 'mcp_getoptions; my $c = AnyEvent::MCP::Config::global_config (); '
   . 'print join "\\n", map { $c->{section}{"instance named"}{$_} } '
   . 'qw(path executable.perl prepend-path), "\\n";';
($status, $out, $err) = command ($set_probe, "--name", "named",
   "--set", "path=/first/", "-s", "path=/last/",
   "-s", "executable.perl=/special/perl=debug", "--set", "prepend-path=");
is $status, 0, "repeated -s/--set accepts trusted instance keys";
is $out, "/last/\n/special/perl=debug\n\n",
   "last assignment wins; values retain equals signs and may be empty";

($status, $out) = command ('mcp_getoptions;', "--name", "named",
   "--bind", ":31740", "--token", "static", "--print-url");
is $out, "http://127.0.0.1:31740/static/named/\n",
   "process-local --set changes are not written back to global.ini";

($status, $out, $err) = command ('mcp_getoptions;', "--set", "invalid");
ok $status && $err =~ /Invalid --set KEY=VALUE/,
   "--set rejects a missing equals sign";
($status, $out, $err) = command ('mcp_getoptions;', "-s", "invalid key=value");
ok $status && $err =~ /Invalid --set KEY=VALUE/,
   "-s rejects whitespace in configuration keys";

open $fh, ">>", "$dir/anyevent-mcp/global.ini" or die $!;
print {$fh} "\n[instance secured]\ntls_cert = cert.pem\n";
close $fh or die $!;
($status, $out, $err) = command ('mcp_getoptions;', "--name", "secured",
   "--bind", ":31740", "--token", "static", "--print-url");
is $status, 0, "named TLS URL discovery succeeds";
is $out, "https://127.0.0.1:31740/static/\nhttp://127.0.0.1:31740/static/\n",
   "named TLS certificate selects dual URLs";
is $err, "", "named TLS URL discovery has no diagnostics";

open $fh, ">>", "$dir/anyevent-mcp/global.ini" or die $!;
print {$fh} "\n[program perl]\ncustom_instructions = Program purpose\n"
   . "[instance named]\ncustom_instructions = Instance purpose\n";
close $fh or die $!;

my $probe = 'mcp_config instructions => "Operating rules", short_instructions => "Discover tools"; '
   . 'my $options = mcp_getoptions; '
   . 'mcp_start %$options, auth => "none", port => 0, on_start => sub { '
   . 'print $_[0]{instructions}, "\\n"; $_[0]->close };';
($status, $out, $err) = command ($probe, "--name", "other");
is $status, 0, "program-level custom instructions start";
my $hint = "\n\nFull instructions: meta-instructions tool description.\n";
is $out, "Program purpose\n\nDiscover tools$hint", "program-level purpose advertised";
($status, $out, $err) = command ($probe, "--name", "named");
is $status, 0, "instance-level custom instructions start";
is $out, "Instance purpose\n\nDiscover tools$hint", "instance setting overrides program setting";
($status, $out, $err) = command ($probe, "--name", "named", "--custom-instructions", "CLI purpose");
is $status, 0, "CLI custom instructions start";
is $out, "CLI purpose\n\nDiscover tools$hint", "CLI purpose overrides instance setting";

for my $bad (
   {},
   { tokens => [] },
   { tokens => ["good", "bad/token"] },
   { auth => "unknown" },
   { auth => "none", tokens => ["x"] },
) {

t/c15_getoptions.t  view on Meta::CPAN

   });
   mcp_log_request (undef, {
      method => "tools/call", tool => "request",
      args => {},
      on_reply => sub {},
   }, method => "GET", url => "https://example.org/page");
   AE::log error => "diagnostic failure";
};
($status, $out, $err) = command ($log_probe, "--name", "example");
is $status, 0, "activity log probe exits cleanly";
like $err, qr/\A\d\d \d\d:\d\d:\d\d\.\d\d [^\s]+\/example\[\d+\] file-patch path=lib\/Foo\.pm\n/,
   "default activity log has short process-wide timestamp and process identity";
is scalar (() = $err =~ /file-patch path=lib\/Foo\.pm/g), 1,
   "a permission retry does not duplicate activity logging";
like $err, qr/file-patch failed: hunk failed\n/,
   "asynchronous-style tool error replies are logged without their long details";
like $err, qr/path-op workdir=4 path=foo unlink mkpath=0700 symlink=x{80} chmod=0600 rename=bar\n/,
   "path-op logs operations in execution order, omitting false flags and truncating long operands";
like $err, qr/ex target=editor command="echo 1\\nx{193}"\.\.\.\n/,
   "Ex log preview preserves escaped newlines and limits command text to 200 characters";
like $err, qr/exec workdir=1 argv="perl" "-e" "print qq\(hello\\nworld\)" "x{80}"\.\.\. \.\.\.\n/,
   "exec logs several JSON-quoted arguments, caps long ones and marks omitted arguments";
like $err, qr/vcs-status workdir=1 cwd=src backend=cvs files="Changes" "space name" "two\\nlines" "x{80}"\.\.\. \.\.\.\n/,
   "VCS status logs JSON-quoted filenames, caps long names and marks omitted files";
like $err, qr/vcs-diff workdir=1 backend=git\n/,
   "VCS diff logs backend and omits an empty filename list";
like $err, qr/vcs-log workdir=2 backend=hg files="quote\\\"name"\n/,
   "VCS log quotes special characters in filenames";
like $err, qr/grep workdir=1 path=t pattern="foo\\ny{156}"\.\.\.\n/,
   "grep logs the bounded search pattern with escaped newlines";
like $err, qr/request method=GET url=https:\/\/example.org\/page\n/,
   "applications can add sanitized context to the shared request logger";
like $err, qr/\d\d \d\d:\d\d:\d\d\.\d\d [^\s]+\/example\[\d+\] error main: diagnostic failure\n/,
   "ordinary diagnostics use the same process-wide formatter";

my $error_probe = q{
   mcp_http auth => "none", port => 0, on_start => sub {
      my ($server) = @_;
      $server->event (connection_error => bless ({
         mcp_remote => "127.0.0.1:12345",
         mcp_peer => { client_info => { name => "two\nlines" } },
      }, "AnyEvent::Handle"), "Broken pipe");
      $server->event (connection_error => bless ({
         mcp_peer => {},
      }, "AnyEvent::Handle"), "Broken pipe");
      $server->close;
   };
};
{
   local $ENV{PERL_ANYEVENT_LOG} = "filter=debug";
   ($status, $out, $err) = command ($error_probe);
}
is $status, 0, "connection error log probe exits cleanly";
unlike $err, qr/MCP connection/, "connection errors are silent at debug level";
{
   local $ENV{PERL_ANYEVENT_LOG} = "filter=trace";
   ($status, $out, $err) = command ($error_probe);
}
is $status, 0, "trace connection error log probe exits cleanly";
like $err, qr/MCP connection id=[a-f0-9]+ remote=127\.0\.0\.1:12345 client="two\\nlines": Broken pipe\n/,
   "trace connection errors identify the remote endpoint and escaped client name";
like $err, qr/MCP connection id=[a-f0-9]+: Broken pipe\n/,
   "unidentified connections still receive a connection id";

my $http_probe = q{
   use AnyEvent;
   use AnyEvent::Handle;
   use AnyEvent::MCP::Server::HTTP;
   use Socket qw(AF_UNIX SOCK_STREAM PF_UNSPEC);

   my $server = AnyEvent::MCP::Server::HTTP->new (
      tokens => ["real-token"],
      on_http_request => sub {
         my ($server, $req, $reply) = @_;
         return 0 unless $req->{uri} eq "/health";
         $reply->(200, "OK", {}, "ok");
         1
      },
   );
   my $timeout = AE::timer 5, 0, sub { die "HTTP probe timed out\n" };

   for my $request (
      "GET / HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "GET /guess-token/mcp/ HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "GET /robots.txt?password=not-for-logs HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "GET /real-token/not-mcp/ HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "GET http://example.org/mcp/ HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "POST /mcp/ HTTP/1.1\r\nContent-Length: 0\r\nAuthorization: Bearer wrong-token\r\n\r\n",
      "POST /real-token/mcp/ HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: 1\r\n\r\n!",
      "GET /health HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "malformed\r\n\r\n",
   ) {
      socketpair my $a, my $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
      my $handle = $server->accept ($a);
      $handle->{mcp_remote} = "192.0.2.1:1234";
      my $client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
      my $done = AE::cv;

      $client->push_write ($request);
      $client->push_read (line => "\r\n\r\n", sub {
         my ($handle, $header) = @_;
         die "GET / must return 404\n"
            if $request =~ m{\AGET / HTTP/} && $header !~ m{\AHTTP/1\.1 404 };
         my ($length) = $header =~ /Content-Length: ([0-9]+)/i;
         defined $length or die "HTTP response missing content length\n";
         $handle->push_read (chunk => $length, sub { $done->send });
      });

      $done->recv;
      $client->destroy;
   }

   $server->close;

   # / is a legitimate MCP POST endpoint; a casual GET must still be 404.
   $server = AnyEvent::MCP::Server::HTTP->new (
      path => "/", tokens => ["real-token"],
   );
   my $body = '{"jsonrpc":"2.0","id":1,"method":"ping","params":{}}';
   for my $request (
      "GET / HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "POST / HTTP/1.1\r\nContent-Type: application/json\r\n"
         . "Authorization: Bearer real-token\r\nContent-Length: " . length ($body) . "\r\n\r\n$body",
   ) {
      socketpair my $a, my $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
      my $handle = $server->accept ($a);
      $handle->{mcp_remote} = "192.0.2.1:1234";
      my $client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
      my $done = AE::cv;
      $client->push_write ($request);
      $client->push_read (line => "\r\n\r\n", sub {
         my ($handle, $header) = @_;
         my $expected = $request =~ /\AGET/ ? 404 : 200;
         die "Root endpoint: expected $expected\n" unless $header =~ /\AHTTP\/1\.1 $expected /;
         my ($length) = $header =~ /Content-Length: ([0-9]+)/i;
         defined $length or die "HTTP response missing content length\n";
         $handle->push_read (chunk => $length, sub { $done->send });
      });
      $done->recv;
      $client->destroy;
   }
   $server->close;
};
{
   local $ENV{PERL_ANYEVENT_LOG} = "filter=warn";
   ($status, $out, $err) = command ($http_probe);
}
is $status, 0, "HTTP rejection log probe exits cleanly";
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.967 second using v1.01-cache-2.11-cpan-1bcd28dbaf1 )