AnyEvent-MCP
view release on metacpan or search on metacpan
lib/AnyEvent/MCP.pm view on Meta::CPAN
instance name and master secret in the range 16384..32767; C<:0> requests an ephemeral
port. C<--print-url> prints enabled user URLs, and C<--print-url=USER>
prints just the chosen user's URLs, without listening.
Named server settings also include C<path>, C<url_host>,
C<url_scheme> and C<tokens>. C<tokens> is a comma-separated list of
URL-safe strings. Repeated C<--token TOKEN> options override this list.
Automatic permission defaults use C<auto-rule.SUFFIX = allow|deny
TOOL[,ACTION[,CAPABILITY]]> in program/instance sections, sorted by suffix.
Instance entries override matching keys or suppress them with empty values.
Command-line automatic rules are evaluated before configured defaults.
All accepted tokens work in the URL path or Authorization bearer header.
Without configured tokens, enabled users in C<[global]>,
C<[program PROGRAM]> and C<[instance NAME]> each have derived credentials,
with later scopes overriding earlier ones. A missing global
C<user.default> is equivalent to C<user.default = 1>. Positive
generations are enabled; negative generations are revoked and retain
their counter for later rotation. Zero is invalid. The principal used
for permissions is C<global:USER>, C<program:USER>, or C<instance:USER>.
All derivation contexts have the C<anyevent-mcp> namespace prefix.
The C<connect_user> setting (default: C<default>) chooses which user's
token may attach Vim editor, browser WebSocket or reverse-MCP connections.
Disabling that user prevents new auxiliary connections, without stopping
other enabled users from making MCP requests.
C<mcp_start> resolves named settings and requires the selected token for
HTTP requests. Explicit tokens replace the derived managed users.
The low-level HTTP transport does not resolve configuration itself.
Simple's stdio startup does not access global HTTP configuration.
Applications can still load it for their own settings; C<mcp-fs>, for
example, reads trusted mount and executable settings even in stdio mode.
Browser origins are permitted by default, but must still pass MCP authentication.
C<[client NAME]> supplies HTTP client defaults: C<url>, C<bearer> and
C<timeout>. Clients consult it only when explicitly given a C<name>.
An unnamed HTTP client and the low-level HTTP server do not read global
configuration. C<mcp_start> resolves a default name and does read it.
Explicit constructor arguments take precedence over named defaults.
=head1 ENVIRONMENT
Project-specific environment variables use the C<PERL_ANYEVENT_MCP_> prefix.
C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio> selects stdio in Simple.
C<PERL_ANYEVENT_MCP_MULTIBROKER_ALIAS> names a multibroker routing prefix;
it does not change the service-instance name.
C<PERL_ANYEVENT_MCP_PERMISSION_HELPER> selects the external asking executable.
C<PERL_ANYEVENT_MCP_PERMISSION_ASK> selects the permission engine's
asking default: C<helper>, C<tty>, C<yad>, C<auto>, C<mcp> or C<none>. See
L<AnyEvent::MCP::Intro/Choose where to ask> for the behavior and client
requirements.
Standard C<HOME> and C<XDG_CONFIG_HOME> keep their standard names.
=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
=head2 PATCH UTILITIES
Since applying patches to files is a common task for MCP servers, the
following utility functions can be used to ease that job. Together, they
define a common patch format (unified diff or a simplified version of it,
with fewer requirements to make it easier for the LLM to generate), helpers
to apply the patch and a helper to verify if the patch was applied
with sufficient precision.
Use C<apply_udiff> to normalize, apply and validate a patch in one operation.
It writes a separate output file; the caller checks freshness and metadata
and commits the result.
For an application-specific applier, the workflow is:
=over
=item 1. AnyEvent::MCP::normalize_udiff
Returns a unified diff for GNU patch and the permitted hunk offsets.
=item 2. Apply the normalized diff
Run GNU patch with fuzz zero and capture its verbose output.
=item 3. AnyEvent::MCP::check_patch_output
Checks the process status and output against the permitted offsets.
C<parse_patch_output> is available separately when only parsing is needed.
=back
=head3 Input format
The patch format accepted by normalize_udiff is an extension to the
(essentially undocumented) unified diff format.
In a hunk header, only the old start C<-N> matters. It is the old-file line
of the first hunk body line, including context, not necessarily the first
changed line. Counts and the new-file position are ignored and recomputed.
Both ordinary headers and the abbreviated form are accepted:
@@ -42,99 +123,99 @@
@@ -42 @@
Optional text after the closing C<@@> is preserved. File headers and other
text before the first hunk are preserved; a diff must describe one file.
Hunk body lines use the usual prefixes: a space for unchanged context,
C<-> for removed lines and C<+> for added lines. The
lib/AnyEvent/MCP.pm view on Meta::CPAN
reference returned by C<normalize_udiff>. At least one hunk is required.
Returns the parsed hunk array reference on success; otherwise dies with a
diagnostic. This is also suitable for callers running patch inside their
own sandbox.
=back
=head1 SMALL UTILITIES
=over
=item $name = AnyEvent::MCP::instance_name ($name)
Validate an instance name, defaulting to C<default> if undefined. Names
start with an ASCII letter, digit or underscore, followed by letters,
digits, underscores, hyphens, dots, C<@> and C<+>. This intentionally
small character set is convenient to use unquoted in a shell.
=item $lock = AnyEvent::MCP::file_lock ($file)
Create the parent directory and state file if necessary, and obtain an
exclusive advisory lock. If another cooperating writer atomically replaced
the pathname while waiting, retry on the new inode. Keep the handle alive
through reading, modifying and replacing the file.
=item AnyEvent::MCP::file_replace ($file, $bytes)
With the C<file_lock> handle held by the caller, write a complete new version
to a temporary file beside C<$file>, preserve the existing file mode and
atomically rename it over C<$file>. Remove the temporary on failure.
This provides atomic visibility, not crash durability; all writers must
follow the locking protocol.
=item $text = AnyEvent::MCP::file_load ($file, $fh)
Load a UTF-8 text file as Unicode characters, rejecting invalid UTF-8.
Optionally read from an already open filehandle C<$fh>, leaving it open
and advancing its position. The caller retains responsibility for locking.
=item AnyEvent::MCP::file_save ($file, $text)
Encode Unicode text as UTF-8 and atomically replace C<$file> using
C<file_replace>. As with C<file_replace>, the caller holds C<file_lock>.
=back
=cut
package AnyEvent::MCP;
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/
or die "Invalid MCP server name '$name'\n";
$name
}
sub file_lock {
my ($file) = @_;
require File::Path;
require File::Basename;
require Fcntl;
require Errno;
File::Path::mkpath (File::Basename::dirname ($file), 0, 0700);
while (1) {
my $fh;
sysopen $fh, $file, Fcntl::O_RDWR () | Fcntl::O_CREAT () | Fcntl::O_EXCL (), 0600 or do {
die "$file: $!\n" unless $! == Errno::EEXIST ();
sysopen $fh, $file, Fcntl::O_RDWR () or die "$file: $!\n";
};
my @stat = stat $fh;
flock $fh, Fcntl::LOCK_EX () or die "$file: $!\n";
my @current = stat $file;
return $fh if @current && $stat[0] == $current[0] && $stat[1] == $current[1];
die "$file: $!\n" unless @current || $! == Errno::ENOENT ();
close $fh;
}
}
sub file_replace {
my ($file, $bytes) = @_;
require Fcntl;
require Errno;
my @stat = stat $file;
die "$file: $!\n" unless @stat || $! == Errno::ENOENT ();
my $temporary = "$file.$$~";
sysopen my $fh, $temporary, Fcntl::O_WRONLY () | Fcntl::O_CREAT () | Fcntl::O_EXCL (), 0600
or die "$temporary: $!\n";
my $ok = eval {
print {$fh} $bytes or die "$temporary: $!\n";
if (@stat) {
my $mode = $stat[2] & 07777;
chmod $mode, $fh or die "$temporary: $!\n";
}
close $fh or die "$temporary: $!\n";
rename $temporary, $file or die "$file: $!\n";
1
};
my $error = $@;
unlink $temporary unless $ok;
die $error unless $ok;
}
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;
my $bytes = "";
if (open my $fh, "<", "/dev/urandom") {
binmode $fh;
while (length $bytes < $length) {
read $fh, $bytes, $length - length $bytes, length $bytes
or last;
}
close $fh;
return $bytes if length $bytes == $length;
}
if (open my $fh, "-|", "openssl", "rand", $length) {
binmode $fh;
local $/;
$bytes = <$fh>;
my $success = close $fh;
return $bytes
if $success && defined $bytes && length $bytes == $length;
}
die "Cannot obtain $length random bytes from /dev/urandom or openssl rand\n";
}
sub normalize_udiff {
my $diff = shift;
my @line = split /\n/, $diff, -1;
my $delta = 0;
my $hunks = 0;
my @max_offset;
pop @line while @line and !length $line[-1];
for (my $i = 0; $i < @line; ++$i) {
next unless $line[$i] =~ /^@@ /;
$line[$i] =~ /^@@ -(\d+)(?:,\d+)?(?: \+\d+(?:,\d+)?)? @@(.*)$/
or die "normalize_udiff: bad hunk header '$line[$i]'\n";
my ($old_start, $suffix) = ($1, $2);
my ($old_count, $new_count) = (0, 0);
my %old_line;
my $j = $i + 1;
# GNU patch mishandles hunks with more prefix than suffix context.
# make the first context line an identity change without losing it.
# see https://unix.stackexchange.com/questions/414542/does-patch-work-with-asymmetric-context
splice @line, $i + 1, 1, "-$1", "+$1"
( run in 0.605 second using v1.01-cache-2.11-cpan-234fa220139 )