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