AnyEvent-MCP

 view release on metacpan or  search on metacpan

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


Print short usage synopsis and exit.

=back

Without explicit C<--tty> or C<--yad>, prompts try YAD first, then
C</dev/tty> only if YAD cannot start. Closing or declining a working
dialog never triggers fallback.

=cut

use common::sense;

use Getopt::Long ();
use Text::ParseWords ();
use File::Temp ();
use JSON::XS ();

use AnyEvent::MCP ();
use AnyEvent::MCP::Permissions::Ask ();
use AnyEvent::MCP::Server::Permissions ();

Getopt::Long::GetOptions
   "manage-rules=s" => \my $rules_file,
   "edit-rules=s"   => \my $edit_file,
   "tty"            => \my $tty_only,
   "yad"            => \my $yad_only,
   "help"           => \my $help,
   or exit 2;

@ARGV || defined $rules_file && defined $edit_file
   and die "Unexpected arguments\n";
$tty_only && $yad_only
   and die "--tty and --yad are mutually exclusive\n";
($tty_only || $yad_only) && (defined $rules_file || defined $edit_file)
   and die "--tty/--yad select permission prompts, not rule management\n";

if ($help) {
   print "usage: $0 [--tty | --yad | --manage-rules FILE | --edit-rules FILE]\n";
   exit;
}

binmode STDIN;
binmode STDOUT;

my $json = JSON::XS->new->canonical;
my $yad_pid;
$SIG{TERM} = $SIG{INT} = sub {
   if ($yad_pid) {
      kill TERM => $yad_pid;
      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;
      my ($status, $output) = yad (
         "--list", "--title=MCP permission rules", "--width=900", "--height=450",
         "--text=$file\nRules are evaluated from top to bottom; the first match wins.",
         "--column=Order:NUM", "--column=Decision", "--column=Action",
         "--column=Dimensions", "--column=Sandbox grants", "--column=Expires",
         "--no-click", "--print-column=1", "--separator=\x1f",
         "--button=Close:0", "--button=Move up:4",
         "--button=Move down:6", "--button=Delete selected:2",
         map {
            my $rule = $rules->[$_];
            $_ + 1, $rule->{decision} || "ask",
            (exists $rule->{action} ? $json->encode ($rule->{action}) : "(any)"),
            (join ", ", map { "$_=" . $json->encode ($rule->{$_}) }
               sort grep /^match\./, keys %$rule) || "(any)",
            (exists $rule->{"sandbox-grants"} ? $json->encode ($rule->{"sandbox-grants"}) : "(any)"),
            (exists $rule->{expires} ? scalar localtime $rule->{expires} : "Indefinite")
         } 0 .. $#$rules,
      );
      defined $status
         or die "YAD rule editor unavailable\n";
      return unless grep $_ == $status, 2, 4, 6;
      my ($index) = $output =~ /\A([1-9][0-9]*)\x1f?\s*\z/;
      next unless $index && $index <= @$rules;
      next if $status == 4 && $index == 1;
      next if $status == 6 && $index == @$rules;
      my $expected = $json->encode ($rules);

      my $ok = eval {
         my $lock = $permissions->_lock;
         my $current = $permissions->rules;
         die "Permission rules changed since selection\n"
            unless $json->encode ($current) eq $expected;
         if ($status == 2) {
            splice @$current, $index - 1, 1;
         } else {
            my $other = $status == 4 ? $index - 2 : $index;
            @$current[$index - 1, $other] = @$current[$other, $index - 1];
         }

         # deletion does not need the application's capability implications.
         $permissions->{sandbox_grants} = {
            map { map { $_ => [] } split /,/, $_->{"sandbox-grants"} } @$current
         };
         $permissions->_write ($current);
         1
      };
      unless ($ok) {
         my $error = $@;
         print STDERR $error;
         yad "--title=MCP permission rules", "--text=$error", "--button=Close:0";
      }
   }
}

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

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

my $dimensions = $request->{dimensions} || {};
my @dimensions = AnyEvent::MCP::Permissions::Ask::dimension_names $request;
my @selectable_dimensions = grep @{$dimensions->{$_}{choices}} > 1, @dimensions;
my %decisions = (d => "deny-once", n => "deny-always", o => "allow-once", a => "allow-always");
my $persistent = !grep !@{$dimensions->{$_}{choices}}, @dimensions;
my @deny_paths = grep defined && !ref, @{$request->{paths} || []};
my $unsandboxed = ($request->{sandbox_implementation} || "") =~ /\ANONE/;

sub rule_dialog {
   my ($choice, $message) = @_;

   # Repeat the action above the scopes; YAD runs with --no-markup.
   my $action = display_text ($request->{action});
   $action =~ s/[\r\n\t]/ /g;
   my $allow = $choice eq "allow-always";
   my %selected = map { $_ => 1 } @{$request->{sandbox_grants}};

   my @fields;
   if ($allow) {
      push @fields, map {
         my $grant = $_;
         my $description = $request->{sandbox_grant_descriptions}{$grant};
         my $label = $grant . (defined $description && length $description ? " - $description" : "");
         $label =~ s/\\/\\\\/g;
         ("--field=$label:CHK", $selected{$grant} ? "TRUE" : "FALSE")
      } @{$request->{sandbox_grant_choices}};
   }

   push @fields, map {
      my $dim = $dimensions->{$_};
      my $default = $dim->{default} // $dim->{choices}[0]{match};
      ("--field=$dim->{label} scope:CB", join "\x1f",
         map { ($dim->{choices}[$_]{match} eq $default ? "^" : "")
            . ($_ + 1) . ": " . $json->encode ($dim->{choices}[$_]{label}) }
            0 .. $#{$dim->{choices}})
   } @selectable_dimensions;

   if (!$allow && @deny_paths) {
      push @fields, "--field=Deny file scope:CB", join "\x1f",
         (map { ($_ == 0 ? "^" : "") . ($_ + 1) . ": Exact file " . $json->encode ($deny_paths[$_]) }
            0 .. $#deny_paths),
         (@deny_paths + 1) . ": All paths";
   }

   my ($status, $output) = yad (
      "--form", "--title=Create MCP permission rule",
      "--width=650", "--separator=\x1f", "--item-separator=\x1f",
      "--num-output", "--always-print-result", "--buttons-layout=edge",
      "--text=Action: $action\n\nConfigure which future requests this rule covers."
         . (!$allow ? "\nDenial reason: " . (length $message ? $message : "(none)") : ""),

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

      my @grants;
      for (@{$request->{sandbox_grant_choices}}) {
         my $value = shift @values;
         defined $value && $value =~ /\A(?:TRUE|FALSE)\z/i
            or die "Invalid YAD sandbox grant selection\n";
         push @grants, $_ if lc $value eq "true";
      }
      $answer{sandbox_grants} = \@grants;
   }

   for my $name (@selectable_dimensions) {
      my $index = shift @values;
      defined $index && $index =~ /\A[1-9][0-9]*\z/
         && $index <= @{$dimensions->{$name}{choices}}
         or die "Invalid YAD dimension scope\n";
      $answer{"dim_$name"} = $dimensions->{$name}{choices}[$index - 1]{match};
   }

   if (!$allow && @deny_paths) {
      my $index = shift @values;
      defined $index && $index =~ /\A[1-9][0-9]*\z/
         && $index <= @deny_paths + 1
         or die "Invalid YAD denial file scope\n";
      $answer{path} = $deny_paths[$index - 1] if $index <= @deny_paths;
   }

   my $lifetime = shift @values;
   defined $lifetime && $lifetime =~ /\A[123]\z/
      or die "Invalid YAD rule lifetime\n";
   $answer{lifetime} = ("indefinite", "900", "57600")[$lifetime - 1];

   \%answer
}

# display-only details are passed by filename, never through shell source text.
sub shell_quote {
   my $arg = shift;

   $arg =~ s/'/'\\''/g;
   "'$arg'"
}

sub display_text {
   my $text = shift;

   # render control and bidi characters explicitly, preserving tabs and newlines.
   $text =~ s/([\x00-\x08\x0b-\x1f\x7f-\x9f\x{202a}-\x{202e}\x{2066}-\x{2069}])/sprintf "\\u{%X}", ord $1/ge;
   $text
}

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;

      push @fields,
         "--field=$info:LBL", "",
         "--field=$button...:FBTN",
         join " ", map shell_quote ($_),
            ("yad", "--no-markup", "--text-info",
             "--title=MCP permission: $label", "--width=900", "--height=650",
             "--fontname=Monospace 11", "--filename=$filename",
             "--button=Close:0");
   }

   @fields
}

sub graphical {
   if (($request->{_permission_stage} || "") eq "rule") {
      my $previous = $request->{_permission_selection};
      return rule_dialog ($previous->{decision}, $previous->{message} // "");
   }

   my @details = map {
      my $value = $request->{$_};
      $value = $_ eq "reason" ? display_text ($value)
         : ref $value || $value =~ /[\x00-\x1f\x7f]/ ? $json->encode ($value) : $value;
      $value =~ s/\\/\\\\/g;
      ({
         name                   => "Server",
         multibroker_alias      => "Multibroker alias",
         tool                   => "Tool",
         action                 => "Action",
         action_description     => "Action description",
         sandbox_implementation => "Sandbox",
         paths                  => "Paths",
         reason                 => "Reason",
      }->{$_} || ucfirst $_) . ": $value"
   } grep defined $request->{$_},
      qw(name multibroker_alias tool action action_description
         sandbox_implementation paths reason);
   push @details, map {
      my $dim = $dimensions->{$_};
      "$dim->{label}: " . $json->encode ($dim->{value})
   } @dimensions;

   my @view_fields = detail_fields;
   my $message = $request->{_permission_selection}{message} // "";
   while (1) {
      my ($status, $output) = yad (
         "--form", ($unsandboxed ? "--title=UNSANDBOXED MCP permission required"
                                  : "--title=MCP permission required"),
         "--width=650", "--height=400", "--scroll",



( run in 1.413 second using v1.01-cache-2.11-cpan-234fa220139 )