ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/lib/AnyEvent/MCP.pm
Revision: 1.21
Committed: Tue Oct 13 22:54:21 2026 UTC (6 weeks, 6 days ago) by root
Branch: MAIN
Changes since 1.20: +53 -15 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3     AnyEvent::MCP - Model Context Protocol client/server support
4    
5     =head1 SYNOPSIS
6    
7 root 1.15 use AnyEvent::MCP::Server::Simple;
8 root 1.1
9 root 1.21 my %options = mcp_getoptions ...;
10     mcp_tool ...;
11     mcp_start %options;
12 root 1.1
13     or use the object interface directly:
14    
15 root 1.6 use AnyEvent::MCP::Server ();
16 root 1.1
17     my $server = AnyEvent::MCP::Server->new (...);
18    
19     =head1 DESCRIPTION
20    
21 root 1.21 AnyEvent::MCP provides event-driven Model Context Protocol client and server
22     support. There are three starting points:
23    
24     =over
25    
26     =item Use the included servers without writing Perl
27    
28     L<AnyEvent::MCP::Intro> walks through installation, a first filesystem
29     request, client connections, configuration, permissions and combining
30     servers. Start there if you want the tools to work on your projects.
31    
32     =item Write a small MCP server
33 root 1.17
34 root 1.21 L<AnyEvent::MCP::Server::Simple/TUTORIAL> builds a complete server,
35     calls it, and adds options, replies, permission checks and asynchronous
36     work. Simple handles transport startup and the event loop.
37    
38     =item Embed MCP in an application
39    
40     The modules below expose tool registries, protocol dispatch, requests and
41     transports separately, for applications that need to control their own
42     connections or lifetime.
43    
44     =back
45 root 1.1
46     The usual way to implement a small MCP server is
47     L<AnyEvent::MCP::Server::Simple>, which provides a function-based interface and
48     creates the underlying server objects when a transport such as stdio or HTTP is
49     started.
50    
51     The lower-level object interfaces are intended for applications that need to
52     manage MCP connections, servers or reusable tool registries directly.
53    
54     =head2 MODULES
55    
56 root 1.7 =over
57 root 1.1
58     =item L<AnyEvent::MCP::Server::Simple>
59    
60     Function-based interface for implementing ordinary MCP servers.
61    
62     =item L<AnyEvent::MCP::Server>
63    
64     Object-oriented MCP server interface.
65    
66     =item L<AnyEvent::MCP::Client>
67    
68     Object-oriented MCP client interface.
69    
70     =item L<AnyEvent::MCP::Server::Toolset>
71    
72     Reusable registry of MCP tool declarations.
73    
74     =item L<AnyEvent::MCP::Server::Permissions>
75    
76 root 1.21 Action authorization and sandbox-grant handling for MCP servers.
77 root 1.1
78     =back
79    
80 root 1.4 C<mcp-multibroker> combines downstream HTTP and stdio servers under tool-name
81     prefixes. It uses the same client, server and permission helper facilities,
82     including modern input forwarding and local permission prompts for legacy
83     callers. Run C<mcp-multibroker --help> for command-line syntax; its manual
84     describes authentication and configuration.
85    
86 root 1.16 The interfaces are still being designed. L<AnyEvent::MCP::Intro> explains
87     the installed programs; module-specific POD describes their Perl APIs.
88 root 1.9
89 root 1.16 =head1 TUTORIAL
90 root 1.9
91 root 1.21 For using the servers, see L<AnyEvent::MCP::Intro>. It includes a working
92     first connection, a complete configuration example, saved permissions,
93     multibroker setup and troubleshooting.
94    
95     For writing a server, see L<AnyEvent::MCP::Server::Simple/TUTORIAL>.
96     The tutorial starts with a complete echo server and a client that prints
97     its reply, then develops argument validation, command-line options,
98     result representations, permission retries and cancellable asynchronous
99     work. The Simple function reference follows it.
100    
101     For custom dispatch and reusable tool registries, see
102     L<AnyEvent::MCP::Server::Toolset/REQUEST AND TOOL WORKFLOW> and
103     L<AnyEvent::MCP::Server>. The client modules describe calling servers
104     from your own application.
105 root 1.9
106 root 1.1
107 root 1.2 =head1 GLOBAL CONFIGURATION
108    
109     The shared per-user configuration is C<$XDG_CONFIG_HOME/anyevent-mcp/global.ini>,
110     or C<$HOME/.config/anyevent-mcp/global.ini> when XDG_CONFIG_HOME is unset.
111     L<AnyEvent::MCP::Config> loads and holds it; loading this module does not access
112     configuration files.
113    
114     The file is UTF-8 and uses sections with single-line C<key = value> pairs.
115     Values are unquoted strings. Blank lines and whole-line comments beginning
116     with C<#> or C<;> are ignored; inline comment characters remain part of the
117     value. Later occurrences of a key replace earlier ones in the same section.
118    
119     [global]
120     secret = ...128 hexadecimal digits...
121    
122 root 1.18 [instance example]
123 root 1.11 bind = 127.0.0.1:31740
124 root 1.13 tokens = first-token,second-token
125 root 1.2
126 root 1.21 [program mcp-fs]
127     mount.opt = ro:/opt
128 root 1.2
129     Section names are unrestricted. Application-specific sections, including
130     exports, utility paths and user settings, are documented by their applications.
131    
132     C<[global]> holds C<secret>, a 64-byte master key encoded as 128 hexadecimal
133     digits. The file must be owned by the current user, with no group or other
134     permissions. A missing secret is generated automatically on first configuration
135     access and saved when possible. Existing secrets are never replaced implicitly.
136     An invalid secret is an error.
137    
138     If saving fails, Config warns and retains the secret in memory. Credentials
139     then remain stable only for that process; other processes cannot derive the
140     same credentials. If randomness is unavailable, supply a securely generated
141     secret in the file.
142    
143 root 1.18 C<[instance NAME]> holds named-server settings.
144 root 1.11 HTTP-capable executables use C<--name NAME> to select these settings, with
145     the executable basename as the default name. Names consist of an ASCII
146     letter or underscore followed by ASCII letters, digits, underscores or
147     hyphens. Their C<--bind ADDRESS[:PORT]> overrides the configured C<bind>.
148     The default bind address is IPv4 loopback with a port derived from the name
149     and master secret in the range 16384..32767; C<:0> requests an ephemeral
150 root 1.12 port. C<--print-url> prints the URL using the first accepted token without
151     listening. Named server settings also include C<path>, C<url_host>,
152     C<url_scheme> and C<tokens>. C<tokens> is a comma-separated list of
153     URL-safe strings. Repeated C<--token TOKEN> options override this list.
154     All accepted tokens work in the URL path or Authorization bearer header.
155     Without configured tokens, one server-specific token is derived.
156 root 1.11
157 root 1.12 C<mcp_start> resolves named settings and requires the selected token for
158     HTTP requests. Explicit tokens replace the derived default.
159 root 1.11 The low-level HTTP transport does not resolve configuration itself.
160 root 1.21 Simple's stdio startup does not access global HTTP configuration.
161     Applications can still load it for their own settings; C<mcp-fs>, for
162     example, reads trusted mount and executable settings even in stdio mode.
163     Browser origins are permitted by default, but must still pass MCP authentication.
164 root 1.3
165 root 1.12 C<[client NAME]> supplies HTTP client defaults: C<url>, C<bearer> and
166     C<timeout>. Clients consult it only when explicitly given a C<name>.
167 root 1.21 An unnamed HTTP client and the low-level HTTP server do not read global
168     configuration. C<mcp_start> resolves a default name and does read it.
169 root 1.3 Explicit constructor arguments take precedence over named defaults.
170    
171     =head1 ENVIRONMENT
172    
173     Project-specific environment variables use the C<PERL_ANYEVENT_MCP_> prefix.
174     C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio> selects stdio in Simple.
175 root 1.11 C<PERL_ANYEVENT_MCP_MULTIBROKER_ALIAS> names a multibroker routing prefix;
176     it does not change the service-instance name.
177 root 1.3 C<PERL_ANYEVENT_MCP_PERMISSION_HELPER> selects the external asking executable.
178 root 1.21 C<PERL_ANYEVENT_MCP_PERMISSION_ASK> selects the permission engine's
179     asking default: C<helper>, C<auto> or C<mcp>. See
180     L<AnyEvent::MCP::Intro/Choose where to ask> for the behavior and client
181     requirements.
182 root 1.3 Standard C<HOME> and C<XDG_CONFIG_HOME> keep their standard names.
183 root 1.2
184     =head1 FUNCTIONS
185    
186 root 1.6 =over
187    
188 root 1.10 =item $class = AnyEvent::MCP::json_class
189    
190     Returns C<JSON::XS> if available, otherwise C<JSON::PP>. The caller
191     configures a new coder instance as needed.
192    
193 root 1.8 =item $bytes = AnyEvent::MCP::utf8enc $text
194    
195     Return a UTF-8 byte string for C<$text>, leaving the argument unchanged.
196    
197     =item $text = AnyEvent::MCP::utf8dec $bytes
198    
199     Decode a UTF-8 byte string into characters, dying on invalid UTF-8.
200     The argument is left unchanged. For intentional in-place conversions,
201     use Perl's C<utf8::encode> or C<utf8::decode> directly.
202    
203 root 1.6 =item $bytes = AnyEvent::MCP::random_bytes $length
204 root 1.2
205     Returns exactly C<$length> random bytes. Tries C</dev/urandom>, then an external
206     C<openssl rand> command. No additional random-number module is required.
207     Dies if neither source supplies the requested bytes successfully.
208     C<$length> must be a nonnegative integer; zero returns an empty string.
209    
210 root 1.20 =item $bytes = AnyEvent::MCP::hkdf_sha512_expand $prk, $info, $length
211    
212     Expand a 64-byte pseudorandom key using the HKDF-SHA512 expand step and
213     the byte string C<$info>. Returns C<$length> bytes. This is the B<expand>
214     step only: it does not extract a key from arbitrary input, generate a salt,
215     or derive a master secret. The caller must supply a suitable PRK.
216    
217 root 1.6 =back
218    
219     =head2 PATCH UTILITIES
220    
221 root 1.7 Since applying patches to files is a common task for MCP servers, the
222 root 1.6 following utility functions can be used to ease that job. Together, they
223 root 1.7 define a common patch format (unified diff or a simplified version of it,
224     with fewer requirements to make it easier for the LLM to generate), helpers
225 root 1.6 to apply the patch and a helper to verify if the patch was applied
226     with sufficient precision.
227    
228 root 1.7 Use C<apply_udiff> to normalize, apply and validate a patch in one operation.
229     It writes a separate output file; the caller checks freshness and metadata
230     and commits the result.
231    
232     For an application-specific applier, the workflow is:
233 root 1.6
234     =over
235    
236     =item 1. AnyEvent::MCP::normalize_udiff
237    
238 root 1.7 Returns a unified diff for GNU patch and the permitted hunk offsets.
239    
240     =item 2. Apply the normalized diff
241 root 1.6
242 root 1.7 Run GNU patch with fuzz zero and capture its verbose output.
243 root 1.6
244 root 1.7 =item 3. AnyEvent::MCP::check_patch_output
245    
246     Checks the process status and output against the permitted offsets.
247     C<parse_patch_output> is available separately when only parsing is needed.
248 root 1.5
249 root 1.6 =back
250    
251 root 1.5 =head3 Input format
252    
253 root 1.6 The patch format accepted by normalize_udiff is an extension to the
254     (essentially undocumented) unified diff format.
255    
256 root 1.5 In a hunk header, only the old start C<-N> matters. It is the old-file line
257     of the first hunk body line, including context, not necessarily the first
258     changed line. Counts and the new-file position are ignored and recomputed.
259     Both ordinary headers and the abbreviated form are accepted:
260    
261     @@ -42,99 +123,99 @@
262     @@ -42 @@
263    
264     Optional text after the closing C<@@> is preserved. File headers and other
265     text before the first hunk are preserved; a diff must describe one file.
266    
267     Hunk body lines use the usual prefixes: a space for unchanged context,
268     C<-> for removed lines and C<+> for added lines. The
269     C<\ No newline at end of file> marker is preserved and counts neither side.
270     Trailing empty lines outside the final hunk are discarded.
271    
272 root 1.7 Pure insertion is permitted only at the beginning, using old start C<0>.
273     For example, C<@@ -0 @@> with one added line becomes C<@@ -0,0 +1,1 @@>.
274     An empty old-side range names the line before the insertion: C<-0,0>
275     means before line 1, whereas C<-1,0> would mean after line 1 and is rejected
276     here. Nonempty ranges use one-based line numbers.
277    
278 root 1.5 An insertion elsewhere needs old-side context. Empty hunks are rejected.
279     New positions include the cumulative line-count changes of preceding hunks.
280    
281     =head3 Applying the result
282    
283 root 1.6 The C<normalize_udiff> function does not apply the patch, check file
284     contents or guard against concurrent edits. The caller must supply those
285     checks, if required.
286 root 1.5
287     Context must match exactly: apply with fuzz zero. For each hunk,
288     C<$max_offset> permits relocation by at most the number of distinct old-side
289     lines minus one, or zero for a pure insertion. Repeated old-side lines do
290     not increase this allowance. The applier must enforce these limits; an
291     unrestricted search for matching context can select the wrong occurrence.
292    
293     For live Vim buffers, also require the expected changedtick to match.
294     File-based users need an equivalent check before replacing the file.
295    
296 root 1.6 To work around GNU patch's handling of asymmetric context, the
297     first context line of each hunk is rewritten as an identity
298     removal/addition. The line contents and old/new line counts are
299     unchanged. This is normalization for the patch applier, not a relaxation
300     of context matching.
301 root 1.5
302 root 1.6 =over
303    
304     =item ($diff, $max_offset) = AnyEvent::MCP::normalize_udiff $diff
305    
306     Normalizes a relaxed, single-file unified diff into ordinary unified diff
307     syntax. Returns the normalized C<$diff> and an array reference C<$max_offset>
308     containing the permitted whole-hunk relocation for each hunk, in order.
309     Dies on malformed hunks or when no hunks are found.
310    
311     Here is a suitable description for the diff format, e.g. in a tool
312     definition:
313    
314     Apply a unified diff to one regular file. Hunk counts are recomputed,
315     fuzz is disabled, whole-hunk relocation is limited per hunk by distinct
316     old-side lines. Pure insertion is allowed only at the beginning;
317     elsewhere include old-side context.
318    
319     =item $cv = AnyEvent::MCP::apply_udiff $input, $output, $diff
320    
321     Asynchronously applies the relaxed C<$diff> to the input file C<$input>,
322     writing a separate output file C<$output>. C<$diff> must contain bytes;
323     callers working with characters must encode them for the file themselves.
324    
325     Normalizes the diff, runs GNU patch using C<AnyEvent::Util::run_cmd>, and
326     validates its verbose output with C<check_patch_output>. The command uses
327     batch/forward mode, binary mode and fuzz zero. No shell is involved.
328    
329     C<$output> must not exist. It is reserved with mode 0600; patch runs in its
330     directory so incidental temporary files stay there. Input and output paths
331     are made absolute before starting the command. These must be trusted paths
332     in a directory controlled by the caller.
333    
334     Returns a condition variable. Its C<recv> returns the validated hunk array
335     reference, or throws on command/application failure. Setup failures throw
336     synchronously. Failed or partial output is removed. C<$input> is unchanged.
337    
338     The caller owns committing the successful output and removing it when no
339     longer needed. Freshness checks, metadata preservation, atomic replacement
340     and application-specific permissions also belong to the caller.
341    
342     For your reference, the exact options used are:
343    
344     --verbose --batch --forward --binary --fuzz=0
345     --no-backup-if-mismatch
346     --reject-file=- --output=... -- <inputfile>
347    
348     =item $parsed = AnyEvent::MCP::parse_patch_output $output
349 root 1.5
350     Parses C<LC_ALL=C> GNU patch C<--verbose> output without judging whether
351     the application is acceptable. C<$parsed> has two fields:
352    
353 root 1.6 =over
354 root 1.5
355     =item hunks => [$hunk...]
356    
357     Hunk records in output order. Each record contains C<hunk> (the one-based
358     number), C<success>, C<line> (the reported application line), C<fuzz> and
359     the signed C<offset>. Omitted fuzz and offset are zero. Failed and ignored
360     hunks have false C<success>.
361    
362     =item unparsed => [$line...]
363    
364     Lines not recognized as hunk results or GNU patch's verbose framing.
365     The parser preserves them for callers to interpret or reject.
366    
367     =back
368    
369     Use verbose output: ordinary patch output omits exact-position successes,
370     so it cannot account for every hunk.
371    
372 root 1.6 =item $hunks = AnyEvent::MCP::check_patch_output $status, $output, [$max_offset...]
373 root 1.5
374     Parses C<$output> and validates a complete application. C<$status> is the
375     raw process wait status, as returned by C<waitpid> or
376     C<AnyEvent::Util::run_cmd>, not just the exit code.
377    
378     Requires status zero, no unrecognized output, exactly the expected hunks
379     in numbered order, successful application, fuzz zero and each signed offset
380     within its corresponding absolute limit. C<[$max_offset...]> is the array
381     reference returned by C<normalize_udiff>. At least one hunk is required.
382    
383     Returns the parsed hunk array reference on success; otherwise dies with a
384     diagnostic. This is also suitable for callers running patch inside their
385     own sandbox.
386    
387 root 1.6 =back
388 root 1.5
389 root 1.1 =cut
390    
391     package AnyEvent::MCP;
392    
393     use common::sense;
394     use Digest::SHA ();
395    
396     our $VERSION = '0.0';
397    
398 root 1.10 sub json_class {
399     our $JSON_CLASS ||= eval { require JSON::XS; "JSON::XS" }
400     || do { require JSON::PP; "JSON::PP" };
401     }
402    
403 root 1.8 sub utf8enc($) {
404     my $text = shift;
405    
406     utf8::encode $text;
407     $text
408     }
409    
410     sub utf8dec($) {
411     my $bytes = shift;
412    
413     utf8::decode $bytes
414     or die "invalid UTF-8\n";
415     $bytes
416     }
417    
418 root 1.2 sub random_bytes($) {
419     my ($length) = @_;
420    
421 root 1.19 defined $length && $length =~ /\A[0-9]+\z/
422     or die "Invalid random byte count\n";
423 root 1.2 return "" unless $length;
424    
425     my $bytes = "";
426    
427     if (open my $fh, "<", "/dev/urandom") {
428     binmode $fh;
429     while (length $bytes < $length) {
430     read ($fh, $bytes, $length - length ($bytes), length $bytes)
431     or last;
432     }
433     close $fh;
434    
435     return $bytes if length $bytes == $length;
436     }
437    
438     if (open my $fh, "-|", "openssl", "rand", $length) {
439     binmode $fh;
440     local $/;
441     $bytes = <$fh>;
442     my $success = close $fh;
443    
444     return $bytes
445     if $success && defined $bytes && length $bytes == $length;
446     }
447    
448     die "Cannot obtain $length random bytes from /dev/urandom or openssl rand\n";
449     }
450    
451 root 1.1 sub hkdf_sha512_expand($$$) {
452     my ($prk, $info, $l) = @_;
453    
454 root 1.2 64 == length $prk
455 root 1.19 or die "hkdf_sha512_expand: prk length must be 64 octets";
456 root 1.2
457 root 1.1 my $t = "";
458     my $okm = "";
459     my $i = 0;
460    
461     do {
462     $t = Digest::SHA::hmac_sha512 $t . $info . chr ++$i, $prk;
463     $okm .= $t;
464     } while $l > length $okm;
465    
466     substr $okm, 0, $l
467     }
468    
469 root 1.5 sub normalize_udiff {
470     my $diff = shift;
471     my @line = split /\n/, $diff, -1;
472     my $delta = 0;
473     my $hunks = 0;
474     my @max_offset;
475    
476     pop @line while @line and !length $line[-1];
477    
478     for (my $i = 0; $i < @line; ++$i) {
479     next unless $line[$i] =~ /^@@ /;
480    
481     $line[$i] =~ /^@@ -(\d+)(?:,\d+)?(?: \+\d+(?:,\d+)?)? @@(.*)$/
482     or die "normalize_udiff: bad hunk header '$line[$i]'\n";
483    
484     my ($old_start, $suffix) = ($1, $2);
485     my ($old_count, $new_count) = (0, 0);
486     my %old_line;
487     my $j = $i + 1;
488    
489     # GNU patch mishandles hunks with more prefix than suffix context.
490     # Make the first context line an identity change without losing it.
491     # see https://unix.stackexchange.com/questions/414542/does-patch-work-with-asymmetric-context
492     splice @line, $i + 1, 1, "-$1", "+$1"
493     if $line[$i + 1] =~ /^ (.*)\z/;
494    
495     for (; $j < @line; ++$j) {
496     last if $line[$j] =~ /^@@ /;
497    
498     my $tag = substr $line[$j], 0, 1;
499    
500     if ($tag eq " ") {
501     ++$old_count;
502     ++$new_count;
503     $old_line{substr $line[$j], 1} = 1;
504     } elsif ($tag eq "-") {
505     ++$old_count;
506     $old_line{substr $line[$j], 1} = 1;
507     } elsif ($tag eq "+") {
508     ++$new_count;
509     } elsif ($line[$j] eq "\\ No newline at end of file") {
510     # Marker belongs to the preceding body line and counts neither side.
511     } else {
512     die "normalize_udiff: bad hunk line '$line[$j]'\n";
513     }
514     }
515    
516     $old_count or $new_count
517     or die "normalize_udiff: empty hunk at old line $old_start\n";
518    
519     $old_count or !$old_start
520     or die "normalize_udiff: hunk " . ($hunks + 1)
521     . " needs old-side context for insertion after old line $old_start\n";
522    
523     my $new_start = $old_start + $delta;
524     ++$new_start unless $old_count;
525     --$new_start unless $new_count;
526    
527     $new_start >= 0
528     or die "normalize_udiff: invalid new line $new_start\n";
529    
530     $line[$i] = sprintf "@@ -%d,%d +%d,%d @@%s",
531     $old_start, $old_count, $new_start, $new_count, $suffix;
532    
533     $delta += $new_count - $old_count;
534     ++$hunks;
535     my $max_offset = keys %old_line;
536     --$max_offset
537     if $max_offset;
538     push @max_offset, $max_offset;
539     $i = $j - 1;
540     }
541    
542     $hunks
543     or die "normalize_udiff: no hunks\n";
544    
545     (join ("\n", @line, ""), \@max_offset)
546     }
547    
548     sub parse_patch_output {
549     my ($output) = @_;
550     my (@hunks, @unparsed);
551    
552     for (split /\n/, $output) {
553     if (/^Hunk #(\d+) (succeeded|FAILED|ignored) at (-?\d+)(?: with fuzz (\d+))?(?: \(offset (-?\d+) lines?\))?\.\z/) {
554     push @hunks, {
555     hunk => 0 + $1,
556     success => $2 eq "succeeded",
557     line => 0 + $3,
558     fuzz => 0 + $4,
559     offset => 0 + $5,
560     };
561     } elsif (!length
562     || /^Hmm\.\.\. +Looks like a unified diff to me\.\.\.\z/
563     || /^The text leading up to this was:\z/
564     || /^-+\z/ || /^\|/
565     || /^patching file / || /^checking file /
566     || /^Using Plan [AB]\.\.\.\z/ || /^done\z/) {
567     # GNU patch --verbose framing, not hunk results.
568     } else {
569     push @unparsed, $_;
570     }
571     }
572    
573     { hunks => \@hunks, unparsed => \@unparsed }
574     }
575    
576     sub check_patch_output {
577     my ($status, $output, $max_offset) = @_;
578     my $parsed = parse_patch_output $output;
579     my $hunks = $parsed->{hunks};
580    
581     die "patch failed (wait status $status):\n$output"
582     if $status;
583     die "patch: unrecognized output:\n" . (join "\n", @{$parsed->{unparsed}}) . "\n"
584     if @{$parsed->{unparsed}};
585     die "patch: expected " . @$max_offset . " hunks, got " . @$hunks . "\n"
586     unless @$hunks == @$max_offset && @$hunks;
587    
588     for my $i (0 .. $#$hunks) {
589     my $hunk = $hunks->[$i];
590    
591     die "patch: unexpected hunk number $hunk->{hunk}\n"
592     unless $hunk->{hunk} == $i + 1;
593     die "patch: hunk $hunk->{hunk} failed\n"
594     unless $hunk->{success};
595     die "patch: hunk $hunk->{hunk} used fuzz $hunk->{fuzz}\n"
596     if $hunk->{fuzz};
597     die "patch: hunk $hunk->{hunk} offset $hunk->{offset} exceeds $max_offset->[$i]\n"
598     if abs $hunk->{offset} > $max_offset->[$i];
599     }
600    
601     $hunks
602     }
603    
604     sub apply_udiff {
605     my ($input, $output, $diff) = @_;
606     my ($normalized, $max_offset) = normalize_udiff $diff;
607    
608     require AnyEvent::Util;
609     require File::Spec;
610     require File::Basename;
611     require Fcntl;
612    
613     $input = File::Spec->rel2abs ($input);
614     $output = File::Spec->rel2abs ($output);
615     my $directory = File::Basename::dirname ($output);
616    
617     sysopen my $fh, $output, Fcntl::O_WRONLY () | Fcntl::O_CREAT () | Fcntl::O_EXCL (), 0600
618     or die "$output: $!\n";
619     close $fh or do { my $error = $!; unlink $output; die "$output: $error\n" };
620    
621     my $cv = AE::cv ();
622     my $log;
623     my $process = eval {
624     AnyEvent::Util::run_cmd ([
625     "patch", "--verbose", "--batch", "--forward", "--binary", "--fuzz=0",
626     "--no-backup-if-mismatch", "--reject-file=-", "--output=$output", "--", $input,
627     ],
628     "<" => \$normalized,
629     ">" => \$log,
630     close_all => 1,
631     on_prepare => sub {
632     $ENV{LC_ALL} = "C";
633     chdir $directory or die "$directory: $!\n";
634     defined POSIX::dup2 (1, 2) or die "dup2: $!\n";
635     },
636     );
637     };
638    
639     if ($@) {
640     my $error = $@;
641     unlink $output;
642     die $error;
643     }
644    
645     $process->cb (sub {
646     my $hunks;
647     eval { $hunks = check_patch_output $_[0]->recv, $log, $max_offset; 1 } or do {
648     my $error = $@;
649     unlink $output;
650     $cv->croak ($error);
651     return;
652     };
653    
654     $cv->send ($hunks);
655     });
656    
657     $cv
658     }
659    
660 root 1.1 sub _clean_text($) {
661     my ($text) = @_;
662    
663     my ($prefix) = (join "\n", grep /\S/, split /\n/, $text)
664     =~ /\A([ \t]*)[^\n]*(?:\n\1[^\n]*)*\z/;
665    
666     $text =~ s/^\Q$prefix\E//mg;
667     $text =~ s/\A\s+//;
668     $text =~ s/\s+\z//;
669     $text
670     }
671    
672     package AnyEvent::MCP::Base;
673    
674     sub new {
675     my ($class, %kv) = @_;
676 root 1.19
677 root 1.1 bless \%kv, $class
678     }
679    
680     sub event {
681     my ($self, $event, @args) = @_;
682 root 1.19
683 root 1.1 ($self->{"on_$event"} or return)->($self, @args)
684     }
685    
686     =head1 SEE ALSO
687    
688 root 1.16 L<AnyEvent::MCP::Intro>, L<AnyEvent::MCP::Server::Simple>,
689 root 1.1 L<AnyEvent>, L<https://modelcontextprotocol.io/>
690    
691     =head1 AUTHOR
692    
693     The main author of this module is OpenAI ChatGPT.
694    
695     Additional guidance received by:
696    
697     Marc Lehmann <schmorp@schmorp.de>
698     http://home.schmorp.de/
699    
700     =cut
701    
702     1
703