AnyEvent-MCP

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

	  global_config() is the initialized cached singleton, while new
	  has no file side effects and load/ensure_secret are explicit.
	  Make anyevent-mcp init idempotent and fail on secret persistence errors.
	- send 30-second elapsed-time progress for outstanding tool calls,
	  forward downstream progress through mcp-multibroker, and stream
	  request-scoped notifications over modern HTTP POST/SSE before the
	  final result, retaining plain JSON for calls without notifications.
	- make mcp-imap messages.more indicate any remaining search work,
	  including sparse UID ranges; document next_cursor as authoritative
	  and recommend threads for targeted whole-mailbox lookups.
	- eliminate the last utf8::is_utf8-based encoding decision in OAuth2:
	  form values are Unicode text encoded to UTF-8 before percent escaping;
	  decode redirect and persisted refresh-token bytes explicitly.
	- centralize UTF-8 configuration file I/O in file_load/file_save:
	  files contain UTF-8 bytes, parse_ini handles Unicode text, and all
	  config, rules and IMAP callers share the same conversion boundary.
	  Keep the atomic byte-oriented file_replace for JSON and raw streams;
	  preserve raw passwords and Base64/hex-encoded binary secrets.
	- load Encode::MIME::Header explicitly in the mcp-imap worker; only
	  mcp-imap requires it, not other AnyEvent::MCP components.
	- decode RFC 2047 encoded subject and address display fields in

bin/anyevent-mcp  view on Meta::CPAN

   usage;
   exit 0;
}

my $command = shift @ARGV;
unless (defined $command) {
   usage;
   exit 2;
}

@ARGV = map AnyEvent::MCP::utf8dec $_, @ARGV;

eval {
   if ($command =~ /\A(?:manage-rules|edit-rules)(?:-file)?\z/ && @ARGV == 1) {
      my $path = $ARGV[0];
      if ($command !~ /-file\z/) {
         $path =~ /\A[A-Za-z0-9][A-Za-z0-9_.-]*\z/
            or die "Invalid permission rule profile name\n";
         my $config_home = $ENV{XDG_CONFIG_HOME} || ($ENV{HOME} || die "HOME is not set\n") . "/.config";
         $config_home =~ m{\A/} or die "XDG_CONFIG_HOME must be an absolute path\n";
         $path = "$config_home/anyevent-mcp/rules/$path.ini";
      }
      my $action = $command =~ /\Amanage-/ ? "--manage-rules" : "--edit-rules";
      exec "anyevent-mcp-askpermission", $action, AnyEvent::MCP::utf8enc $path;
      die "Cannot start permission rule tool: $!\n";
   } elsif ($command eq "init" && !@ARGV) {
      my $config = AnyEvent::MCP::Config::global_config (defined $file ? (file => $file) : ());
      print "Initialized $config->{file}\n";
   } elsif ($command =~ /\A(?:create-user|revoke-user)\z/ && @ARGV == 1) {
      !defined $program || !defined $instance or die "--program and --instance are exclusive\n";
      my $user = AnyEvent::MCP::Config::user_name ($ARGV[0]);
      my $scope = defined $program ? "program " . AnyEvent::MCP::instance_name ($program)
                : defined $instance ? "instance " . AnyEvent::MCP::instance_name ($instance)
                : "global";

bin/anyevent-mcp-askpermission  view on Meta::CPAN

      waitpid $yad_pid, 0;
   }
   exit 1;
};

sub yad {
   my $pid = open my $fh, "-|";
   return unless defined $pid;
   if (!$pid) {
      open STDERR, ">", "/dev/null" or exit 127;
      exec "yad", "--no-markup", map AnyEvent::MCP::utf8enc $_, @_;
      exit 127;
   }
   $yad_pid = $pid;
   local $/;
   my $output = <$fh>;
   close $fh;
   my $status = $?;
   undef $yad_pid;

   # our buttons never use 1: GTK display failure is not user cancellation.
   return if $status == 1 << 8 || $status == 127 << 8 || $status & 127;
   ($status >> 8, AnyEvent::MCP::utf8dec $output)
}

sub manage_rules {
   my ($file) = @_;

   my $permissions = AnyEvent::MCP::Server::Permissions->new;
   $permissions->{file} = $file;

   while (1) {
      my $rules = $permissions->rules;

bin/anyevent-mcp-askpermission  view on Meta::CPAN


   my $permissions = AnyEvent::MCP::Server::Permissions->new;
   $permissions->{file} = $file;
   my $lock = $permissions->_lock; # ensure the file exists and is private.
   close $lock or die "Cannot unlock permission rules: $!\n";

   for my $choice (grep { defined && /\S/ } @ENV{qw(VISUAL EDITOR)}, "sensible-editor", "vi") {
      my @editor = Text::ParseWords::shellwords ($choice);
      next unless @editor;

      my $status = system { $editor[0] } @editor, AnyEvent::MCP::utf8enc ($file);
      next if $status == -1;

      $status == 0
         or die "Editor failed or was interrupted (status $status)\n";

      return
   }

   die "No editor found (VISUAL, EDITOR, sensible-editor, vi)\n"
}
if (defined $rules_file) {
   eval { manage_rules AnyEvent::MCP::utf8dec $rules_file; 1 } or do {
      print STDERR $@;
      exit 1;
   };
   exit;
}

if (defined $edit_file) {
   eval { edit_rules AnyEvent::MCP::utf8dec $edit_file; 1 } or do {
      print STDERR $@;
      exit 1;
   };
   exit;
}

my $request = do { local $/; JSON::XS::decode_json (scalar <STDIN>) };
$request->{version} == 1
   or die "Invalid permission request\n";

bin/anyevent-mcp-askpermission  view on Meta::CPAN

sub detail_fields {
   my @fields;

   for my $label (sort keys %{$request->{details} || {}}) {
      my $text = $request->{details}{$label};
      defined $text && !ref $text
         or die "Invalid permission detail\n";

      my $preview = AnyEvent::MCP::Permissions::Ask::detail_text $label, $text;
      my $chars = length $text;
      my $bytes = length AnyEvent::MCP::utf8enc $text;

      my ($fh, $filename) = File::Temp::tempfile (
         "mcp-permission-XXXXXXXX", TMPDIR => 1, UNLINK => 1);
      binmode $fh;
      print {$fh} AnyEvent::MCP::utf8enc ($preview)
         or die "Cannot write permission detail: $!\n";
      close $fh or die "Cannot close permission detail: $!\n";

      $label = display_text $label;
      $label =~ s/[:\t\n]/sprintf "\\u{%X}", ord $&/ge;
      my $info = "$label: $chars characters, $bytes UTF-8 bytes"
         . ($chars > 65536 ? " (incomplete preview)" : "");
      $info =~ s/\\/\\\\/g;
      my $button = $label;
      $button =~ s/\\/\\\\/g;

bin/anyevent-mcp-form-elicitation  view on Meta::CPAN

      waitpid $yad_pid, 0;
   }
   exit 1;
};

sub yad {
   my $pid = open my $fh, "-|";
   return unless defined $pid;
   if (!$pid) {
      open STDERR, ">", "/dev/null" or exit 127;
      exec "yad", "--no-markup", map AnyEvent::MCP::utf8enc $_, @_;
      exit 127;
   }
   $yad_pid = $pid;
   local $/;
   my $output = <$fh>;
   close $fh;
   my $status = $?;
   undef $yad_pid;
   return if $status == 1 << 8 || $status == 127 << 8 || $status & 127;
   ($status >> 8, AnyEvent::MCP::utf8dec $output)
}

my $fields = fields $params;
for my $field (@$fields) {
   $field->{choices} = [
      { label => "No", value => JSON::XS::false },
      { label => "Yes", value => JSON::XS::true },
   ] if $field->{type} eq "boolean";
}

bin/mcp-fs  view on Meta::CPAN

my $config_file = AnyEvent::MCP::Config::_file ();
my $config = -e $config_file ? AnyEvent::MCP::Config::global_config () : undef;
my %settings = $config ? (
   %{ $config->{section}{"program $program_name"} },
   %{ $config->{section}{"instance $name"} },
) : ();

# executable names from the UTF-8 config are text; process argv needs bytes.
my %executable = map {
   (my $name = $_) =~ s/\Aexecutable\.//;
   ($name => AnyEvent::MCP::utf8enc $settings{$_})
} grep /\Aexecutable\./, keys %settings;

my $sandbox_path = "/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin";
(my $prepend = $settings{"prepend-path"} // "") =~ s/:+\z//;
$sandbox_path = "$prepend:$sandbox_path" if length $prepend;
$sandbox_path = AnyEvent::MCP::utf8enc $sandbox_path;

my @mount;
for my $key (sort grep /\Amount(?:-try)?\./, keys %settings) {
   my $value = $settings{$key};
   next unless length $value;
   my ($mode, $path) = $value =~ /\A(ro|rw):(\/.*)\z/
      or die "invalid $key mount '$value'\n";
   -e (AnyEvent::MCP::utf8enc $path) or die "invalid $key mount path '$path'\n"
      unless $remote || $key =~ /\Amount-try\./;
   push @mount, [$key, $mode, $path];
}

my @environment;
for my $key (sort grep /\Aenv\./, keys %settings) {
   my $value = $settings{$key};
   next unless length $value;
   my ($name, $text) = $value =~ /\A([A-Za-z_][A-Za-z_0-9]*)(?:=(.*))?\z/s
      or die "invalid $key environment entry '$value'\n";

bin/mcp-fs  view on Meta::CPAN

	sysread STDIN, $s, %1$d - length $s, length $s or die "read\n";
}
eval $s; die $@ if $@;
}, length $remote_launcher;
my $remote_command = "exec " . join " ", map shell_quote ($_),
   @exec_prefix, ($executable{perl} || "perl"), "-e", $remote_loader;

# all fields here are already octets, including encoded filenames and argv.
sub fs_remote_frame {
   my @arg = @_;
   utf8::downgrade $_ for @arg; # enforce octets, not an external encoding
   pack "N/a*", pack "(w/a*)*", @arg
}

my ($find, $grep, $patch, $perl, $sed);
my %vcs_program;

$bwrap //= $executable{bwrap} || "bwrap";

if ($sandbox_mode ne "none" && !$remote) {
   my $name = $bwrap;

bin/mcp-fs  view on Meta::CPAN

   /etc/nsswitch.conf
   /etc/hosts
   /etc/resolv.conf
);
@runtime_path = grep -e, @runtime_path unless $remote;

my (@workdir, @workdir_identity);
if (defined $exec_cmd) {
   @workdir = Cwd::abs_path ".";
   @workdir or die "cannot resolve current directory\n";
   utf8::decode $workdir[0] or die "workdir is not UTF-8\n";
   @workdir_identity = @workdir;
} else {
   for my $path (@ARGV) {
      my $workdir;
      if ($remote) {
         $path =~ m{\A/} or die "remote workdirs must be absolute paths\n";
         $workdir = $path;
      } else {
         $workdir = Cwd::abs_path $path;
         -d $workdir or die "invalid workdir '$path'\n";
      }
      utf8::decode $workdir or die "workdir is not UTF-8\n";
      my $identity = $path;
      utf8::decode $identity or die "workdir identity is not UTF-8\n";
      push @workdir, $workdir;
      push @workdir_identity, $identity;
   }
}

my $home = $ENV{HOME};
$home =~ m{\A/} and -d $home
   or die "HOME must name an absolute existing directory\n";
$home = Cwd::abs_path $home
   // die "cannot resolve HOME\n";
utf8::decode $home
   or die "HOME is not a valid UTF-8 path\n";

my $config_home;
unless (defined $exec_cmd) {
   $config_home = $ENV{XDG_CONFIG_HOME};
   if (length $config_home) {
      $config_home =~ m{\A/}
         or die "permission config directory must be absolute\n";
      utf8::decode $config_home
         or die "permission config directory is not UTF-8\n";
   } else {
      $config_home = "$home/.config";
   }
}

my (%remote_program, @remote_vcs_marker, $remote_umask);
my @tmp_realpath = map { Cwd::abs_path $_ || $_ } qw(/tmp /var/tmp);
if ($remote) {
   # probe once per startup; the local MCP frontend keeps the result.

bin/mcp-fs  view on Meta::CPAN


      print pack "N/a*", pack "(w/a*)*",
         $home, $bwrap, scalar umask, $>, @resolved, @markers,
         (map { -e $_ ? $_ : "" } @runtime), @program,
         (map { Cwd::abs_path $_ || $_ } qw(/tmp /var/tmp));
   };

   my @names = qw(perl find grep patch sed git svn cvs hg);
   my @args = (
      $sandbox_path, $sandbox_mode, $bwrap, scalar @workdir,
      (map { AnyEvent::MCP::utf8enc $_ } @workdir),
      scalar (grep $_->[0] =~ /\Amount\./, @mount), (map { AnyEvent::MCP::utf8enc $_->[2] } grep $_->[0] =~ /\Amount\./, @mount),
      scalar @runtime_path, @runtime_path,
      (map { ($_, $executable{$_} || $_, length $settings{"executable.$_"} ? 1 : 0) } @names),
   );
   my @command = ($executable{perl} || "perl", "-e", $probe, @args);
   my $pid = IPC::Open2::open2 (my $out, my $in, @rsh, $host, $remote_command);
   binmode $in;
   binmode $out;
   print {$in} $remote_launcher, fs_remote_frame ("", @command) or die "remote probe input: $!\n";
   close $in or die "remote probe input: $!\n";
   my $output = do { local $/; <$out> };

bin/mcp-fs  view on Meta::CPAN

   $remote_umask = shift @values;
   my $worker_uid = shift @values;
   $host_dac && $worker_uid != 0
      and die "--host-dac needs root privileges on the remote host\n";
   @workdir = splice @values, 0, @workdir;
   @remote_vcs_marker = map { [length $_ ? split /,/, $_ : ()] } splice @values, 0, @workdir;
   @runtime_path = grep length, splice @values, 0, @runtime_path;
   @remote_program{@names} = splice @values, 0, @names;
   @tmp_realpath = splice @values, 0, 2;
   for ($home, @workdir, @runtime_path, @tmp_realpath) {
      utf8::decode $_ or die "remote path is not UTF-8\n";
   }
   # remote executable names and the bwrap path are OS bytes, like local discovery.
}

$host_dac && !$bwrap and die "--host-dac requires bubblewrap\n";
my ($workdir_ids, $workdir_refresh);

unless (defined $exec_cmd) {
   # IDs represent logical pathnames, not physical symlink destinations.
   $workdir_ids = AnyEvent::MCP::Workdirs->new (

bin/mcp-fs  view on Meta::CPAN

my $umask = $remote ? $remote_umask : umask;

my $permissions;
$permissions = AnyEvent::MCP::Server::Permissions->new (
   sandbox_grants             => \%sandbox_grant,
   sandbox_grant_descriptions => sub {
      my ($request) = @_;

      my %description = %sandbox_grant_description;
      if (defined $request->{selected_workdir}) {
         my $name = JSON::XS->new->utf8 (0)->allow_nonref
            ->encode ($request->{selected_workdir});
         $description{"workdir-read"} = "Read files in selected workdir $name";
         $description{"workdir-write"} = "Change files in selected workdir $name";
      }
      \%description
   },
   sandbox_implementation => $bwrap ? "bubblewrap" : "NONE - UNSANDBOXED (full host-user privileges)",
   actions => {
      inspect => "Inspect resource metadata and enumerate names",
      read    => "Read resource contents",

bin/mcp-fs  view on Meta::CPAN

      unless (defined $exec_cmd) {
         $have->{$_} or die "unsandboxed execution needs $_ grant\n"
            for @unsandboxed_grants;
      }
      return ();
   }

   die "host-proc sandbox authority is unresolved and unavailable in v1\n"
      if $have->{"host-proc"};

   my $workdir_bytes = AnyEvent::MCP::utf8enc $workdir;
   my $home_bytes = AnyEvent::MCP::utf8enc $home;
   my $configured_root = grep $_->[2] eq "/", @mount;
   my $configured_root_write = grep $_->[2] eq "/" && $_->[1] eq "rw", @mount;
   my $root_read = $configured_root || $have->{"world-read"}
      || ($have->{"workdir-read"} && $workdir eq "/")
      || ($have->{"all-workdirs-read"} && grep $_ eq "/", @workdir);
   my $root_write = $configured_root_write || $have->{"world-write"}
      || ($have->{"workdir-write"} && $workdir eq "/")
      || ($have->{"all-workdirs-write"} && grep $_ eq "/", @workdir);
   $root_read ||= $root_write;

bin/mcp-fs  view on Meta::CPAN

      unless $root_read || (@exec_prefix && !$remote);
   push @command, "--ro-bind", "/etc/passwd", "/etc/passwd" if @exec_prefix && !$remote && !$root_read;
   push @command, $root_write ? "--bind-try" : "--ro-bind-try", "/", "/"
      if $root_read;

   my @scope_mount;

   unless ($root_read) {
      for my $path (@runtime_path) {
         my $mount = (fs_writable $workdir, $path, $have) ? "--bind-try" : "--ro-bind-try";
         my $bytes = AnyEvent::MCP::utf8enc $path;
         push @scope_mount, [$mount, $bytes, $bytes];
      }
   }

   if ($have->{"homedir-read"}
       and (!$root_read or ($have->{"homedir-write"} and !$root_write))) {
      my $mount = (fs_writable $workdir, $home, $have) ? "--bind-try" : "--ro-bind-try";
      push @scope_mount, [$mount, $home_bytes, $home_bytes];
   }

   if ($have->{"all-workdirs-read"}) {
      for my $path (@workdir) {
         next if $path eq "/";
         my $mount = ($have->{"all-workdirs-write"}
            or ($path eq $workdir && $have->{"workdir-write"}))
               ? "--bind" : "--ro-bind";
         my $bytes = AnyEvent::MCP::utf8enc $path;
         push @scope_mount, [$mount, $bytes, $bytes];
      }
   } elsif ($have->{"workdir-read"} && $workdir ne "/") {
      my $mount = $have->{"workdir-write"} ? "--bind" : "--ro-bind";
      push @scope_mount, [$mount, $workdir_bytes, $workdir_bytes];
   }

   # Host binds go parent-first so broader mounts cannot hide narrower grants.
   # Skip a nested read that is already covered by an equally strong mount.
   my @visible;

bin/mcp-fs  view on Meta::CPAN

   }

   # Configured mounts are explicit exceptions. Apply an ancestor of a
   # private mount first; the narrow exception itself may follow afterward.
   my @configured_after;
   unless ($have->{"world-write"}) {
      for my $entry (@mount) {
         my ($key, $mode, $path) = @$entry;
         next if $path eq "/";
         next if $mode eq "ro" && ($root_read || fs_writable $workdir, $path, $have);
         my $bytes = AnyEvent::MCP::utf8enc $path;
         my @bind = (($mode eq "rw" ? "--bind" : "--ro-bind")
            . ($key =~ /\Amount-try\./ ? "-try" : ""), $bytes, $bytes);
         if (grep { $_ ne $path && fs_inside $_, $path } qw(/sys /run /dev /proc /tmp /var/tmp)) {
            push @command, @bind;
         } else {
            push @configured_after, @bind;
         }
      }
   }

bin/mcp-fs  view on Meta::CPAN

      # Explicit access to the temporary directory itself takes precedence.
      next if (grep $_->[2] eq $tmp, @mount)
         || ($have->{"workdir-read"} && $workdir eq $tmp)
         || ($have->{"all-workdirs-read"} && grep $_ eq $tmp, @workdir);

      # If the host symlink is visible, bwrap must mount on its real target,
      # not the symlink. The remote probe supplies remote, not local, paths.
      my $visible = $root_read
         || (grep { fs_inside $tmp, $_->[2] } @visible)
         || (grep { fs_inside $tmp, $_->[2] } @mount);
      my $destination = $visible ? AnyEvent::MCP::utf8enc $tmp_realpath[$i] : $tmp;
      if ($have->{"shared-tmp"}) {
         push @command, "--bind-try", $tmp, $destination;
      } else {
         push @command, "--perms", "1777", "--tmpfs", $destination;
      }
   }

   # Narrow explicit exceptions are allowed to override the private baseline.
   push @command, @configured_after;

bin/mcp-fs  view on Meta::CPAN

      "--setenv", "PERL_BADLANG", "0",
      "--setenv", "HOME", $home_bytes;

   for my $name (qw(TERM COLORTERM TERMINFO TERMINFO_DIRS NO_COLOR CLICOLOR CLICOLOR_FORCE LINES COLUMNS)) {
      push @command, "--setenv", $name, $ENV{$name} if defined $ENV{$name};
   }

   for my $entry (@environment) {
      my ($name, $value) = @$entry;
      next if $name eq "SSH_AUTH_SOCK";
      $value = defined $value ? AnyEvent::MCP::utf8enc $value : $ENV{$name};
      push @command, "--setenv", $name, $value if defined $value;
   }
   push @command, "--setenv", "SSH_AUTH_SOCK", $agent_socket if defined $agent_socket;

   push @command,
      "--chdir", defined $exec_cmd ? $workdir_bytes : $have->{"workdir-read"} ? $workdir_bytes : "/tmp",
      "--";

   @command
}

# pass a private synthetic user entry to bubblewrap without a host passwd mount.
sub fs_passwd_fd {
   my ($read, $write) = AnyEvent::Util::portable_pipe
      or die "passwd pipe: $!\n";
   print {$write} "sandbox:x:$<:" . POSIX::getgid () . ":Sandbox:" . (AnyEvent::MCP::utf8enc $home) . ":/bin/sh\n"
      or die "passwd pipe: $!\n";
   close $write or die "passwd pipe: $!\n";

   if (fileno ($read) != 3) {
      POSIX::dup2 (fileno ($read), 3) == 3 or die "passwd dup2: $!\n";
      close $read;
      open $read, "<&=3" or die "passwd fd: $!\n";
   }

   defined fcntl ($read, F_SETFD, 0) or die "passwd fcntl: $!\n";

bin/mcp-fs  view on Meta::CPAN


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);
   }

   my ($parent, $child) = AnyEvent::Util::portable_socketpair
      or die "socketpair: $!\n";
   my ($error, $child_error) = AnyEvent::Util::portable_pipe
      or die "pipe: $!\n";

bin/mcp-fs  view on Meta::CPAN

            unless $req->{finished};
         return;
      }

      my (@response, $error);
      my $ok = eval {
         @response = unpack "(w/a*)*", $payload;
         my $status = shift @response;
         defined $status or die "missing perl response status\n";
         if ($status eq "-") {
            $error = AnyEvent::MCP::utf8dec $response[0];
         } elsif ($status ne "+") {
            die "invalid perl response status\n";
         }
         1
      };

      unless ($ok) {
         my $error = $@;
         AE::log warn => "sandbox perl worker: $error";
         proc_destroy $io;

bin/mcp-fs  view on Meta::CPAN

      $options{$name} =~ /\A[0-9]+\z/ && $options{$name} >= 1
         && $options{$name} <= $output_schema{$name}{maximum}
         or die "invalid $name\n";
   }

   if (exists $args->{grep}) {
      defined $args->{grep} && !ref $args->{grep} && $args->{grep} !~ /\0/
         && length $args->{grep} <= 65536
         or die "grep must be a string without NUL, at most 65536 characters\n";
      $grep or die "output filtering needs GNU grep\n";
      $options{grep} = AnyEvent::MCP::utf8enc $args->{grep};
   }

   \%options
}

# clipping a UTF-8 stream may leave at most three bytes of an incomplete character.
sub fs_output_text {
   my ($bytes, $cut) = @_;

   for (0 .. ($cut ? 3 : 0)) {
      my $text = $bytes;
      return $text if utf8::decode $text;
      chop $bytes;
   }

   die "command output is not UTF-8\n";
}

# preserve child status while bounding capture and, separately, returned output.
sub fs_command {
   my ($req, $workdir, $grants, $argv, $input, $timeout, $options, $cwd) = @_;

   # argv and input are octets; workdir and cwd are Unicode paths.
   my $workdir_bytes = AnyEvent::MCP::utf8enc $workdir;

   # check the actual directory inside the worker, after resolving symlinks.
   $argv = [$perl, "-MCwd", "-e", q{
      my $workdir = shift;
      chdir shift or die "VCS chdir: $!\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;

bin/mcp-fs  view on Meta::CPAN

               $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";

bin/mcp-fs  view on Meta::CPAN


   my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
      $args->{reason} // "$tool $path");

   if ($recurse) {
      AE::log debug => join " ", "fs", $tool, $path, (substr $args->{name}, 0, 40);
   } else {
      AE::log debug => "fs $tool $path";
   }

   my $find_path = AnyEvent::MCP::utf8enc $path;
   my @command = ((fs_sandbox $workdir, $granted), $find, $find_path);

   if ($recurse) {
      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 };

            if ($@) {
               $failure = "$tool returned a non-UTF-8 pathname\n";
               last;
            }

            if (++$seen > $limit) {
               $truncated = 1;
               last;
            }

bin/mcp-fs  view on Meta::CPAN

      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);

bin/mcp-fs  view on Meta::CPAN

      $length <= 1<<20
         or die "invalid read range\n";
      my $path = fs_path $workdir, $args->{path};

      my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
         $args->{reason} // "read $path");

      AE::log debug => join " ", "fs file-read", $path, $offset, $length;

      perl_eval $req, $workdir, $granted, $file_read,
         [AnyEvent::MCP::utf8enc $path, $offset, $length], 30, sub {
         my ($success, $result) = @_;

         return $req->error ($result)
            unless $success;

         @$result == 2
            or return $req->error ("invalid file-read response\n");
         my ($ok, $value) = @$result;
         if ($ok eq "1") {
            $req->reply (fs_result {
               data => MIME::Base64::encode_base64 ($value, ""),
            });
         } elsif ($ok eq "0") {
            $req->reply (fs_result {
               error => AnyEvent::MCP::utf8dec $value,
            });
         } else {
            $req->error ("invalid file-read status\n");
         }
      };
   }
;

$sed && mcp_tool read_lines =>
   "Read byte-LF (0x0A) lines by positive line ranges. "

bin/mcp-fs  view on Meta::CPAN

               if $truncated && !@content;
            return $req->reply ({ content => \@content });
         }

         my ($range, $start, $end) = @{shift @range};
         my @command = (
            (fs_sandbox $workdir, $granted),
            $sed, "-n",
            "-e", ($start == $end ? "${start}p" : "${start},${end}p"),
            "-e", "${end}Q", # Preserve unterminated final line (GNU sed).
            AnyEvent::MCP::utf8enc $path,
         );

         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}
                     : $encoding eq "base64" ? MIME::Base64::encode_base64 ($value->{stdout}, "")
                     : $value->{stdout}; # Unflagged byte strings are Latin-1 to Perl/JSON::XS.
               1
            };
            return $req->error ($@)
               unless $ok;

            push @result, [$range, $body];
            $remaining -= length $value->{stdout};
            if ($value->{truncated} or ($remaining <= 0 and @range)) {

bin/mcp-fs  view on Meta::CPAN

      length $data <= 1048576
         or die "write data exceeds 1 MiB\n";
      my $path = fs_path $workdir, $args->{path};

      my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "write",
         $args->{reason} // "write $path");

      AE::log debug => join " ", "fs file-write", $path, $offset, length ($data);

      perl_eval $req, $workdir, $granted, $file_write,
         [AnyEvent::MCP::utf8enc $path, $offset, $data], 30, sub {
         my ($success, $result) = @_;

         return $req->error ($result)
            unless $success;

         @$result == 2
            or return $req->error ("invalid file-write response\n");
         my ($ok, $value) = @$result;
         if ($ok eq "1") {
            $value =~ /\A[0-9]+\z/
               or return $req->error ("invalid file-write byte count\n");
            $req->reply (fs_result {
               bytes => 0 + $value,
            });
         } elsif ($ok eq "0") {
            $req->reply (fs_result {
               error => AnyEvent::MCP::utf8dec $value,
            });
         } else {
            $req->error ("invalid file-write status\n");
         }
      };
   }
;

my $path_op = q{#perl
   while (@ARGV) {

bin/mcp-fs  view on Meta::CPAN

      my $reason = join "\n",
         (defined $args->{reason} ? $args->{reason} : ()),
         "Path: " . $json->encode ($path), "Operations (in order):", map "  $_", @log;

      my $granted = fs_require_paths $req, $workdir, $identity,
         [$path, (defined $rename ? $rename : ())], "write", $reason;

      AE::log debug => join " ", "fs path-op", $path, @log;

      my @operation;
      my $raw_path = AnyEvent::MCP::utf8enc $path;

      push @operation, unlink => $raw_path
         if $args->{unlink};
      push @operation, rmdir => $raw_path
         if $args->{rmdir};
      push @operation, mkpath => $raw_path, $args->{mkpath}
         if exists $args->{mkpath};
      push @operation, mkdir => $raw_path, $args->{mkdir}
         if exists $args->{mkdir};
      push @operation, symlink => (AnyEvent::MCP::utf8enc $args->{symlink}), $raw_path
         if exists $args->{symlink};
      push @operation, truncate => $raw_path, $args->{truncate}
         if exists $args->{truncate};
      push @operation, chmod => $raw_path, $args->{chmod}
         if exists $args->{chmod};
      push @operation, rename => $raw_path, (AnyEvent::MCP::utf8enc $rename)
         if defined $rename;

      perl_eval $req, $workdir, $granted, $path_op,
         \@operation, 30, sub {
         my ($success, $result) = @_;

         return $req->error ($result)
            unless $success;

         @$result == 1 and $result->[0] eq "1"

bin/mcp-fs  view on Meta::CPAN

;

my $file_patch = q{#perl
   use Fcntl qw(O_RDWR O_CREAT O_EXCL);
   use Errno qw(EEXIST ENAMETOOLONG);

   my ($patch, $path, $diff, @max_offset) = @ARGV;

   my $create_tempfile = sub {
      my ($name) = @_;
      utf8::decode $name
         or return undef, "invalid UTF-8 tempfile name";

      my $slash = rindex $name, "/";
      my $dir = $slash < 0 ? "" : substr $name, 0, $slash + 1;
      my $file = substr $name, $slash + 1;

      for (;;) {
         my $pathname = "$dir$file";
         utf8::encode $pathname;

         if (sysopen my $fh, $pathname, O_RDWR | O_CREAT | O_EXCL, 0600) {
            binmode $fh;
            return $fh, $pathname
         }

         if ($! == EEXIST) {
            $file .= "~";
         } elsif ($! == ENAMETOOLONG) {
            substr $file, (length $file) * .75, 2, "~";

bin/mcp-fs  view on Meta::CPAN

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

      my ($workdir, $identity) = fs_workdir $args->{workdir};
      my $path = fs_path $workdir, $args->{path};
      my $diff = $args->{diff};
      my $detail = $diff;

      if ((index $diff, "@") >= 0) {
         $diff = AnyEvent::MCP::utf8enc $diff;
      } else {
         my $bytes = MIME::Base64::decode_base64 $diff;
         MIME::Base64::encode_base64 ($bytes, "") eq $diff
            or die "invalid base64 diff\n";
         $diff = $bytes;
         $detail = eval { AnyEvent::MCP::utf8dec $bytes };

         unless (defined $detail) {
            $detail = $bytes;
            $detail =~ s/([^\x09\x0a\x20-\x5b\x5d-\x7e])/sprintf "\\x{%02X}", ord $1/ge;
            $detail = "Raw patch: " . length ($bytes) . " bytes (escaped byte view)\n\n" . $detail;
         }
      }

      my $max_offset;
      ($diff, $max_offset) = AnyEvent::MCP::normalize_udiff $diff;
      length $diff <= 4<<20
         or die "patch exceeds 4 MiB\n";

      my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "write",
         $args->{reason} // "patch $path", { "View patch" => "File: $path\n\n$detail" });

      AE::log debug => join " ", "fs file-patch", $path, scalar (@$max_offset), "hunks", length ($diff), "bytes";

      perl_eval $req, $workdir, $granted, $file_patch,
         [$patch, AnyEvent::MCP::utf8enc $path, $diff, @$max_offset], 30, sub {
         my ($success, $result) = @_;

         return $req->error ($result)
            unless $success;

         @$result == 2
            or return $req->error ("invalid file-patch response\n");
         my ($ok, $value) = @$result;

         if ($ok eq "1") {
            $value =~ /\A[0-9]+\z/
               or return $req->error ("invalid file-patch byte count\n");
            $req->reply (fs_result {
               bytes => 0 + $value,
            });
         } elsif ($ok eq "0") {
            $req->reply (fs_result {
               error => AnyEvent::MCP::utf8dec $value,
            });
         } else {
            $req->error ("invalid file-patch status\n");
         }
      };
   }
;

$find && $grep && mcp_tool grep =>
   "Search regular files up to 1 MiB recursively; skip symlinks and .git. "

bin/mcp-fs  view on Meta::CPAN

      $mode eq "fixed" or $mode eq "pcre"
         or die "invalid grep mode\n";
      my $limit = $args->{limit} // 200;
      $limit <= 1000
         or die "invalid limit\n";
      my $granted = fs_require_paths ($req, $workdir, $identity, [$path], "read",
         $args->{reason} // "grep $path");

      AE::log debug => join " ", "fs grep", $path, $mode, (substr $args->{pattern}, 0, 40);

      my $find_path = AnyEvent::MCP::utf8enc $path;
      my $pattern = AnyEvent::MCP::utf8enc $args->{pattern};
      my @command = (
         (fs_sandbox $workdir, $granted),
         $find, $find_path,
         "-name", ".git", "-prune", "-o",
         "-type", "f",
         "-size", "-1048577c",
         "-exec",
         # GNU find treats any nonzero -exec ... + batch as failure.
         # grep uses 1 for no matches, which is a successful empty search;
         # preserve all other errors (including find traversal failures).

bin/mcp-fs  view on Meta::CPAN

      );

      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},

bin/mcp-fs  view on Meta::CPAN

      my @paths = map { fs_path $workdir, $_ } @{$args->{paths}};
      die "stat paths must be inside the selected workdir\n"
         if grep { !fs_inside ($_, $workdir) } @paths;

      my $granted = fs_require_paths $req, $workdir, $identity, \@paths, "read", $args->{reason};

      my @log = @paths;
      splice @log, 3, @log - 3, "..." if @log > 3;
      AE::log debug => join " ", "fs stat", @log;

      perl_eval $req, $workdir, $granted, $stat, [map { AnyEvent::MCP::utf8enc $_ } @paths],
         30, sub {
         my ($success, $result) = @_;

         return $req->error ($result)
            unless $success;

         @$result == @paths
            or return $req->error ("invalid stat response\n");

         my @result;

bin/mcp-fs  view on Meta::CPAN

                  type  => $type,
                  size  => 0 + $s[7],
                  mode  => (sprintf "%04o", $s[2] & 07777),
                  uid   => 0 + $s[4],
                  gid   => 0 + $s[5],
                  mtime => 0 + $s[9],
               };
            } else {
               push @result, +{
                  path  => $paths[$i],
                  error => AnyEvent::MCP::utf8dec $s[0],
               };
            }
         }

         $req->reply (fs_result { result => \@result });
      };
   }
;

mcp_tool exec =>

bin/mcp-fs  view on Meta::CPAN

      my $requested = $permissions->closure ($sandbox_grants);
      die "host-proc sandbox authority is unresolved and unavailable in v1\n"
         if $bwrap && $requested->{"host-proc"};

      my $stdin_text = $args->{stdin} // "";
      my $stdin_encoding = $args->{stdin_encoding} // "utf-8";
      $stdin_encoding =~ /\A(?:utf-8|latin1|base64)\z/
         or die "invalid stdin_encoding\n";
      my $input;
      if ($stdin_encoding eq "utf-8") {
         $input = AnyEvent::MCP::utf8enc $stdin_text;
      } elsif ($stdin_encoding eq "latin1") {
         $stdin_text !~ /[^\x00-\xff]/
            or die "latin1 stdin contains code points above U+00FF\n";
         $input = pack "C*", unpack "U*", $stdin_text;
      } else {
         $input = MIME::Base64::decode_base64 $stdin_text;
         MIME::Base64::encode_base64 ($input, "") eq $stdin_text
            or die "invalid base64 stdin\n";
      }
      length $input <= 4 * 1024 * 1024 or die "stdin exceeds 4 MiB\n";

bin/mcp-fs  view on Meta::CPAN

      });

      $timeout <= 300 || $permissions->closure ($granted)->{"long-running"}
         or die "permission reduced below long-running for exec\n";

      AE::log debug => "fs exec "
         . (substr $subject, 0, 200)
         . (length $subject > 200 ? "..." : "")
         . (length $input ? " stdin=" . length ($input) : "");

      fs_command $req, $workdir, $granted, [map { AnyEvent::MCP::utf8enc $_ } @{$args->{argv}}], $input, $timeout, $output;
   }
;

# 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. "

bin/mcp-fs  view on Meta::CPAN

         fs_inside $cwd, $workdir or die "VCS cwd must stay within the selected workdir\n";
         my $files = $args->{files} // [];
         ref $files eq "ARRAY" or die "files must be an array of filenames\n";
         my @files;
         my @paths = ($cwd);
         for my $file (@$files) {
            my $path = fs_path $cwd, $file;
            fs_inside $path, $workdir or die "VCS files must stay within the selected workdir\n";
            push @paths, $path;
            my $relative = File::Spec::Unix->abs2rel ($path, $cwd);
            push @files, (AnyEvent::MCP::utf8enc "./$relative");
         }

         my @argv = $backend eq "git"
            ? ($program, "--no-pager", "--no-optional-locks", "--literal-pathspecs", "-c", "core.fsmonitor=false",
               $operation, ($operation eq "diff" ? qw(--no-ext-diff --no-textconv --no-color --ignore-submodules)
                         : $operation eq "status" ? qw(--short --untracked-files=normal --ignore-submodules)
                                                  : qw(--no-decorate)),
               "--", @files)
            : $backend eq "svn"
            ? ($program, "--non-interactive", "--no-auth-cache", $operation,

bin/mcp-http  view on Meta::CPAN

#!/opt/bin/perl

=encoding utf8

=head1 NAME

mcp-http - HTTP requests with URL and method permissions

=head1 SYNOPSIS

   mcp-http --stdio
   mcp-http --connect http://host:port/TOKEN/http

bin/mcp-http  view on Meta::CPAN

      my $headers = $args->{headers} || {};
      for my $key (keys %$headers) {
         $key =~ /\A[A-Za-z0-9!#\$%&'*+.^_\x60|~-]+\z/
            && defined $headers->{$key} && !ref $headers->{$key}
            && $headers->{$key} !~ /[\r\n\x00]/
            or die "Invalid HTTP header\n";
      }
      $headers = { %$headers };
      $headers->{"User-Agent"} = "mcp-http/$AnyEvent::MCP::VERSION"
         unless grep lc $_ eq "user-agent", keys %$headers;
      my $data = exists $args->{body} ? (AnyEvent::MCP::utf8enc $args->{body}) : undef;
      if (defined $args->{body_base64}) {
         $args->{body_base64} =~ /\A(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?\z/
            or die "Invalid Base64 body\n";
         $data = MIME::Base64::decode_base64 ($args->{body_base64});
      }
      !defined $data || length $data <= 1048576 or die "Request body exceeds 1 MiB\n";
      my $limit = $args->{max_bytes} // 65536;
      $limit >= 1 && $limit <= 2097152 or die "Invalid max_bytes\n";

      !defined $args->{grep} || !ref $args->{grep} or die "Invalid grep\n";

bin/mcp-imap  view on Meta::CPAN

#!/opt/bin/perl

=encoding utf8

=head1 NAME

mcp-imap - inspect and manage one IMAP account through MCP

=head1 SYNOPSIS

   mcp-imap [OPTION]...
   mcp-imap [OPTION]... login [method password|oauth2] [server HOST]
       [user USER] [tls connect|starttls|none] [port PORT] [oauth-KEY VALUE]...

bin/mcp-imap  view on Meta::CPAN

   }
}

sub login {
   @ARGV % 2 == 0 or die "login expects key/value pairs\n";
   my %input;
   while (@ARGV) {
      my ($key, $value) = splice @ARGV, 0, 2;
      $key =~ /\A(?:method|server|user|tls|port|oauth-(?:client-id|client-secret|client-auth|authorization-endpoint|token-endpoint|scope|pkce|redirect-uri|sasl|auth-[A-Za-z0-9_]+))\z/
         or die "Unknown login key '$key' (passwords and tokens cannot be given on argv)\n";
      $value = AnyEvent::MCP::utf8dec $value;
      $value !~ /[\r\n\x00]/ or die "Invalid $key\n";
      $input{$key} = $value;
   }
   my $old = load_account ();
   my $method = $input{method} || $old->{method} || "password";
   $method =~ /\A(?:password|oauth2)\z/ or die "Unknown login method\n";

   my %kv = %$old;
   %kv = map +(exists $old->{$_} ? ($_ => $old->{$_}) : ()), qw(server user tls port)
      if ($old->{method} || "password") ne $method;
   %kv = (%kv, %input);
   delete $kv{port} if exists $input{tls} && !exists $input{port} && ($old->{tls} // "") ne $input{tls};
   $kv{method} = $method;
   delete $kv{"password-base64"} if $method eq "oauth2";
   delete @kv{grep /^oauth-/, keys %kv} if $method eq "password";

   for my $key (qw(server user)) {
      next if defined $kv{$key} && length $kv{$key};
      print STDERR "$key: ";
      chomp ($kv{$key} = <STDIN> // "");
      $kv{$key} = AnyEvent::MCP::utf8dec $kv{$key};
   }
   $kv{tls} ||= "connect";
   $kv{port} ||= $kv{tls} eq "connect" ? 993 : 143;

   my $account;
   if ($method eq "oauth2") {
      require AnyEvent::MCP::IMAP::OAuth2;
      AnyEvent::MCP::IMAP::OAuth2::validate (\%kv);
      my ($url, $state, $verifier) = AnyEvent::MCP::IMAP::OAuth2::authorize (\%kv);
      print STDERR "Authorize the mail account '$kv{user}', not a different account already signed into the browser.\n";

bin/mcp-imap  view on Meta::CPAN

      print STDERR "This is expected. Copy the FULL URL from the browser address bar and paste it here.\n";
      open my $tty, "+<", "/dev/tty"
         or die "OAuth callback requires a controlling terminal: $!\n";
      print {$tty} "Paste redirected URL: ";
      Term::ReadKey::ReadMode ("noecho", $tty);
      my $redirect = <$tty>;
      Term::ReadKey::ReadMode ("restore", $tty);
      print {$tty} "\n";
      close $tty;
      defined $redirect or die "No OAuth redirect URL supplied\n";
      $redirect = AnyEvent::MCP::utf8dec $redirect;
      $redirect =~ s/\r?\n\z//;
      my $tokens = AnyEvent::MCP::IMAP::OAuth2::finish (\%kv, $state, $verifier, $redirect);
      my $refresh = $tokens->{refresh_token}
         or die "OAuth provider returned no refresh token; configure offline access and try again\n";
      $kv{"oauth-refresh-token-base64"} = MIME::Base64::encode_base64 (AnyEvent::MCP::utf8enc $refresh, "");
      $account = settings (\%kv);
      $account->{access_token} = $tokens->{access_token};
   } else {
      open my $tty, "+<", "/dev/tty"
         or die "Password requires a controlling terminal: $!\n";
      print {$tty} "IMAP password for $kv{user}\@$kv{server}: ";
      Term::ReadKey::ReadMode ("noecho", $tty);
      my $password = <$tty>;
      Term::ReadKey::ReadMode ("restore", $tty);
      print {$tty} "\n";

bin/mcp-sctl  view on Meta::CPAN

#!/opt/bin/perl

=encoding utf8

=head1 NAME

mcp-sctl - ScriptCat and sctl Browser WebSocket bridge for MCP

=head1 SYNOPSIS

   mcp-sctl --stdio
   mcp-sctl
   mcp-sctl --bind 127.0.0.1:9000

bin/mcp-sctl  view on Meta::CPAN


my $name = $options->{name};
my $connect = $options->{connect};
my $stdio = $options->{stdio} || !defined $connect && $ENV{PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL} eq "stdio";
!($stdio && defined $connect) or die "Cannot combine --stdio and --connect\n";

my $config = AnyEvent::MCP::Config::global_config ();
my %http = $config->http_settings ($name, $options->{bind}, $options->{default_port});
$http{tokens} = $options->{tokens} if $options->{tokens};

my $json = JSON::XS->new->utf8->max_depth (64);
my $log_json = JSON::XS->new->allow_nonref;
my $keys_file = ($ENV{XDG_CONFIG_HOME} || "$ENV{HOME}/.config") . "/anyevent-mcp/sctl-$name-keys.json";
my $cache_file = ($ENV{XDG_CACHE_HOME} || "$ENV{HOME}/.cache") . "/anyevent-mcp/sctl-protocol.json";
my $keys = -f $keys_file ? $json->decode (AnyEvent::MCP::utf8enc (AnyEvent::MCP::file_load ($keys_file))) : {};
ref $keys eq "HASH" or die "Invalid sctl key registry\n";
my ($schema, $fetching, @search_waiters);
my (%connections, %online, $enrollment, $rpcid);
my $done = AE::cv;

# Authentication contexts from sctl protocol.json. They are transport
# constants; business method definitions are deliberately not compiled in.
my %context = (
   sessionExt             => "scriptcat-rpc-v1/ext",
   sessionDaemon          => "scriptcat-rpc-v1/daemon",

bin/mcp-sctl  view on Meta::CPAN

      if $method eq "scripts.source.get" && defined $result->{code} && !ref $result->{code};
   return "enabled=" . ($result->{enabled} ? "yes" : "no") if exists $result->{enabled};
   return "deleted" if $result->{deleted};
   "ok"
}

sub key_save {
   File::Path::mkpath (($keys_file =~ m{\A(.*)/[^/]+\z})[0], 0, 0700);
   my $lock = AnyEvent::MCP::file_lock ("$keys_file.lock");
   # A second process must not silently overwrite registrations.
   my $stored = -f $keys_file ? $json->decode (AnyEvent::MCP::utf8enc (AnyEvent::MCP::file_load ($keys_file))) : {};
   %$stored = (%$stored, %$keys);
   AnyEvent::MCP::file_replace ($keys_file, $json->encode ($stored));
   $keys = $stored;
}

sub send_message {
   my ($peer, $packet) = @_;
   $peer->{conn}->send (AnyEvent::WebSocket::Message->new (opcode => 1, body => $json->encode ($packet)));
}

bin/mcp-sctl  view on Meta::CPAN

      },
      sandbox_grants => [],
      reason => "Call $method on $peer->{name} ($id)\n\n"
         . (length $payload > 500 ? substr ($payload, 0, 500) . "..." : $payload),
   });
}

sub load_schema {
   return $schema if $schema;
   return unless -f $cache_file;
   my $raw = eval { AnyEvent::MCP::utf8enc (AnyEvent::MCP::file_load ($cache_file)) };
   return unless defined $raw;
   my $decoded = eval { $json->decode ($raw) };
   $schema = $decoded if ref $decoded eq "HASH" && ref $decoded->{methods} eq "HASH";
   $schema
}

sub refresh_schema {
   my ($cb) = @_;
   push @search_waiters, $cb if $cb;
   return if $fetching;

bin/mcp-vim  view on Meta::CPAN

$http{tokens} = \@tokens if @tokens;
$http{connect_tokens} = \@tokens if @tokens;
delete $http{token_users} if @tokens;
my @accepted_tokens = @{$http{tokens}};
my @connect_tokens = @{$http{connect_tokens}};
/\A[A-Za-z0-9_.~-]+\z/ or die "Invalid mcp-vim token\n" for @accepted_tokens;
my %connect_token = map { $_ => 1 } @connect_tokens;

$NICK //= (POSIX::uname)[1] || die "cannot determine mcp-vim hostname\n";

our $JSON_CODER = JSON::XS->new->utf8;

#############################################################################

my %xpcse;
my %vim;
my %target;

sub targets_changed {
   $_->send_json ([targets => keys %target]) for values %xpcse;
}

bin/mcp-vim  view on Meta::CPAN

      target      => $name,
      requested   => $requested,
      instance_id => $instance_id,
   }, $class;

   $vim{$self+0} = $self;

   AE::log debug => "new vim connection\n";

   # the line-based hello reader leaves subsequent bytes in the handle.
   $hdl->{json} = AnyEvent::MCP::json_class ()->new->utf8->max_depth (512);
   $hdl->rtimeout (0);

   {
      Scalar::Util::weaken (my $self = $self);

      $hdl->on_error (sub {
         $_[0]->destroy;
         $self->destroy;
      });
   }

bin/mcp-webbrowser  view on Meta::CPAN

#!/opt/bin/perl

=encoding utf8

=head1 NAME

mcp-webbrowser - expose opted-in browser tabs to MCP

=head1 SYNOPSIS

   mcp-webbrowser --stdio
   mcp-webbrowser --print-url
   mcp-webbrowser --stdio --bind 127.0.0.1:31741

bin/mcp-webbrowser  view on Meta::CPAN

my $connect = $options->{connect};
my $stdio = $options->{stdio} || !defined $connect && $ENV{PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL} eq "stdio";
!($stdio && defined $connect) or die "Cannot combine --stdio and --connect\n";

my $config = AnyEvent::MCP::Config::global_config ();
my %http = $config->http_settings ($name, $options->{bind});

$http{tokens} = $options->{tokens} if $options->{tokens};
$http{connect_tokens} = $options->{tokens} if $options->{tokens};
my %token = map { $_ => 1 } @{$http{connect_tokens}};
my $json = JSON::XS->new->utf8->max_depth (64);
my (%connections, %pages, %tabs);
my ($last_allowed, $marked);
my $done = AE::cv;

my $permissions = AnyEvent::MCP::Server::Permissions->new (
   name => "webbrowser-$name",
   actions => {
      read => "List connected browser tabs and their reported metadata",
      exec => "Execute JavaScript or tab operations in a connected browser page",
   },

bin/mcp-webbrowser  view on Meta::CPAN

   };
   my $ws = AnyEvent::WebSocket::Server->new (
      max_payload_size => 16 * 1024 * 1024,
      handshake => sub {
         my ($req, $res) = @_;
         my ($cookie, $target) = $req->{resource_name} =~ m{\A/([^/]+)/([^/?#]+)\z};
         defined $cookie or $reject->("invalid path");
         $token{$cookie} or $reject->("invalid token");
         $target =~ /%(?![0-9a-fA-F]{2})/ and $reject->("invalid target");
         $target =~ s/%([0-9a-fA-F]{2})/chr hex $1/ge;
         utf8::decode $target or $reject->("invalid target");
         length $target && $target !~ /\0/ or $reject->("invalid target");
         $requested = $target;

         $res
      },
   );
   $ws->establish ($fh)->cb (sub {
      my $conn = eval { $_[0]->recv };
      unless ($conn) {
         AE::log warn => $rejection

lib/AnyEvent/MCP.pm  view on Meta::CPAN


=head1 FUNCTIONS

=over

=item $class = AnyEvent::MCP::json_class

Returns C<JSON::XS> if available, otherwise C<JSON::PP>. The caller
configures a new coder instance as needed.

=item $bytes = AnyEvent::MCP::utf8enc $text

Return a UTF-8 byte string for C<$text>, leaving the argument unchanged.

=item $text = AnyEvent::MCP::utf8dec $bytes

Decode a UTF-8 byte string into characters, dying on invalid UTF-8.
The argument is left unchanged. For intentional in-place conversions,
use Perl's C<utf8::encode> or C<utf8::decode> directly.

=item $bytes = AnyEvent::MCP::random_bytes $length

Returns exactly C<$length> random bytes. Tries C</dev/urandom>, then an external
C<openssl rand> command. No additional random-number module is required.
Dies if neither source supplies the requested bytes successfully.
C<$length> must be a nonnegative integer; zero returns an empty string.

=back

lib/AnyEvent/MCP.pm  view on Meta::CPAN


use common::sense;

our $VERSION = 0.91;

sub json_class {
   our $JSON_CLASS ||= eval { require JSON::XS; "JSON::XS" }
                    || do { require JSON::PP; "JSON::PP" };
}

sub utf8enc($) {
   my $text = shift;

   utf8::encode $text;
   $text
}

sub utf8dec($) {
   my $bytes = shift;

   utf8::decode $bytes
      or die "invalid UTF-8\n";
   $bytes
}

sub instance_name {
   my ($name) = @_;

   $name = "default" unless defined $name;

   $name =~ /\A[A-Za-z0-9_][A-Za-z0-9_.@+-]*\z/

lib/AnyEvent/MCP.pm  view on Meta::CPAN


sub file_load {
   my ($file, $fh) = @_;
   my $close = !defined $fh;
   open $fh, "<:raw", $file or die "$file: $!\n" if $close;

   local $/;
   my $bytes = <$fh>;
   defined $bytes or die "$file: $!\n";
   close $fh or die "$file: $!\n" if $close;
   utf8dec $bytes
}

sub file_save {
   my ($file, $text) = @_;
   file_replace $file, utf8enc $text
}


sub random_bytes($) {
   my ($length) = @_;

   defined $length && $length =~ /\A[0-9]+\z/
      or die "Invalid random byte count\n";
   return "" unless $length;

lib/AnyEvent/MCP/Client/HTTP.pm  view on Meta::CPAN

   $headers{authorization} = "Bearer $self->{bearer}" if defined $self->{bearer};
   $headers{"mcp-protocol-version"} = $self->{protocol_version} if defined $self->{protocol_version};
   $headers{"mcp-session-id"} = $self->{session}
      if $self->{protocol_version} lt "2026" && defined $self->{session};

   if ($self->{protocol_version} ge "2026" && exists $message->{method} && exists $message->{id}) {
      $headers{"mcp-method"} = $message->{method};
      if ($message->{method} =~ /\A(?:tools\/call|prompts\/get|resources\/read)\z/) {
         my $name = exists $message->{params}{name} ? $message->{params}{name} : $message->{params}{uri};
         $headers{"mcp-name"} = $name =~ /[^\x20-\x7e]/
            ? "=?base64?" . MIME::Base64::encode_base64 (AnyEvent::MCP::utf8enc ($name), "") . "?="
            : $name;
      }
   }

   my ($buffer, $sse, $received, $failure) = ("", 0, 0);
   my $limit = $self->{max_size} || 8 * 1024 * 1024;
   weaken $self;

   my $deliver = sub {
      my ($response) = @_;

lib/AnyEvent/MCP/Config.pm  view on Meta::CPAN

an ordered list of context byte strings C<@info>. The class form uses
C<global_config>, loading the default configuration on first use and reusing it
thereafter. The object form uses that object's configuration, including
one loaded from an explicit file.

The same master secret and context always produce the same bytes. Use a
distinctive application/purpose string as the first context field, followed
by names or other values identifying the result:

   my $secret = AnyEvent::MCP::Config->derive_secret (
      32, "my application token v1", AnyEvent::MCP::utf8enc ($name)
   );

The result contains raw bytes; encode it yourself if a printable token is
needed. This method does not add the result to a server's accepted tokens.

The fixed C<anyevent-mcp> context field is prepended automatically.
Context fields are separately length-prefixed, so C<("ab", "c")> and
C<("a", "bc")> have different contexts. Encode character strings explicitly,
for example with C<AnyEvent::MCP::utf8enc>. Context arguments are left
unchanged.

C<$length> must be an integer in 0..16320; zero returns an empty string.
Shorter results are prefixes of longer results for the same master secret
and context. Use distinct context fields for different purposes, rather
than relying on different lengths to separate them.

Derivation uses HKDF-SHA512 expansion, with each context field prefixed by
its four-byte big-endian byte length. Changing or losing the master secret
changes every result derived from it.

lib/AnyEvent/MCP/Config.pm  view on Meta::CPAN


   $username = "" unless defined $username;

   $purpose eq "token"
      or die "Unknown credential purpose '$purpose'\n";

   my $credential = MIME::Base64::encode_base64 (
      $self->derive_secret (
         32,
         $purpose,
         (AnyEvent::MCP::utf8enc program_name),
         (AnyEvent::MCP::utf8enc $name),
         (AnyEvent::MCP::utf8enc $username)
      ), ""
   );
   $credential =~ y!+/=!-_!d;

   $credential
}

sub users {
   my ($self, $name, $program) = @_;

lib/AnyEvent/MCP/Config.pm  view on Meta::CPAN


   $name = AnyEvent::MCP::instance_name $name;
   $program //= program_name;
   my $users = $self->users ($name, $program);
   my @credentials;

   for my $user (sort { ($a ne "default") <=> ($b ne "default") || $a cmp $b } keys %$users) {
      my $info = $users->{$user};
      next unless $info->{generation} > 0;
      my $token = MIME::Base64::encode_base64 ($self->derive_secret (
         32, "user-token-v1", AnyEvent::MCP::utf8enc ($program),
         AnyEvent::MCP::utf8enc ($name), $info->{scope},
         AnyEvent::MCP::utf8enc ($user), "$info->{generation}"
      ), "");
      $token =~ y!+/=!-_!d;
      push @credentials, [$user, "$info->{scope}:$user", $token];
   }

   \@credentials
}

sub connect_user {
   my ($self, $name, $program) = @_;

lib/AnyEvent/MCP/Config.pm  view on Meta::CPAN


sub server_port {
   my ($self, $name) = @_;

   $name = AnyEvent::MCP::instance_name $name;

   16384 + (
      (unpack "n", $self->derive_secret (
         2,
         "port",
         (AnyEvent::MCP::utf8enc program_name),
         (AnyEvent::MCP::utf8enc $name))
   ) & 16383)
}

sub http_settings {
   my ($self, $name, $bind, $default_port) = @_;

   $name = AnyEvent::MCP::instance_name $name;
   my $settings = {
      %{ $self->{section}{"program " . program_name ()} },
      %{ $self->{section}{"instance $name"} },

lib/AnyEvent/MCP/Extension.pm  view on Meta::CPAN

sub accept {
   my ($handle, $tokens, $done, $reject) = @_;

   my $rbuf_max = $handle->{rbuf_max};
   $handle->rtimeout (15);
   $handle->{rbuf_max} = 4096;
   $handle->push_read (line => sub {
      my (undef, $line) = @_;

      my $ok = eval {
         my $hello = JSON::XS->new->utf8->max_depth (8)->decode ($line);
         ref $hello eq "ARRAY" && @$hello >= 2
            && defined $hello->[0] && !ref $hello->[0]
            && defined $hello->[1] && !ref $hello->[1]
            && (grep $_ eq $hello->[1], @$tokens)
            or die "Invalid extension hello\n";

         $handle->rtimeout (0);
         $handle->{rbuf_max} = $rbuf_max;
         $done->($handle, $hello);
         1

lib/AnyEvent/MCP/IMAP/OAuth2.pm  view on Meta::CPAN

use AnyEvent::HTTP ();
use AnyEvent::MCP ();
use AnyEvent::MCP::Config ();
use Digest::SHA ();
use MIME::Base64 ();
use JSON::XS ();

# OAuth form parameters are Unicode text; escape the UTF-8 bytes.
sub encode {
   my ($str) = @_;
   my $bytes = AnyEvent::MCP::utf8enc $str;
   $bytes =~ s/([^A-Za-z0-9._~-])/sprintf "%%%02X", ord $1/ge;
   $bytes
}

sub form {
   my (%pairs) = @_;
   join "&", map +(encode $_) . "=" . (encode $pairs{$_}), sort keys %pairs
}

sub decode {
   my ($str) = @_;
   $str =~ /%(?![a-fA-F0-9]{2})/ and die "Invalid OAuth redirect URL encoding\n";
   $str =~ tr/+/ /;
   $str =~ s/%([a-fA-F0-9]{2})/chr hex $1/ge;
   AnyEvent::MCP::utf8dec $str
}

sub b64url {
   my ($bytes) = @_;
   my $s = MIME::Base64::encode_base64 ($bytes, "");
   $s =~ tr{+/}{-_};
   $s =~ s/=+\z//;
   $s
}

lib/AnyEvent/MCP/IMAP/OAuth2.pm  view on Meta::CPAN

   }
   my %current = %{AnyEvent::MCP::Config::merge_sections ($sections, "account")->{account}};
   for my $key (qw(method server user tls port oauth-client-id oauth-client-secret
                   oauth-client-auth oauth-token-endpoint oauth-scope oauth-sasl)) {
      ($current{$key} // "") eq ($kv->{$key} // "")
         or die "IMAP OAuth account changed; restart mcp-imap\n";
   }
   my $encoded = $current{"oauth-refresh-token-base64"};
   defined $encoded && $encoded =~ /\A[A-Za-z0-9+\/]*={0,2}\z/
      or die "Missing OAuth refresh token; run mcp-imap login again\n";
   my $old = AnyEvent::MCP::utf8dec (MIME::Base64::decode_base64 $encoded);
   length $old or die "Empty OAuth refresh token\n";
   my $new = token ($kv, grant_type => "refresh_token", refresh_token => $old);
   if (defined $new->{refresh_token} && $new->{refresh_token} ne $old) {
      $current{"oauth-refresh-token-base64"} = MIME::Base64::encode_base64 (AnyEvent::MCP::utf8enc $new->{refresh_token}, "");
      AnyEvent::MCP::file_save $file,
         AnyEvent::MCP::Config::serialize_ini [["account", \%current]];
   }
   close $lock;
   $new->{access_token}
}

1;

lib/AnyEvent/MCP/Permissions/Ask.pm  view on Meta::CPAN

      ) : ())
}

sub detail_text {
   my ($label, $text) = @_;

   defined $text && !ref $text
      or die "Invalid permission detail\n";

   my $chars = length $text;
   my $bytes = length AnyEvent::MCP::utf8enc $text;
   my $truncated = $chars > 65536;
   $text = substr $text, 0, 65536;
   $text =~ s/([\x00-\x08\x0b-\x1f\x7f-\x9f\x{202a}-\x{202e}\x{2066}-\x{2069}])/sprintf "\\u{%X}", ord $1/ge;
   $label =~ s/([\x00-\x1f\x7f-\x9f\x{202a}-\x{202e}\x{2066}-\x{2069}])/sprintf "\\u{%X}", ord $1/ge;

   "$label: $chars characters, $bytes UTF-8 bytes\n\n"
      . ($truncated ? "WARNING: INCOMPLETE PREVIEW. Additional text is not shown here.\n\n" : "")
      . $text
}

lib/AnyEvent/MCP/Server/HTTP.pm  view on Meta::CPAN

         "mcp-method"           => $message->{method},
      );

      $expected{"mcp-name"} = exists $params->{name} ? $params->{name} : $params->{uri}
         if $message->{method} =~ /\A(?:tools\/call|prompts\/get|resources\/read)\z/;

      for my $name (keys %expected) {
         my $value = $hdr->{$name};

         if ($name eq "mcp-name" && $value =~ /\A=\?base64\?([A-Za-z0-9+\/=]*)\?=\z/) {
            $value = eval { AnyEvent::MCP::utf8dec (MIME::Base64::decode_base64 ($1)) };
         }

         unless (defined $value && defined $expected{$name} && $value eq $expected{$name}) {
            return $self->_rpc_error (sub {
               $self->_respond ($handle, 400, "Bad Request", JSON::XS::encode_json $_[0]);
            }, $message->{id}, -32020, "Header mismatch: $name");
         }
      }
   }

lib/AnyEvent/MCP/Server/Permissions.pm  view on Meta::CPAN


   my $auto_rules = delete $kv{auto_rules} || [];
   my $ask = exists $kv{ask} ? $kv{ask} : $ENV{PERL_ANYEVENT_MCP_PERMISSION_ASK};
   $ask = "helper" unless defined $ask && length $ask;
   die "Invalid permission ask mode (expected helper, tty, yad, auto, mcp, or none)\n"
      unless ref $ask eq "CODE" || !ref $ask && $ask =~ /\A(?:helper|tty|yad|auto|mcp|none)\z/;

   my $self = $class->SUPER::new (sandbox_grants => {}, actions => {}, rules => [], ask => $ask, timeout => 300, %kv);

   if (!exists $kv{file} && defined $kv{name}) {
      my $name = AnyEvent::MCP::utf8enc $kv{name};
      $name =~ s/([^A-Za-z0-9_.-])/sprintf "%%%02X", ord $1/ge;
      my $dir = $ENV{XDG_CONFIG_HOME} || ($ENV{HOME} || die "HOME is not set\n") . "/.config";
      $self->{file} = "$dir/anyevent-mcp/rules/$name.ini";
   }

   $self->closure ([keys %{$self->{sandbox_grants}}]);
   $self->_rule ($_) for @{$self->rules};
   $self->auto_rules ($auto_rules);
   $self
}

lib/AnyEvent/MCP/Workdirs.pm  view on Meta::CPAN

=cut

package AnyEvent::MCP::Workdirs;

use common::sense;
use AnyEvent::MCP ();
use JSON::XS ();

our @ISA = qw(AnyEvent::MCP::Base);

my $json = JSON::XS->new->utf8->canonical->pretty;

sub _read {
   my ($self, $lock) = @_;

   local $/;
   my $text = <$lock>;
   my $entries = length $text ? $json->decode ($text) : {};
   ref $entries eq "HASH" or die "$self->{file}: expected workdir ID object\n";

   for my $id (keys %$entries) {

lib/AnyEvent/MCP/Worker/IMAP.pm  view on Meta::CPAN

      my %row = (uid => 0 + $uid);
      for my $field (@fields) {
         next if $field eq "uid";
         my $key = $env{$field};
         $row{$field} = $key ? $item->{envelope}{$key}
                      : $field eq "size" ? $item->{"rfc822.size"} : $item->{$field};
         $row{$field} = mime_header ($row{$field}) if $field =~ /\A(?:subject|from|to|cc|reply-to)\z/;
      }
      if (@headers) {
         $row{headers} = $item->{headers} || {};
         length (JSON::XS->new->utf8->encode ($row{headers})) <= 65536
            or die "Selected headers exceed 64 KiB\n";
      }
      push @messages, \%row;
   }

   my $before = $explicit ? undef : $incomplete ? $hi + 1 : @found ? $found[-1] : undef;

   +{
      uidvalidity => $validity,
      messages    => \@messages,

t/c00_load.t  view on Meta::CPAN

   AnyEvent::MCP::Server::Permissions
   AnyEvent::MCP::Server::Request
   AnyEvent::MCP::Server::Simple
   AnyEvent::MCP::Server::Toolset
   AnyEvent::MCP::Workdirs
)) {
   require_ok $module;
}

my $text = "\x{e4}\x{1f642}";
my $bytes = AnyEvent::MCP::utf8enc $text;
is $bytes, "\xc3\xa4\xf0\x9f\x99\x82", "encode UTF-8";
is AnyEvent::MCP::utf8dec ($bytes), $text, "decode UTF-8";
is $text, "\x{e4}\x{1f642}", "source is unchanged";
eval { AnyEvent::MCP::utf8dec ("\xff") };
ok $@, "reject invalid UTF-8";

done_testing;

t/c02_config.t  view on Meta::CPAN

my $unicode_config = "$dir/unicode.ini";
my $lock = AnyEvent::MCP::file_lock $unicode_config;
AnyEvent::MCP::file_save $unicode_config, $unicode_ini;
close $lock;
ok AnyEvent::MCP::file_load ($unicode_config) eq $unicode_ini,
   "shared UTF-8 text loader and saver round-trip non-ASCII characters";
open $fh, "<:raw", $unicode_config or die $!;
ok AnyEvent::MCP::file_load ($unicode_config, $fh) eq $unicode_ini,
   "UTF-8 loader can read an already open filehandle without closing it";
close $fh;
my $invalid_utf8 = "$dir/invalid-utf8.ini";
my $invalid_lock = AnyEvent::MCP::file_lock $invalid_utf8;
AnyEvent::MCP::file_replace $invalid_utf8, "[text]\nvalue = \xff\n";
close $invalid_lock;
ok !eval { AnyEvent::MCP::file_load $invalid_utf8; 1 },
   "shared UTF-8 text loader rejects invalid encoding";
my $cfg = AnyEvent::MCP::Config->new (file => $unicode_config)->load;
ok $cfg->{section}{text}{value} eq "\x{e4}\x{1f431}",
   "global configuration uses the same shared UTF-8 INI parser";
ok $cfg->ensure_secret->{section}{global}{secret} eq
   AnyEvent::MCP::Config->new (file => $unicode_config)->load->{section}{global}{secret},
   "secret creation re-reads Unicode INI bytes and persists the generated secret";

my $partial = "$dir/partial.ini";
open $fh, ">", $partial or die $!;

t/c16_vim_auth.t  view on Meta::CPAN

   print {$in} JSON::XS::encode_json ({
      jsonrpc => "2.0", id => $id, method => "tools/call",
      params => { name => $name, arguments => $args },
   }), "\n" or die "send tool request: $!";
}

my %vim_parser;

sub vim_call {
   my $socket = $_[0] || $valid;
   my $parser = $vim_parser{fileno $socket} ||= JSON::XS->new->utf8;
   for (1 .. 120) {
      my $packet = $parser->incr_parse;
      return $packet if $packet;
      next unless IO::Select->new ($socket)->can_read (0.25);
      my $n = sysread $socket, my $fragment, 8192;
      last unless $n;
      $parser->incr_parse ($fragment); # void context: leave complete packets for the next iteration
   }
   die "private Vim message timeout\n";
}

t/c18_form.t  view on Meta::CPAN

use common::sense;
use JSON::XS ();
local $/;
open my $fh, "<", $ENV{MCP_TEST_FORM_QUEUE} or die $!;
my $queue = JSON::XS::decode_json <$fh>;
close $fh;
my $reply = shift @$queue or die "Unexpected form";
open $fh, ">", $ENV{MCP_TEST_FORM_QUEUE} or die $!;
print {$fh} JSON::XS::encode_json $queue;
close $fh;
utf8::decode ($_) for @ARGV;
open $fh, ">>", $ENV{MCP_TEST_FORM_LOG} or die $!;
print {$fh} JSON::XS::encode_json (\@ARGV), "\n";
close $fh;
my @fields = grep /\A--field=/, @ARGV;
my @quoted = map {
   my $value = $_;
   my $field = shift @fields;
   $value =~ s/([\x09\x0a\x5c])/chr (92) . (ord $1 == 10 ? "n" : ord $1 == 9 ? "t" : chr (92))/ge
      if $field =~ /:TXT\z/;
   $value =~ s/'/chr (39) . chr (92) . chr (39) . chr (39)/ge;
   "'$value'"
} @{$reply->{values} || []};
my $output = join " ", @quoted;
utf8::encode $output;
print $output, "\n";
exit $reply->{status};
};
chmod 0700, "$dir/yad" or die $!;
local $ENV{PATH} = "$dir:$ENV{PATH}";
local $ENV{MCP_TEST_FORM_QUEUE} = "$dir/queue";
local $ENV{MCP_TEST_FORM_LOG} = "$dir/log";

sub run_form {
   my ($params, $queue, @options) = @_;

t/c20_workdirs.t  view on Meta::CPAN

use common::sense;
use Test::More;
use AnyEvent::MCP::Workdirs ();
use File::Temp ();
use JSON::XS ();
use POSIX ();

my $dir = File::Temp::tempdir (CLEANUP => 1);
my $file = "$dir/config/fs-workdir-ids.json";
my $json = JSON::XS->new->utf8;
my $start = time;

sub entries {
   open my $fh, "<", $file or die $!;
   local $/;
   $json->decode (<$fh>)
}

sub save_entries {
   my ($entries) = @_;

t/c29_imap_oauth.t  view on Meta::CPAN

   "oauth-token-endpoint" => "https://login.example.org/token",
   "oauth-scope" => "mail.read offline_access",
   "oauth-redirect-uri" => "http://127.0.0.1:1",
   "oauth-pkce" => 1,
   "oauth-auth-access_type" => "offline",
);

my $oauth = "AnyEvent::MCP::IMAP::OAuth2";
my $latin1 = "\x{e4}";
my $upgraded = $latin1;
utf8::upgrade $upgraded;
is $latin1, $upgraded, "both representations hold the same Unicode character";
is $oauth->can ("encode")->($latin1), "%C3%A4",
   "OAuth form encoding UTF-8 encodes a Latin-1-range codepoint";
is $oauth->can ("encode")->($upgraded), "%C3%A4",
   "OAuth form encoding is independent of the scalar UTF8 flag";
is $oauth->can ("form")->(scope => "mail.$latin1"), "scope=mail.%C3%A4",
   "OAuth form values are UTF-8 encoded before percent escaping";
is $oauth->can ("decode")->("%C3%A4"), $latin1,
   "OAuth percent decoder returns Unicode text";
ok !eval { $oauth->can ("decode")->("%FF"); 1 },

t/c29_imap_oauth.t  view on Meta::CPAN

      my $ok = eval { $oauth->can ("token")->(\%kv, grant_type => "refresh_token", refresh_token => "old"); 1 };
      ok !$ok && $@ =~ /response too large/, "OAuth token response size is bounded";
   }
}

{
   my %unicode = (%kv, "oauth-scope" => "mail.\x{e4}");
   my $old = "before-\x{e4}\x{1f431}";
   my $rotated = "after-\x{e4}\x{1f431}";
   $unicode{"oauth-refresh-token-base64"} =
      MIME::Base64::encode_base64 (AnyEvent::MCP::utf8enc $old, "");
   my $dir = tempdir (CLEANUP => 1);
   my $file = "$dir/unicode-account.ini";
   my $text = "[account]\n" . (join "", map "$_ = $unicode{$_}\n", sort keys %unicode);
   my $lock = AnyEvent::MCP::file_lock $file;
   AnyEvent::MCP::file_save $file, $text;
   close $lock;

   my $body;
   {
      no warnings "redefine";

t/c29_imap_oauth.t  view on Meta::CPAN

      };
      is $oauth->can ("refresh")->($file, \%unicode), "unicode-access",
         "refresh reads UTF-8 account settings and exchanges Unicode token text";
   }
   like $body, qr/refresh_token=before-%C3%A4%F0%9F%90%B1/,
      "Base64-decoded refresh token is decoded as UTF-8 before form encoding";

   my $settings = AnyEvent::MCP::Config::merge_sections (
      AnyEvent::MCP::Config::parse_ini (AnyEvent::MCP::file_load $file), "account")->{account};
   is $settings->{"oauth-scope"}, "mail.\x{e4}", "rotated account retains Unicode configuration values";
   is AnyEvent::MCP::utf8dec (MIME::Base64::decode_base64 $settings->{"oauth-refresh-token-base64"}),
      $rotated, "rotated refresh token is UTF-8 encoded before Base64 persistence";
}

my $worker_tests = eval {
   require Mail::IMAPTalk;
   require IO::Socket::SSL;
   require Authen::SASL;
   require AnyEvent::MCP::Worker::IMAP;
   1
};

t/e10_fs.t  view on Meta::CPAN

      && $result->{content}[0]{text} eq "[range=3]"
      && $result->{content}[1]{text} eq MIME::Base64::encode_base64 ("C\x80", ""),
      "base64 preserves absence of the final newline inside the encoded bytes";
   $result = call "read-lines" => {
      path => "binary-lines", ranges => ["2,3"], encoding => "base64", linenums => JSON::XS::true,
   };
   ok !$result->{isError}
      && MIME::Base64::decode_base64 ($result->{content}[1]{text}) eq "2:B\xe4\n3:C\x80",
      "base64 encodes numbered lines while retaining raw bytes and unterminated final line";

   write_file "$dir/work/utf8-lines", "\xc3\xa4\n";
   $result = call "read-lines" => { path => "utf8-lines", ranges => ["1"] };
   ok !$result->{isError} && @{$result->{content}} == 2
      && $result->{content}[0]{text} eq "[range=1]"
      && $result->{content}[1]{text} eq chr (0xe4) . "\n",
      "valid UTF-8 is decoded into a separate source entry with default behavior unchanged";
   $result = call "read-lines" => { path => "utf8-lines", ranges => ["1"], encoding => "latin1" };
   ok !$result->{isError} && @{$result->{content}} == 2
      && $result->{content}[0]{text} eq "[range=1]"
      && $result->{content}[1]{text} eq "\xc3\xa4\n",
      "Latin-1 does not reinterpret valid UTF-8 byte sequences";
   $result = call "read-lines" => { path => "read", ranges => ["1"], encoding => "utf-16" };
   ok $result->{isError}, "unsupported read-lines encoding is rejected";

   my $large_bytes = "X" x ((1 << 20) + 100);
   write_file "$dir/work/large-lines", $large_bytes;
   $result = call "read-lines" => { path => "large-lines", ranges => ["1"], encoding => "base64" };

t/e10_fs.t  view on Meta::CPAN

   my @log = split /\n/, read_file "$dir/vcs.log";
   my $argv = JSON::XS::decode_json $log[-1];
   ok !$result->{isError} && read_file ("$dir/vcs-cwd.log") eq "$dir/work/sub"
      && $argv->[-1] eq ($backend eq "svn" ? "./../-strange@" : "./../-strange")
      && $prompts[-1]{reason} =~ /\Q$dir\/work\/sub\E/,
      "$backend runs in cwd with relative filenames and displays command directory";
}
my $unicode_cwd = "dir-\x{e4}\x{1f431}";
my $unicode_file = "file-\x{e4}\x{1f431}";
my ($cwd_bytes, $file_bytes) = ($unicode_cwd, "./$unicode_file");
utf8::encode $_ for $cwd_bytes, $file_bytes;
mkdir "$dir/work/$cwd_bytes" or die $!;
$result = call "vcs-status" => { backend => "git", cwd => $unicode_cwd, files => [$unicode_file] };
my @unicode_log = split /\n/, read_file "$dir/vcs.log";
my $unicode_argv = JSON::XS::decode_json $unicode_log[-1];
ok !$result->{isError} && read_file ("$dir/vcs-cwd.log") eq "$dir/work/$cwd_bytes",
   "VCS wrapper encodes Unicode working directory before chdir";
ok $unicode_argv->[-1] eq $file_bytes,
   "VCS pathspec is passed as UTF-8 bytes alongside binary executable path";

ok $tool{"vcs-diff"}{inputSchema}{properties}{cwd}{default} eq "."

t/e11_permission_ui.t  view on Meta::CPAN

   %ENV, PATH => "$dir:$ENV{PATH}", DISPLAY => ":test", WAYLAND_DISPLAY => "",
   PERL_ANYEVENT_MCP_TEST_UI_QUEUE => "$dir/queue",
   PERL_ANYEVENT_MCP_TEST_UI_LOG => "$dir/log",
   PERL_ANYEVENT_MCP_TEST_VIEW_LOG => "$dir/view_log",
);
my @prompt_options;
sub prompt {
   my ($request, @responses) = @_;
   write_file "$dir/queue", $json->encode (\@responses);
   my ($output, $error);
   my $input = AnyEvent::MCP::utf8enc ($json->encode ($request));
   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"),

t/e11_permission_ui.t  view on Meta::CPAN

      "popup uses a monospace source viewer";
   ok +(grep /--field=View stdin: .* characters, .* UTF-8 bytes:LBL/, @$form),
      "approval dialog identifies stdin without embedding its source";
   unlike $json->encode ($form), qr/print \\"ok\\"/,
      "source is not interpolated into the main dialog command line";
   open my $fh, "<", "$dir/view_log" or die $!;
   my $details = $json->decode (scalar <$fh>);
   close $fh;
   is $details->{mode}, 0600, "popup reads a private mode-0600 file";
   my $visible = pack "H*", $details->{contents_hex};
   is AnyEvent::MCP::utf8dec ($visible),
      AnyEvent::MCP::Permissions::Ask::detail_text ("View stdin", $source),
      "popup shows Unicode source and visibly escapes control characters";
}
my $truncated = prompt {
   %$preview, details => { "View stdin" => "first chunk" . ("x" x 65536) },
}, { status => 0, output => "\x1f\n", click_view => "View stdin" },
   { status => 0, output => "" };
is $truncated->{decision}, "deny-once", "viewing incomplete input does not force approval";
{
   open my $fh, "<", "$dir/view_log" or die $!;
   my $line;
   $line = $_ while <$fh>;
   close $fh;
   my $info = $json->decode ($line);
   like AnyEvent::MCP::utf8dec (pack "H*", $info->{contents_hex}),
      qr/65547 characters.*WARNING: INCOMPLETE PREVIEW.*first chunk/s,
      "UI bounds complete detail text and conspicuously warns about the incomplete preview";
}

my $patch_details = {
   %$request,
   details => {
      "View patch" => "File: /one/file\n\n@@ -1 @@\n-old\n+new\n",
      "More: context" => "second detail\n",
   },

t/e30_fs_remote.t  view on Meta::CPAN

   env => \%env,
);
$r = call $broken, "file-read" => { path => "renamed" };
ok $r->{isError}, "remote sandbox=auto does not fall back when bwrap is present but fails";
$broken->close;

my $unicode_workdir = "$dir/work-\x{e4}\x{1f431}";
my $unicode_home = "$dir/home-\x{e4}";
my $file = "name-\x{1f431}";
my ($raw_workdir, $raw_home, $raw_file) = ($unicode_workdir, $unicode_home, $file);
utf8::encode $_ for $raw_workdir, $raw_home, $raw_file;
mkdir $raw_workdir or die $!;
mkdir $raw_home or die $!;
put "$raw_workdir/$raw_file", "unicode paths\n";
my $unicode_bin = "$dir/bin-\x{e4}\x{1f431}";
my $raw_bin = $unicode_bin;
utf8::encode $raw_bin;
mkdir $raw_bin or die $!;
put "$raw_bin/git", "#!$^X\nprint 'raw git output';\n";
chmod 0700, "$raw_bin/git" or die $!;
open my $cfg, ">>:raw", "$dir/config/anyevent-mcp/global.ini" or die $!;
my $config_text = "[program mcp-fs]\nprepend-path = $unicode_bin\nexecutable.git = $unicode_bin/git\n"
   . "mount-try.unicode = ro:$unicode_bin\nenv.unicode = MCP_TEST_UNICODE=value-\x{e4}\x{1f431}\nenv.raw = MCP_TEST_RAW\n";
utf8::encode $config_text;
print {$cfg} $config_text;
close $cfg or die $!;
my %unicode_env = (%env, HOME => $raw_home, MCP_TEST_RAW => "\xff");
my $unicode_client = AnyEvent::MCP::Client::JSONL->new (
   command => [@base, $raw_workdir], env => \%unicode_env,
);
$r = call $unicode_client, workdirs => {};
ok (grep $_ eq $unicode_workdir, values %{$r->{structuredContent}{resolved_workdirs}}),
   "remote startup probe decodes explicitly encoded Unicode workdir";
$r = call $unicode_client, "file-read" => { path => $file };



( run in 4.303 seconds using v1.01-cache-2.11-cpan-234fa220139 )