AnyEvent-MCP

 view release on metacpan or  search on metacpan

bin/mcp-fs  view on Meta::CPAN

=head1 NAME

mcp-fs - filesystem and command tools with optional sandboxing

=head1 SYNOPSIS

   mcp-fs --stdio /path/to/workdir
   mcp-fs --name project --bind 127.0.0.1:31741 /path/to/workdir
   mcp-fs --stdio --host kaos --rsh rsh /root/src

=head1 DESCRIPTION

C<mcp-fs> gives an MCP client tools to read, search and change files, and
run commands. An assistant can use these tools to work on your projects
without you writing a Perl server.

Start it with one or more project directories, called workdirs. The client
connects to the server, lists its tools and makes requests. A request can
select one of these workdirs; with only one, the selection can be omitted.
Tools operate on files on disk. To work with unsaved Vim buffers, use
L<mcp-vim>.

Before starting an operation, the server checks permission rules and, when
needed, asks you for approval. Operations normally run in a bubblewrap
sandbox with the approved access. Workdirs provide the default filesystem
scope; operations needing access elsewhere require the corresponding
sandbox grants.

You can connect an MCP client directly over HTTP or stdin/stdout, or run
the server through C<mcp-multibroker>. See L<AnyEvent::MCP::Intro> for a
walkthrough from installation to a first filesystem request.

With C<--host>, the same tools operate on a remote host over SSH (or the
command selected by C<--rsh>). Only Perl 5.8.4 and the tools used by the
requested operations are needed remotely; neither mcp-fs nor its CPAN
modules must be installed there. Each server instance uses one host, with
any number of workdirs on that host.

=head1 FIRST USE

Configure your MCP client to launch the server with an existing project:

   mcp-fs --stdio --name project /home/alice/src/project

The client starts the process and speaks MCP over stdin/stdout. Do not run
another copy in a terminal. For HTTP clients, run without C<--stdio> and
use C<--print-url> with the same C<--name> and C<--bind> settings; see
L<AnyEvent::MCP::Intro/YOUR FIRST FILESYSTEM SERVER>.

To inspect the tools available with your installed utilities without
starting a listener, run C<mcp-fs --tool-help /home/alice/src/project>.

Once connected, ask the assistant:

   Show the configured workdirs and list my project's top-level files.
   Read its README if present. Do not change files or run commands.

C<workdirs> shows the available paths without a worker. Listing requests
C<inspect> permission, and reading a file requests C<read>. Allow each once
to try them. Approval is specific to the requested action and sandbox grants.
If no dialog appears, inspect the tool error and server stderr: the helper
needs a YAD display or usable terminal. See L</PERMISSIONS>.

For a separate sandbox check without MCP, change to your project directory
and run:

   mcp-fs --exec-cmd workdir-read -- ls

This uses the current directory as the workdir. It tests the sandbox,
not client connectivity or permission prompting.

=head2 Remote workdirs

To use an existing directory on another machine:

   mcp-fs --stdio --host server.example.org /srv/project
   mcp-fs --stdio -h kaos -e rsh /root/src /srv/projects

Workdir arguments are ordinary absolute paths on that host, without a
C<host:> prefix. Omitting C<--host> retains local operation, regardless of
C<--rsh>. The remote shell is started locally, outside the operation
sandbox. Its connection does not require the remote operation's C<network>
grant. Combine unrelated hosts through C<mcp-multibroker>.

Remote request cancellation and timeouts terminate the local remote-shell
process, but may leave the remote worker running. After a connection failure,
the outcome of a modifying operation may be unknown; inspect the remote
filesystem before retrying it. Reliable remote process termination is not
yet implemented.

=head1 TOOLS

The filesystem tools are:

=over

=item C<workdirs>

Report configured workdirs and available sandbox grants, without starting a worker.

=item C<list>, C<find>

Enumerate directory entries.

=item C<stat>

Return lstat metadata without following symlinks.

=item C<file-read>

Read byte ranges and return Base64 data.

=item C<read-lines>

Read LF-delimited lines with selectable UTF-8, Latin-1 or Base64 representation.

=item C<grep>

Search files using a literal pattern or PCRE.

=item C<file-write>

Write Base64 bytes at an offset without implicit truncation.

=item C<path-op>

Perform pathname mutations.

=item C<file-patch>

Apply a unified diff to a single file.

=item C<exec>

Run an argv array, not a shell command string. To use shell syntax,
explicitly invoke a shell in that array.

=back

For C<exec>, C<stdin_encoding> selects C<utf-8> (default), C<latin1>
or C<base64>. The 4 MiB limit applies to the resulting stdin bytes.
The C<argv> elements are Unicode MCP strings encoded as UTF-8 for the
operating system; they cannot represent arbitrary non-UTF-8 argv bytes.
Stdout and stderr are decoded as UTF-8, with a raw capture limit of
1 MiB per stream; use the byte-range tools for binary file contents.
Its optional C<sandbox_grants> B<replaces> the default C<workdir-read>
grant rather than adding to it. Explicitly passing an empty array
therefore asks for no grants. Command exit codes are normal tool results,
not transport errors. On timeout, output collection stops and
C<truncated> is true; C<exit> and C<signal> still describe the reaped child.

Perl is required for normal server operation; missing optional GNU utilities
can cause their tools to be omitted. The command requested by C<exec>
is resolved when the worker runs; it need not be present when the server
starts. Inspect C<tools/list> rather than assuming every tool is present.

=head2 Command output

C<exec>, C<vcs-diff>, C<vcs-status> and C<vcs-log> share three presentation options:

=over

=item grep => $pattern

Optional PCRE line filter for stdout. It runs in a separate timed GNU grep
worker after command output has been captured. It is not passed to the
original command or a shell. Stderr remains unfiltered.

=item max_lines => $integer

Maximum returned stdout lines after filtering, default 2000, maximum 100000.

=item max_bytes => $integer

Maximum returned UTF-8 bytes per stream, default 65536, maximum 1048576.
Clipping does not leave an incomplete UTF-8 character. Stderr has its own
budget, so a large stdout does not hide diagnostics.

=back

The command runs once and is drained to completion, subject to its timeout.
Raw capture is bounded to 1 MiB per stream, independently of the returned
output limits. C<capture_truncated> means bytes were omitted before filtering
or collection ended on timeout: matches in that omitted output are unknown.
C<stdout_truncated>, C<stderr_truncated> and the combined C<truncated> flag
also account for returned-output limits.

Changing presentation options does not change the command's permission
subject. C<exit>, C<signal> and C<timed_out> always describe the original
command, including a diff exit code indicating differences. A filter error
makes the tool result an error and adds C<filter_error>, while retaining that
command status. The command may already have completed; do not rerun it
merely because its output filter failed.

=head2 Version control

C<vcs-diff>, C<vcs-status> and C<vcs-log> take a required C<backend>: C<git>, C<svn>,
C<cvs> or C<hg>, a workdir, an optional C<cwd> (default C<.>), and an optional
C<files> array. C<cwd> selects a directory within the workdir; it does not
change the granted mount boundary. Files are relative to C<cwd> and must
stay within the selected workdir. The worker checks its resolved directory
after chdir and before starting the client, rejecting symlink escapes.
Backend selection is explicit. With no files, the command examines the
working copy at C<cwd>. Files must be inside the selected workdir;
they are passed as literal filenames, not options, revisions or shell code.
Git diff shows unstaged changes; SVN, CVS and Mercurial diff compare the
working copy with its base. No commit, update, fetch or push is performed.
C<vcs-log> reads revision history. CVS reports revisions separately per file
(including their commit IDs), unlike Git's repository-wide commits.
Use output limits to bound potentially long histories.

These tools have separate C<vcs-diff>, C<vcs-status> and C<vcs-log> permission actions.
They request C<workdir-read> for the selected working copy. CVS additionally
requests C<ssh-agent>, which includes network access. SVN log may contact the
repository and also requests C<ssh-agent> to support svn+ssh; SVN diff/status,
Git and Mercurial operations run without network or home access.
A saved approval can cover the fixed operation regardless of filenames or
output filters, for that workdir and backend, or all supported backends.
Configured VCS clients and their configuration are trusted, including any
helpers they invoke; these tools do not sandbox the client's own semantics.
The ordinary sandbox grants still bound its host access. In unsandboxed
mode, the normal full-authority approval requirement applies.

Clients are resolved at startup. C<executable.git>, C<executable.svn>,
C<executable.cvs> and C<executable.hg> in trusted program/instance settings
can override them. A missing client produces a tool error for that backend.

=head1 REQUIREMENTS

Bubblewrap is required by default, but can be disabled explicitly.
Perl 5.8.4 or later must run in the worker environment at startup (except
for C<--exec-cmd>). GNU find, grep, patch and sed are optional; tools
requiring an unavailable utility are omitted. Use C<tools/list> to see
which tools are available.

Remote startup resolves workdirs, HOME, required mounts, executable
locations and VCS markers once; C<workdirs> thereafter uses this snapshot.
Optional C<mount-try> paths are instead passed to bubblewrap for every
invocation. Restart mcp-fs to refresh the workdir configuration and tools.

=head1 CONNECTIONS

HTTP is the default and does not print its URL on startup. C<--print-url>
prints the credential-bearing URL; the same token works in a bearer header.
C<--stdio> or

bin/mcp-fs  view on Meta::CPAN

shell-style quoting. No additional shell is used locally. For example,
C<--exec-prefix 'doas -n'> can read protected files on a machine using doas
instead of sudo. Remote execution uses the existing SSH command shell and
places the prefix before the remote Perl launcher. A failed prefix never
falls back to the original credentials.

=item --sudo[=USER]

Shortcut for C<--exec-prefix 'sudo -n'>, optionally adding C<-u USER>.
Overrides C<--exec-prefix>. For example, C<--sudo> with
C<--host user@host> works when SSH must log in as an unprivileged account
but passwordless sudo is permitted. C<--sudo=mail> runs as the mail user.
Sudo must work noninteractively; no password or terminal is supplied.

=item --host-dac

Keep the host user namespace and retain C<CAP_DAC_OVERRIDE> inside
bubblewrap. For example, a root worker can inspect a 0700 directory owned
by another user within a granted workdir. Other capabilities are dropped;
the existing mount and MCP permission restrictions still apply. Requires
privileged bubblewrap; C<--sandbox none> is incompatible.

=item --bwrap PATH

Use specified bubblewrap executable. Default: C<bwrap> found in C<PATH>.
Relevant with C<--sandbox bwrap> or C<--sandbox auto>.

=back

=head2 Shared-option behavior

=over

=item --name NAME

Also selects permission profile C<fs-NAME> and its rule file,
C<rules/fs-NAME.ini>. Default instance name: C<default>.

=item --print-url[=USER]

Does not require a WORKDIR argument.

=item --tool-help

Requires normal WORKDIR arguments, since available tools depend on the
selected workdirs and installed utilities.

=item --auto-allow TOOL[,ACTION[,CAPABILITY]]

For example, combining C<--auto-allow '*,inspect,workdir-read'> with
C<--auto-allow '*,read,workdir-read'> approves only those two actions
within read-only workdir authority. C<--auto-allow '*,*,workdir-write'>
approves any action requiring at most workdir-write authority,
including reads.

=back

Rules reside in C<$XDG_CONFIG_HOME/anyevent-mcp/rules/fs-NAME.ini>,
or the corresponding C<$HOME/.config> path. The rules filename shares the
service-instance name but has an C<fs> namespace. The default instance uses
C<rules/fs-default.ini>. The rules path is printed on stderr when starting
HTTP; normal startup leaves stdout untouched.
Local and remote instances with the same C<--name> intentionally share
the same rule profile. Permission requests include a host dimension: C<local>
for local execution, or C<remote HOST> using C<--host> independently of
C<--rsh>. New persistent rules default to this host, but may match all hosts.
The workdir matcher is simply the logical path, independent of host. Existing
rules lacking C<match.host> continue to apply across local and remote hosts;
only newly saved host-specific rules restrict this.
Use different instance names or C<match.host> to separate approvals for
different hosts. Unscoped rules apply across hosts sharing the profile.

=head1 TRUSTED CONFIGURATION

In C<~/.config/anyevent-mcp/global.ini> (or the corresponding
C<XDG_CONFIG_HOME> location), C<[program NAME]> supplies defaults based
on the executable basename, while C<[instance NAME]> overrides them for
C<--name NAME>. A symlinked executable therefore has its own program defaults.

   [program mcp-fs]
   mount-try.opt = ro:/opt
   mount-try.perl = ro:/opt/perl
   prepend-path = /opt/bin:/opt/sbin
   mount.shared = rw:/srv/shared
   env.cvs = CVS_RSH=/my/cvs/rsh
   executable.perl = /opt/bin/perl

   [instance myproject]
   mount.opt =
   prepend-path =
   mount.extra = ro:/srv/project-tools

To override settings for one invocation, use the common C<-s> / C<--set>
option rather than editing the file:

   mcp-fs --stdio -s executable.perl=/opt/perl/bin/perl \
     -s prepend-path=/opt/perl/bin /srv/project

Command-line settings take precedence over program and instance settings;
repeated keys use their last value. See L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.

Automatic permission rules can also be configured:

   [program mcp-fs]
   auto-rule.10 = allow *,read,workdir-read
   auto-rule.20 = allow *,write,workdir-write
   auto-rule.30 = deny *,exec,*

The supported configuration entries are:

=over

=item C<auto-rule.SUFFIX>

Automatic permission rules apply to every named mcp-fs instance;
CLI auto-rules are evaluated first.

=item C<mount.SUFFIX>

A required sandbox mount. The named path must exist at startup.

bin/mcp-fs  view on Meta::CPAN

         : map { (length $_ ? $_ : ".") . "/$name" } split /:/, $ENV{PATH}, -1;
      for (@path) {
         next unless -f $_ && -x _;
         return m{\A/} ? $_ : Cwd::getcwd () . "/$_";
      }
      undef
   }

   while (@ARGV) {
      my ($name, $wanted, $explicit) = splice @ARGV, 0, 3;
      my $path = find_executable $wanted;
      if ($path && !$explicit && $test{$name}) {
         my ($args, $match) = @{$test{$name}};
         my $ok = open my $fh, "-|", $path, @$args;
         if ($ok) {
            my $output = do { local $/; <$fh> };
            $ok = close $fh && $output =~ $match;
         }
         undef $path unless $ok;
      }
      $path ||= "";
      print "$path\0";
   }
};

my @names = qw(perl find grep patch sed git svn cvs hg);
my $perl_name = $executable{perl} || "perl";
my %program = %remote_program;
unless ($remote) {
   my @command = (@exec_prefix, $bwrap ? (fs_sandbox $workdir[0], []) : (),
      $perl_name, "-e", $probe,
      map { ($_, $executable{$_} || $_, length $settings{"executable.$_"} ? 1 : 0) } @names);
   my $pid = open my $fh, "-|";
   defined $pid or die "Perl probe fork: $!\n";

   unless ($pid) {
      my $passwd_fd = fs_passwd_fd () if $bwrap && !@exec_prefix;
      exec {$command[0]} @command;
      warn "exec $command[0]: $!\n";
      POSIX::_exit 126;
   }

   my $output = do { local $/; <$fh> };
   close $fh or die "Perl '$perl_name' cannot run in the worker environment\n";
   my @paths = split /\0/, $output, -1;
   @paths == @names + 1 && pop @paths eq ""
      or die "invalid Perl executable probe response\n";
   @program{@names} = @paths;
}
$program{perl} or die "Perl interpreter not found inside the sandbox\n";
($find, $grep, $patch, $perl, $sed) = @program{qw(find grep patch perl sed)};
warn "$_: not detected or wrong version\n"
   for grep !$program{$_}, qw(find grep patch sed);
%vcs_program = map { ($_ => $program{$_}) } qw(git svn cvs hg);

AE::log warn => "bubblewrap unavailable, running without sandbox"
   if $sandbox_mode eq "auto" && !$bwrap;

AnyEvent::detect; # proc_spawn creates child watchers after they might have died

# spawn stdin/stdout and stderr handles; proc_destroy closes them and terminates the child.
# the independent child watcher remains alive until the child is reaped.
sub proc_spawn {
   my ($program, @argv) = @_;

   my $remote_input;
   if ($remote) {
      $remote_input = $remote_launcher . fs_remote_frame ($bwrap ? AnyEvent::MCP::utf8enc $home : "", $program, @argv);
      ($program, @argv) = (@rsh, $host, $remote_command);
   } elsif (@exec_prefix) {
      ($program, @argv) = (@exec_prefix, $program, @argv);
   }

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

   my $pid = fork;
   defined $pid or die "fork: $!\n";

   unless ($pid) {
      open STDIN,  "<&", $child       or POSIX::_exit 126;
      open STDOUT, ">&", $child       or POSIX::_exit 126;
      open STDERR, ">&", $child_error or POSIX::_exit 126;

      close $parent;
      close $error;
      close $child;
      close $child_error;

      my $passwd_fd = fs_passwd_fd () if $bwrap && !$remote && !@exec_prefix;
      AnyEvent::Util::close_all_fds_except (0, 1, 2, ($bwrap && !$remote && !@exec_prefix ? 3 : ()));

      exec {$program} $program, @argv;
      print STDERR "exec $program: $!\n";
      POSIX::_exit 126;
   }

   close $child;
   close $child_error;

   my $io  = AnyEvent::Handle->new (fh => $parent);
   my $err = AnyEvent::Handle->new (fh => $error);
   my $proc = { pid => $pid };

   # keep the watcher alive independently so a fatal I/O error still reaps.
   $proc->{child} = AE::child $pid, sub {
      $proc->{status} = $_[1];
      delete $proc->{pid};
      delete $proc->{child};
      (delete $proc->{done})->($proc->{status}) if $proc->{done};
   };

   $io->{proc}     = $proc;
   $io->{proc_err} = $err;
   $io->push_write ($remote_input) if $remote;

   $io
}

# signal a spawned process while its pid is still owned by us.
sub proc_kill {
   my ($proc, $signal) = @_;

   my $pid = $proc->{pid} or return;

   $signal //= "KILL";
   kill $signal => $pid
}

# abandon a process and release its streams; repeated cleanup is harmless.
sub proc_destroy {
   my ($io) = @_;

   proc_kill (delete $io->{proc}) if $io->{proc};
   (delete $io->{proc_err})->destroy if $io->{proc_err};
   $io->destroy;
}

# register the process's exit callback, or call it immediately if reaped.
sub proc_on_exit {
   my ($proc, $done) = @_;

   return $done->($proc->{status})
      if defined $proc->{status};

   $proc->{done} = $done;
}

# run a one-shot subprocess, leaving output interpretation to the caller.
# the stream callbacks consume rbuf and may return true to terminate the child.
sub proc_run {
   my ($req, $command, $input, $timeout, $on_stdout, $on_stderr, $done) = @_;

   my $io = proc_spawn @$command;
   my $err = $io->{proc_err};
   my $proc = $io->{proc};
   my ($open, $timed_out, $failure, $timer) = (2);

   my $complete = sub {
      return if $open || !defined $proc->{status};
      my $cb = $done or return;
      undef $done;
      undef $timer;
      proc_destroy $io;
      return if $req->{finished};
      delete $req->{on_cancel};
      $cb->($proc->{status}, $timed_out, $failure);
   };

   my $stop = sub {
      undef $timer;
      delete $req->{on_cancel};
      $open = 0;
      proc_destroy $io;
      $complete->();
   };
   $req->{on_cancel} = $stop;

   for my $stream ([$io, $on_stdout], [$err, $on_stderr]) {
      my ($handle, $consume) = @$stream;
      my $closed;
      my $finish = sub {
         return if $closed++;
         --$open;
         $complete->();
      };
      my $read = sub {
         my ($handle, $eof) = @_;
         my $stop = eval { $consume->($handle, $eof) };
         if ($@) {
            $failure ||= $@;
            $stop = 1;
         }
         proc_kill $proc if $stop;
      };
      $handle->on_read (sub { $read->($_[0], 0) });
      $handle->on_eof (sub {
         $read->($_[0], 1);
         $finish->();
      });
      $handle->on_error (sub {
         return unless $_[1];
         $read->($_[0], 0);
         $failure ||= "subprocess I/O: $_[2]\n" unless $timed_out;
         proc_kill $proc;
         $finish->();
      });
   }

   my $ok = eval {
      $io->push_write ($input) if length $input;
      $io->push_shutdown;
      1
   };
   unless ($ok) {
      my $error = $@;
      proc_destroy $io;
      die $error;
   }

   $timer = AE::timer $timeout, 0, sub {
      $timed_out = 1;
      $stop->();
   };

   proc_on_exit $proc, $complete;
}

# run a subprocess and collect bounded output.
sub fs_run {
   my ($req, $command, $input, $timeout, $byte_limit, $line_limit, $done) = @_;

   my ($truncated, $line_truncated);
   my ($stdout, $stderr) = ("", "");

   my $capture = sub {
      my ($target, $data, $lines) = @_;

      return if $lines and $line_truncated;
      return unless length $data;
      my $remaining = $byte_limit - (length $stdout) - (length $stderr);
      $truncated = 1 if length $data > $remaining;
      $$target .= substr $data, 0, $remaining
         if $remaining > 0;

      if ($lines and $line_limit and ($$target =~ tr/\n//) > $line_limit) {
         my $end = -1;
         $end = index $$target, "\n", $end + 1
            for 1 .. $line_limit;
         substr $$target, $end + 1, length $$target, "";
         $truncated = $line_truncated = 1;
         return 1
      }

      0
   };

   proc_run $req, $command, $input, $timeout,
      sub {
         my ($handle) = @_;
         my $stop = $capture->(\$stdout, $handle->{rbuf}, 1);
         $handle->{rbuf} = "";
         $stop
      },
      sub {
         my ($handle) = @_;
         $capture->(\$stderr, $handle->{rbuf}, 0);
         $handle->{rbuf} = "";
         0
      },
      sub {
         my ($status, $timed_out, $failure) = @_;
         return $done->(0, $failure) if $failure;
         $done->(1, +{
            stdout    => $stdout,
            stderr    => $stderr,
            exit      => $status >> 8,
            signal    => $status & 127,
            timed_out => $timed_out ? JSON::XS::true : JSON::XS::false,
            truncated => $truncated || $timed_out ? JSON::XS::true : JSON::XS::false,
         });
      };
}

my $perl_slave = q{#perl
   binmode STDIN;
   binmode STDOUT;
   $SIG{PIPE} = "IGNORE";
   $| = 1;

   for (;;) {
      4 == read STDIN, my $buf, 4
         or last;
      my $len = unpack "N", $buf;
      $len == read STDIN, $buf, $len
         or die "short perl frame\n";

      my @result = do {
         (my $source, local @ARGV) = unpack "(w/a*)*", $buf;
         ("+", eval $source)
      };

      @result = ("-", $@)
         if $@;

      print pack "N/a*", pack "(w/a*)*", @result
         or die "stdout: $!\n"
   }
};

sub perl_frame {
   pack "N/a*", pack "(w/a*)*", @_
}

my $perl_worker;

sub perl_eval {
   my ($req, $workdir, $sandbox_grants, $source, $args, $timeout, $done) = @_;

   my @command = ((fs_sandbox $workdir, $sandbox_grants), $perl, "-e", $perl_slave);
   my $key = pack "(w/a*)*", @command;
   my $io = $perl_worker;
   undef $perl_worker;

   if ($io && ($io->{perl_key} ne $key || !$io->{proc}{pid})) {
      proc_destroy $io;
      undef $io;
   }

   unless ($io) {
      $io = proc_spawn @command;
      $io->{rbuf_max} = (1 << 20) + 4096;
      $io->{perl_key} = $key;
      weaken (my $this = $io);

      my $idle_destroy = sub {
         my $io = $this or return;

         undef $perl_worker if $perl_worker && $perl_worker == $io;
         proc_destroy $io;
      };
      my $idle_stderr = sub { $_[0]{rbuf} = "" };

      $io->{perl_idle} = sub {
         my ($io) = @_;
         my $err = $io->{proc_err};

         $io ->on_eof   ($idle_destroy);
         $io ->on_error ($idle_destroy);
         $err->on_eof   ($idle_destroy);
         $err->on_error ($idle_destroy);
         $err->on_read  ($idle_stderr );
         $io ->on_read  ($idle_destroy);
      };

      proc_on_exit $io->{proc}, sub {
         my $io = $this or return;

         $io->{perl_on_exit}->($_[0]) if $io->{perl_on_exit};
         $idle_destroy->() if $perl_worker && $perl_worker == $io;
      };
   }

   my $err = $io->{proc_err};
   my $timer;
   my $stderr = "";

   my $finish = sub {
      my ($failure, $payload) = @_;
      my $cb = $done or return;
      undef $done;
      undef $timer;
      delete $req->{on_cancel};
      delete $io->{perl_on_exit};

      if ($failure || defined $io->{proc}{status}) {
         my $status = $io->{proc}{status};
         my $reason = $failure || "exited (exit " . ($status >> 8)
            . ", signal " . ($status & 127) . ")";
         AE::log warn => "sandbox perl worker: $reason"
            unless $failure && $failure =~ /\Asandbox perl (?:cancelled|timed out)\n\z/;
         proc_destroy $io;
         return $cb->(0, $failure || "sandbox perl exited\n")
            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;
         return $cb->(0, $error) unless $req->{finished};
         return;
      }

      # the response completes the request; the interpreter remains idle.
      proc_destroy $perl_worker if $perl_worker;
      $perl_worker = $io;
      $io->{perl_idle}->($io);
      return if $req->{finished};
      return $cb->(0, $error) if defined $error;
      $cb->(1, \@response);
   };

   $io->{perl_on_exit} = sub {
      my ($status) = @_;
      $finish->("sandbox perl failed (exit " . ($status >> 8)
         . ", signal " . ($status & 127) . "): $stderr\n");
   };

   $req->{on_cancel} = sub { $finish->("sandbox perl cancelled\n") };
   $io->on_eof (sub { $finish->("short perl response\n") });
   $io->on_error (sub { $finish->("sandbox perl stdout: $_[2]\n") if $_[1] });
   $err->on_read (sub {
      $stderr .= substr $_[0]{rbuf}, 0, 65536 - length $stderr
         if length $stderr < 65536;
      $_[0]{rbuf} = "";
   });
   $err->on_eof (sub { $finish->("sandbox perl stderr closed\n") });
   $err->on_error (sub { $finish->("sandbox perl stderr: $_[2]\n") if $_[1] });

   $timer = AE::timer $timeout, 0, sub { $finish->("sandbox perl timed out\n") };
   my $ok = eval {
      $io->push_read (packstring => "N", sub {
         my ($io, $payload) = @_;

         return $finish->("unexpected sandbox perl output\n")
            if length $io->{rbuf};
         $finish->(undef, $payload);
      });
      $io->push_write (perl_frame $source, @$args);
      1
   };
   $finish->($@) unless $ok;
}

# resolve a configured workdir by persistent ID or exact path.
sub fs_workdir {
   my ($id) = @_;

   $id = $workdir_ids->{ids}[0] if !defined $id and @workdir == 1;

   defined $id && !ref $id
      or die "select a configured workdir by ID or exact path\n";

   my $i;
   if ($id =~ /\A[0-9]+\z/) {
      ($i) = grep $workdir_ids->{ids}[$_] == $id, 0 .. $#workdir;
      defined $i or die "Unknown workdir ID '$id'\n";
   } else {
      my @match = grep { $id eq $workdir_identity[$_] || $id eq $workdir[$_] } 0 .. $#workdir;
      @match == 1 or die @match
         ? "Ambiguous configured workdir '$id'\n"
         : "Unknown configured workdir '$id'\n";
      $i = $match[0];
   }

   wantarray ? ($workdir[$i], $workdir_identity[$i]) : $workdir[$i]
}

my $workdir_schema = {
   description => "Workdir ID or configured absolute path. Get IDs/paths from cerebro-fs.workdirs. IDs are persistent.",
   anyOf => [
      { type => "integer", minimum => 1 },
      { type => "string", minLength => 1 },
   ],
};

sub fs_result;

# command output options affect presentation, never argv or permission scope.
my %output_schema = (
   grep => { type => "string", description => "Optional PCRE stdout line filter after capture; no shell." },
   max_lines => { type => "integer", minimum => 1, maximum => 100000, default => 2000,
      description => "Max stdout lines after filtering." },
   max_bytes => { type => "integer", minimum => 1, maximum => 1048576, default => 65536,
      description => "Max returned UTF-8 bytes per stream; stderr unfiltered." },
);

sub fs_output_options {
   my ($args) = @_;

   my %options = (max_lines => $args->{max_lines} // 2000, max_bytes => $args->{max_bytes} // 65536);
   for my $name (qw(max_lines max_bytes)) {
      $options{$name} =~ /\A[0-9]+\z/ && $options{$name} >= 1
         && $options{$name} <= $output_schema{$name}{maximum}
         or die "invalid $name\n";
   }

   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;
      $$cut = 1 if length $handle->{rbuf} > $remaining;
      $$out .= substr $handle->{rbuf}, 0, $remaining if $remaining > 0;
      $handle->{rbuf} = "";
      0
   };

   proc_run $req, \@command, $input, $timeout,
      sub { $capture->($_[0], \$stdout, \$stdout_cut) },
      sub { $capture->($_[0], \$stderr, \$stderr_cut) },
      sub {
         my ($status, $timed_out, $failure) = @_;
         return $req->error ($failure) if $failure;

         my $result = {
            exit => $status >> 8, signal => $status & 127,
            timed_out => $timed_out ? JSON::XS::true : JSON::XS::false,
            capture_truncated => $stdout_cut || $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false,
         };

         my $finish = sub {
            my $ok = eval {
               $stdout_cut = 1 if length $stdout > $options->{max_bytes};
               $stderr_cut = 1 if length $stderr > $options->{max_bytes};
               my $out = fs_output_text (substr ($stdout, 0, $options->{max_bytes}), $stdout_cut);
               my $err = fs_output_text (substr ($stderr, 0, $options->{max_bytes}), $stderr_cut);
               my @lines = split /(?<=\n)/, $out;
               if (@lines > $options->{max_lines}) {
                  splice @lines, $options->{max_lines};
                  $out = join "", @lines;
                  $stdout_cut = 1;
               }
               @$result{qw(stdout stderr)} = ($out, $err);
               $result->{stdout_truncated} = $stdout_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
               $result->{stderr_truncated} = $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
               $result->{truncated} = $stdout_cut || $stderr_cut || $timed_out ? JSON::XS::true : JSON::XS::false;
               1
            };
            return $req->error ($@) unless $ok;
            $req->reply (fs_result $result, exists $result->{filter_error});
         };

         return $finish->() unless exists $options->{grep};

         {
            my $ok = eval { $stdout = AnyEvent::MCP::utf8enc (fs_output_text $stdout, $stdout_cut); 1 };
            return $req->error ($@) unless $ok;
         }

         # regex execution stays in a timed worker, outside the broker's event loop.
         my @filter = ((fs_sandbox $workdir, $grants), $grep, "-aP", "--", $options->{grep});
         fs_run $req, \@filter, $stdout, 5, 1048576, 0, sub {
            my ($success, $filtered) = @_;
            if (!$success || $filtered->{exit} > 1 || $filtered->{signal} || $filtered->{timed_out}) {
               my $error = $success ? $filtered->{stderr} : $filtered;
               $error = eval { fs_output_text (substr ($error, 0, 4096), 1) } || "no diagnostic";
               $result->{filter_error} = "stdout filter failed: $error";
               $stdout = "";
               $stdout_cut = 1;
            } else {
               $stdout = $filtered->{stdout};
               $stdout_cut ||= $filtered->{truncated};
            }
            $finish->();
         };
      };
}

# wrap raw text as an MCP text result.
sub fs_text_result {
   my ($text, $failed) = @_;

   my $response = {
      content => [{
         type => "text",
         text => $text,
      }],
   };

   $response->{isError} = JSON::XS::true if $failed;

   $response
}

# wrap a Perl value as an MCP text result.
sub fs_result {
   my ($result, $failed) = @_;

   my $response = fs_text_result (JSON::XS->new->encode ($result), $failed);
   $response->{structuredContent} = $result;

   $response
}

mcp_tool workdirs =>
   "List workdirs, VCS markers (remote snapshot at startup), available VCS clients, sandbox grants, trusted mounts, runtime paths.",
   {
      type                 => "object",
      properties           => {},
      additionalProperties => JSON::XS::false,
   },
   sub {
      my ($req, $args) = @_;

      AE::log debug => "fs workdirs";

      # report metadata markers, not an inferred repository for the tree.
      my %marker = (cvs => "CVS", git => ".git", hg => ".hg", svn => ".svn");
      my %workdir_vcs = map {
         my $i = $_;
         ($workdir_identity[$i] => $remote ? $remote_vcs_marker[$i] : [grep {
            lstat "$workdir[$i]/$marker{$_}" && (-d _ || -l _ || ($_ eq "git" && -f _))
         } sort keys %marker])
      } 0 .. $#workdir;

bin/mcp-fs  view on Meta::CPAN


      my ($dir, $name);

      if (!length $relative) {
         ($name) = $full_path =~ m{([^/]*)\z};
      } else {
         ($dir, $name) = $relative =~ m{\A(?:(.*)/)?([^/]*)\z};
         $dir //= "";

         if (!defined $directory or $directory ne $dir) {
            push @line, "/" . (escape_path $dir);
            $directory = $dir;
         }
      }

      $name = escape_path $name;
      push @line, $type eq "f"
         ? (join "\t", $type, (format_iec_number $size), $name)
         : (join "\t", $type, $name);
   }

   push @line, "!truncated" if $truncated;

   join "", map "$_\n", @line
}

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

   my $tool = $recurse ? "find" : "list";

   my ($workdir, $identity) = fs_workdir $args->{workdir};
   my $path = fs_path $workdir, length $args->{path} ? $args->{path} : ".";
   my $limit = $args->{limit} // 200;
   $limit <= 1000
      or die "invalid limit\n";

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

            push @record, [$type, $size, $full_path];
         }

         $failure ||= "incomplete $tool output\n"
            if $eof && length $handle->{rbuf} && !$truncated;
         $handle->{rbuf} = "" if $failure or $truncated;
         $failure || $truncated
      },
      sub {
         my ($handle) = @_;
         my $remaining = 65536 - length $stderr;
         $stderr .= substr $handle->{rbuf}, 0, $remaining if $remaining > 0;
         $handle->{rbuf} = "";
         0
      },
      sub {
         my ($status, $timed_out, $io_failure) = @_;
         return if $req->{finished};

         my $result;
         my $ok = eval {
            die "$tool timed out\n" if $timed_out;
            die $failure || $io_failure if $failure || $io_failure;

            if (($status >> 8 or $status & 127) and !$truncated) {
               my $error = eval { AnyEvent::MCP::utf8dec $stderr };
               $error = "non-UTF-8 error output" if $@;
               die "$tool failed (exit " . ($status >> 8) . ", signal " . ($status & 127) . "): $error\n";
            }

            $result = fs_text_result (format_path_listing $path, \@record, $truncated);
            1
         };

         if ($ok) {
            $req->reply ($result);
         } else {
            $req->error ($@);
         }
      };
}

$find && mcp_tool list =>
   "List immediate entries; no symlink following. "
   . "Text format: /relative-directory headers; f<TAB>approx-size<TAB>name for files; "
   . "TYPE<TAB>name for l/p/s/b/c/? nodes. "
   . "Size suffixes k/M/G/T/P use IEC powers (1024); "
   . "!truncated means limit exceeded. Names escape backslash/newline.",
   {
      type                 => "object",
      properties           => {
         path   => {
            type        => "string",
            description => "Directory; omitted/empty = .",
         },
         limit  => {
            type    => "integer",
            minimum => 1,
            maximum => 1000,
            default => 200,
         },
         workdir => $workdir_schema,
         reason => {
            type        => "string",
            description => "Why access needed.",
         },
      },
      additionalProperties => JSON::XS::false,
   },
   sub {
      fs_list_find $_[0], $_[1], 0
   }
;

$find && mcp_tool find =>
   "Find non-directory entries recursively by literal basename substring; no symlink following. Output as list.",
   {
      type                 => "object",
      properties           => {
         path   => {
            type        => "string",
            description => "Search root; omitted/empty = .",
         },
         name   => {
            type        => "string",
            minLength   => 1,

bin/mcp-fs  view on Meta::CPAN

      my ($req, $args) = @_;

      my $encoding = $args->{encoding} // "utf-8";
      $encoding =~ /\A(?:utf-8|latin1|base64)\z/ or die "invalid read-lines encoding\n";

      my ($workdir, $identity) = fs_workdir $args->{workdir};
      my $path = fs_path $workdir, $args->{path};
      my @range = map {
         my ($start, $end) = /\A([1-9]\d*)(?:,([1-9]\d*))?\z/
            or die "invalid line range\n";
         $end //= $start;
         $start <= $end
            or die "invalid line range\n";
         [$_, $start, $end]
      } @{$args->{ranges}};

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

      AE::log debug => join " ", "fs read-lines", $path, map $_->[0], @range;

      my (@result, $truncated);
      my $remaining = 1 << 20;
      my $next;
      $next = sub {
         unless (@range) {
            undef $next;
            my @content;
            for my $i (0 .. $#result) {
               my ($range, $body) = @{$result[$i]};
               my $header = "[range=$range";
               $header .= " truncated=1" if $truncated && $i == $#result;
               push @content,
                  { type => "text", text => "$header]" },
                  { type => "text", text => $body };
            }
            push @content, { type => "text", text => "[truncated=1]" }
               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)) {
               $truncated = 1;
               @range = ();
            }
            $next->();
         };
      };

      $next->();
   }
;

my $file_write = q{#perl
   my ($path, $offset, $data) = @ARGV;

   use Fcntl qw(O_WRONLY O_CREAT);
   sysopen my $fh, $path, O_WRONLY | O_CREAT, 0666 or return 0, "open: $!";

   binmode $fh;
   defined sysseek $fh, $offset, 0 or return 0, "seek: $!";
   my $n = syswrite $fh, $data;
   defined $n or return 0, "write: $!";

   (1, "$n")
};

$perl && mcp_tool file_write =>
   "Write up to 1 MiB Base64-decoded bytes at offset; no truncation. Returns {bytes: INTEGER} or {error: STRING} on filesystem failure.",
   {
      type                 => "object",
      properties           => {
         path    => {
            type => "string",
         },
         offset  => {
            type    => "integer",
            minimum => 0,
            default => 0,
         },
         data    => {
            type => "string",

bin/mcp-fs  view on Meta::CPAN


      for (split /\n/, $output) {
         if (/^Hunk #(\d+) (succeeded|FAILED|ignored) at (-?\d+)(?: with fuzz (\d+))?(?: \(offset (-?\d+) lines?\))?\.\z/) {
            push @hunks, [0 + $1, $2 eq "succeeded", 0 + $4, 0 + $5];
         } elsif (!length
            || /^Hmm\.\.\. +Looks like a unified diff to me\.\.\.\z/
            || /^The text leading up to this was:\z/
            || /^-+\z/ || /^\|/
            || /^patching file / || /^checking file /
            || /^Using Plan [AB]\.\.\.\z/ || /^done\z/) {
            # GNU patch --verbose framing.
         } else {
            push @unparsed, $_;
         }
      }

      $status == 0
         or die "patch failed (wait status $status):\n$output";
      @unparsed == 0
         or die "patch: unrecognized output:\n" . (join "\n", @unparsed) . "\n";
      @hunks == @max_offset && @hunks
         or die "patch: expected " . @max_offset . " hunks, got " . @hunks . "\n";

      for my $i (0 .. $#hunks) {
         my ($number, $success, $fuzz, $offset) = @{$hunks[$i]};

         $number == $i + 1
            or die "patch: unexpected hunk number $number\n";
         $success
            or die "patch: hunk $number failed\n";
         !$fuzz
            or die "patch: hunk $number used fuzz $fuzz\n";
         abs ($offset) <= $max_offset[$i]
            or die "patch: hunk $number offset $offset exceeds $max_offset[$i]\n";
      }
   };

   my $run_patch = sub {
      my ($newname, $path, $diff) = @_;

      my ($errfh, $errname) = $create_tempfile->("/tmp/mcp-fs~~patch~~");
      $errfh
         or return undef, $errname;

      local $ENV{LC_ALL} = "C";
      open my $write, "|-", "sh", "-c",
         q{exec "$4" --unified --verbose --binary --batch --forward --get=0 --fuzz=0 --reject-file=- --no-backup-if-mismatch -o "$2" "$1" >"$3" 2>&1},
         "--", $path, $newname, $errname, $patch
         or return undef, "open patch pipe: $!";

      my $write_error;
      {
         print $write $diff
            or $write_error = "write patch: $!";
         close $write;
      }

      my $status = $?;

      unlink $errname
         or return undef, "unlink patch stderr: $!";
      defined sysseek $errfh, 0, 0
         or return undef, "seek patch stderr: $!";
      my $output = do { local $/; <$errfh> };
      $output = "" unless defined $output;
      $output =~ s/\s+\z//;

      return undef, $write_error
         if $write_error and !$status;

      $status, $output
   };

   my $replace_file = sub {
      my ($path, $before, $newfh, $newname) = @_;

      chown $before->[4], $before->[5], $newfh;
      chmod $before->[2], $newfh;

      my @after = lstat $path;
      @after
         or return undef, "lstat: $!";
      (join "\0", @$before[0, 1, 2, 3, 4, 5, 7, 9, 10])
         eq (join "\0", @after[0, 1, 2, 3, 4, 5, 7, 9, 10])
         or return undef, "file changed while applying patch";
      my @new = stat $newfh;
      $after[3] == 1
         or return undef, "refusing to replace multiply-linked file";
      (join "\0", @after[2, 4, 5]) eq (join "\0", @new[2, 4, 5])
         or return undef, "cannot preserve file metadata";

      rename $newname, $path
         or return undef, "rename: $!";

      $new[7], undef
   };

   my @before = lstat $path;
   @before
      or return 0, "lstat: $!";
   -f _
      or return 0, "not a regular file";

   my ($newfh, $newname) = $create_tempfile->("$path~~new~~");
   $newfh
      or return 0, $newname;

   my ($status, $output) = $run_patch->($newname, $path, $diff);
   unless (defined $status) {
      unlink $newname;
      return 0, $output
   }

   unless (eval { $check_patch_output->($status, $output, @max_offset); 1 }) {
      my $error = $@;
      unlink $newname;
      return 0, $error
   }

   my ($bytes, $error) = $replace_file->($path, \@before, $newfh, $newname);
   unlink $newname unless defined $bytes;
   defined $bytes
      ? (1, "$bytes")

bin/mcp-fs  view on Meta::CPAN

         },
         limit   => {
            type        => "integer",
            minimum     => 1,
            maximum     => 1000,
            default     => 200,
            description => "Max matching lines.",
         },
         workdir => $workdir_schema,
         reason  => {
            type        => "string",
            description => "Why access needed.",
         },
      },
      required             => ["pattern"],
      additionalProperties => JSON::XS::false,
   },
   sub {
      my ($req, $args) = @_;

      my ($workdir, $identity) = fs_workdir $args->{workdir};
      my $path = fs_path $workdir, length $args->{path} ? $args->{path} : ".";
      my $mode = $args->{mode} // "fixed";
      $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/sh", "-c", q{"$@" || [ "$?" -eq 1 ]}, "sh",
         $grep, ($mode eq "pcre" ? "-P" : "-F"),
         "-I", "-H", "-n", "--color=never", "-e", $pattern,
         "{}", "+",
      );

      fs_run $req, \@command, "", 30, 1024 * 1024, $limit, sub {
         my ($success, $result) = @_;

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

         my $response;
         my $ok = eval {
            my $stdout = AnyEvent::MCP::utf8dec $result->{stdout};
            my $stderr = AnyEvent::MCP::utf8dec $result->{stderr};

            if (($result->{exit} or $result->{signal})
                and !$result->{truncated} and !$result->{timed_out}) {
               die "grep failed (exit $result->{exit}, signal $result->{signal}): $stderr\n";
            }

            $response = {
               stdout    => $stdout,
               stderr    => $stderr,
               timed_out => $result->{timed_out},
               truncated => $result->{truncated},
            };
            1
         };
         return $req->error ($@)
            unless $ok;

         $req->reply (fs_result $response);
      };
   }
;

my $stat = q{#perl
   map {
      my @s = lstat $_;

      pack "(w/a*)*", (@s
         ? (1, (-l _ ? "link" : -d _ ? "directory" : -f _ ? "file" : "other"), @s)
         : (0, "lstat: $!"))
   } @ARGV
};

$perl && mcp_tool stat =>
   "lstat up to 100 paths; no symlink following.",
   {
      type                 => "object",
      properties           => {
         paths  => {
            type     => "array",
            items    => {
               type => "string",
            },
            minItems => 1,
            maxItems => 100,
         },
         workdir => $workdir_schema,
         reason => {
            type        => "string",
            description => "Why access needed.",
         },
      },
      required             => ["paths"],
      additionalProperties => JSON::XS::false,
   },
   sub {
      my ($req, $args) = @_;

      my ($workdir, $identity) = fs_workdir $args->{workdir};
      ARRAY:: eq ref $args->{paths} and @{$args->{paths}} and @{$args->{paths}} <= 100
         or die "stat needs 1..100 paths\n";
      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;
         for my $i (0 .. $#paths) {
            my ($ok, @s) = unpack "(w/a*)*", $result->[$i];

            if ($ok) {
               my $type = shift @s;
               push @result, +{
                  path  => $paths[$i],
                  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 =>
   "Run argv " . ($bwrap ? "in bubblewrap. " : "UNSANDBOXED with full host-user privileges. ")
   . ($bwrap ? "Private /tmp by default (gone after exec); use for temp files/IPC. shared-tmp exposes HOST /tmp (sockets/services). Request ONLY for HOST /tmp, NOT ordinary temp/IPC. " : "")
   . "stdin_encoding: utf-8 (default), latin1 or base64; max 4 MiB decoded. "
   . "stdout/stderr UTF-8, captured to 1 MiB each; max_lines/max_bytes bound response. Optional grep: PCRE stdout filter after capture; stderr unfiltered. Reports capture truncation. "
   . "Explicit sandbox_grants replace default workdir-read. Exit/signal/timeout are normal results, not tool errors. No command-prefix safety classification. Timeout >300 s requires "
   . "long-running grant; max six hours.",
   {
      type       => "object",
      properties => {
         %output_schema,
         workdir => $workdir_schema,
         argv => {
            type     => "array",
            items    => { type => "string" },
            minItems => 1,
         },
         sandbox_grants => {
            type        => "array",
            description => "Providing sandbox_grants (even []) replaces this default entirely; otherwise workdir-read under bubblewrap. Without bubblewrap: full host authority. host-proc unavailable under bubblewrap.",
            items       => {
               type => "string",
               enum => [sort keys %sandbox_grant],
            },
         },
         reason => {
            type        => "string",
            description => "Why command needs authority.",
         },
         stdin  => { type => "string" },
         stdin_encoding => {
            type => "string",
            default => "utf-8",
            enum => [qw(utf-8 latin1 base64)],
            description => "stdin bytes: UTF-8 (default), Latin-1 code points U+0000..U+00FF, or canonical Base64; max 4 MiB decoded.",
         },
         timeout => {
            type    => "integer",
            minimum => 1,
            maximum => 21600,
            default => 30,
            description => "Timeout seconds; >300 also requires long-running grant.",
         },
      },
      required             => [qw(argv reason)],
      additionalProperties => JSON::XS::false,
   },
   sub {
      my ($req, $args) = @_;

      my $output = fs_output_options $args;

      ARRAY:: eq ref $args->{argv} and @{$args->{argv}}
         or die "exec needs argv strings without NUL\n";
      for my $arg (@{$args->{argv}}) {
         defined $arg and !ref $arg and $arg !~ /\0/
            or die "exec needs argv strings without NUL\n";
      }
      length $args->{argv}[0] or die "exec needs an executable\n";

      my ($workdir, $identity) = fs_workdir $args->{workdir};
      my $timeout = $args->{timeout} // 30;
      $timeout >= 1 && $timeout <= 21600 && $timeout == int $timeout
         or die "invalid timeout\n";

bin/mcp-fs  view on Meta::CPAN

      } 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";
      my $stdin_detail = $stdin_text;
      if (length $input && $stdin_encoding ne "utf-8") {
         my $preview = substr $input, 0, 4096;
         $preview =~ s/([^\x20-\x5b\x5d-\x7e])/sprintf "\\x{%02X}", ord $1/ge;
         $stdin_detail = "$stdin_encoding stdin: " . length ($input) . " bytes (escaped preview)\n\n" . $preview;
         $stdin_detail .= "\n... (preview limited to 4096 bytes)"
            if length $input > 4096;
      }

      my $coder = JSON::XS->new->canonical;
      my $subject = $coder->encode ($args->{argv});
      my $executable = $coder->encode ($args->{argv}[0]);
      my $command_label = length $subject > 100 ? substr ($subject, 0, 97) . "..." : $subject;
      my $executable_label = $args->{argv}[0];
      $executable_label = substr ($executable_label, 0, 97) . "..."
         if length $executable_label > 100;
      my $granted = fs_require_permission ($req, $identity, {
         tool           => "exec",
         action         => "exec",
         dimensions     => fs_permission_dimensions (fs_grant_workdir ($identity, $sandbox_grants),
            $subject, [
               { label => "Exact command: $command_label", match => $subject },
               { label => "This executable: $executable_label (any arguments)",
                  match => "^\\[\Q$executable\E(?:,.*)?\\]\\z" },
               { label => "any command", match => "^" },
            ]),
         reason         => $args->{reason},
         sandbox_grants => $sandbox_grants,
         (length $input ? (details => { "View stdin" => $stdin_detail }) : ()),
      });

      $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. "
      . "Returns exit/signal, bounded stdout/stderr, truncation flags. "
      . "grep filters stdout via PCRE after 1 MiB capture; max_lines/max_bytes bound output. "
      . "Trusts VCS client/config; sandbox enforces approved filesystem/network grants.",
      {
         type => "object",
         properties => {
            workdir => $workdir_schema,
            cwd => { type => "string", default => ".",
               description => "cwd relative to workdir; empty = .; must stay inside. Mount boundary unchanged." },
            backend => { type => "string", enum => [qw(git svn cvs hg)] },
            files => { type => "array", items => { type => "string" }, default => [] },
            %output_schema,
         },
         required => ["backend"],
         additionalProperties => JSON::XS::false,
      },
      sub {
         my ($req, $args) = @_;

         my $backend = $args->{backend};
         defined $backend && !ref $backend && $backend =~ /\A(?:git|svn|cvs|hg)\z/
            or die "backend must be git, svn, cvs or hg\n";
         my $program = $vcs_program{$backend}
            or die "$backend executable is unavailable\n";
         my $output = fs_output_options $args;
         my ($workdir, $identity) = fs_workdir $args->{workdir};
         my $cwd = fs_path $workdir, length $args->{cwd} ? $args->{cwd} : ".";
         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,
               ($operation eq "diff" ? ("--internal-diff") : ()), "--", map "$_\@", @files)
            : $backend eq "cvs"
            ? ($program, "-f", $operation,
               ($operation eq "diff" ? ("-u") : $operation eq "log" ? ("-N") : ()),
               "--", @files)
            : ($program, "--noninteractive", "--config", "ui.paginate=never", $operation, "--", @files);

         my @need = fs_effective_grants ("workdir-read",
            ($backend eq "cvs" || $backend eq "svn" && $operation eq "log" ? ("ssh-agent") : ()));
         my $granted = fs_require_permission ($req, $identity, {
            tool => $req->{tool}, action => "vcs-$operation",
            dimensions => fs_permission_dimensions (fs_grant_workdir ($identity, \@need),
               $backend, [
                  { label => "$backend working copies", match => $backend },
                  { label => "all supported VCS clients", match => "^" },
               ]),
            sandbox_grants => \@need, paths => \@paths,
            reason => "$backend $operation in $cwd (workdir $identity)"
               . (@files ? ": " . join (", ", @files) : " (entire working copy)"),
         });
         my $have = $permissions->closure ($granted);
         $have->{$_} or die "permission reduced below $_ for $req->{tool}\n" for @need;

         AE::log debug => join " ", "fs vcs-$operation", $backend, $cwd, @files;

         fs_command $req, $workdir, $granted, \@argv, "", 30, $output, $cwd;
      };
}

mcp_config
   name        => $name,
   idle_exit   => 300,
   server_name    => "mcp-fs",
   server_version => 0,
   on_error    => sub { AE::log info => "mcp-tool $_[1]{tool}: $_[2]" },
   on_start    => sub {
      print STDERR "Permission rules: $permissions->{file}\n"
         if $_[0]->isa ("AnyEvent::MCP::Server::HTTP");
   },
   short_instructions => "Filesystem access: read/edit files, run sandboxed commands, inspect VCS in configured workdirs. Discover tools when working with files.",
   instructions =>
      "Start with workdirs: IDs/paths, mounts, sandbox_grants. "
      . "Select persistent integer ID (listing key, not array position) or configured/resolved path. "
      . "Inactive mappings expire after seven days; IDs may be reused; stale paths fail. "
      . "Paths relative to selected workdir. "
      . "workdir-read/write grant only selected workdir; all-workdirs-read/write grant every workdir. "
      . "all-workdirs-read + workdir-write: read all, write selected only. "
      . "Absolute paths in other workdirs need all-workdirs grants; other absolute paths need home/world grants or shared-tmp for host tmp. "
      . "Multi-path stat stays in selected workdir; rename across paths needs combined grants and may fail EXDEV at mount boundary. "
      . "Symlinks resolve inside granted mounts; overlapping workdir access unspecified. "
      . "Trusted mounts add baseline authority; world-read keeps writable exceptions, world-write ignores them. "
      . "exec requires useful reason and explicit sandbox_grants when needed. "
      . "Prefer vcs-diff/vcs-status/vcs-log for working copies: explicit backend, fixed argv, automatic grants. "
      . "exec/VCS: grep filters stdout via PCRE after capture; max_lines/max_bytes bound output; stderr unfiltered. "
      . "capture_truncated means possible unseen matches.\n";

mcp_start %$server_options, (stdio => $stdio);



( run in 0.838 second using v1.01-cache-2.11-cpan-60884a8df76 )