ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/lib/AnyEvent/MCP.pm
Revision: 1.18
Committed: Sun Oct 11 15:29:10 2026 UTC (5 weeks, 1 day ago) by root
Branch: MAIN
Changes since 1.17: +2 -2 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.6 =back
173    
174     =head2 PATCH UTILITIES
175    
176 root 1.7 Since applying patches to files is a common task for MCP servers, the
177 root 1.6 following utility functions can be used to ease that job. Together, they
178 root 1.7 define a common patch format (unified diff or a simplified version of it,
179     with fewer requirements to make it easier for the LLM to generate), helpers
180 root 1.6 to apply the patch and a helper to verify if the patch was applied
181     with sufficient precision.
182    
183 root 1.7 Use C<apply_udiff> to normalize, apply and validate a patch in one operation.
184     It writes a separate output file; the caller checks freshness and metadata
185     and commits the result.
186    
187     For an application-specific applier, the workflow is:
188 root 1.6
189     =over
190    
191     =item 1. AnyEvent::MCP::normalize_udiff
192    
193 root 1.7 Returns a unified diff for GNU patch and the permitted hunk offsets.
194    
195     =item 2. Apply the normalized diff
196 root 1.6
197 root 1.7 Run GNU patch with fuzz zero and capture its verbose output.
198 root 1.6
199 root 1.7 =item 3. AnyEvent::MCP::check_patch_output
200    
201     Checks the process status and output against the permitted offsets.
202     C<parse_patch_output> is available separately when only parsing is needed.
203 root 1.5
204 root 1.6 =back
205    
206 root 1.5 =head3 Input format
207    
208 root 1.6 The patch format accepted by normalize_udiff is an extension to the
209     (essentially undocumented) unified diff format.
210    
211 root 1.5 In a hunk header, only the old start C<-N> matters. It is the old-file line
212     of the first hunk body line, including context, not necessarily the first
213     changed line. Counts and the new-file position are ignored and recomputed.
214     Both ordinary headers and the abbreviated form are accepted:
215    
216     @@ -42,99 +123,99 @@
217     @@ -42 @@
218    
219     Optional text after the closing C<@@> is preserved. File headers and other
220     text before the first hunk are preserved; a diff must describe one file.
221    
222     Hunk body lines use the usual prefixes: a space for unchanged context,
223     C<-> for removed lines and C<+> for added lines. The
224     C<\ No newline at end of file> marker is preserved and counts neither side.
225     Trailing empty lines outside the final hunk are discarded.
226    
227 root 1.7 Pure insertion is permitted only at the beginning, using old start C<0>.
228     For example, C<@@ -0 @@> with one added line becomes C<@@ -0,0 +1,1 @@>.
229     An empty old-side range names the line before the insertion: C<-0,0>
230     means before line 1, whereas C<-1,0> would mean after line 1 and is rejected
231     here. Nonempty ranges use one-based line numbers.
232    
233 root 1.5 An insertion elsewhere needs old-side context. Empty hunks are rejected.
234     New positions include the cumulative line-count changes of preceding hunks.
235    
236     =head3 Applying the result
237    
238 root 1.6 The C<normalize_udiff> function does not apply the patch, check file
239     contents or guard against concurrent edits. The caller must supply those
240     checks, if required.
241 root 1.5
242     Context must match exactly: apply with fuzz zero. For each hunk,
243     C<$max_offset> permits relocation by at most the number of distinct old-side
244     lines minus one, or zero for a pure insertion. Repeated old-side lines do
245     not increase this allowance. The applier must enforce these limits; an
246     unrestricted search for matching context can select the wrong occurrence.
247    
248     For live Vim buffers, also require the expected changedtick to match.
249     File-based users need an equivalent check before replacing the file.
250    
251 root 1.6 To work around GNU patch's handling of asymmetric context, the
252     first context line of each hunk is rewritten as an identity
253     removal/addition. The line contents and old/new line counts are
254     unchanged. This is normalization for the patch applier, not a relaxation
255     of context matching.
256 root 1.5
257 root 1.6 =over
258    
259     =item ($diff, $max_offset) = AnyEvent::MCP::normalize_udiff $diff
260    
261     Normalizes a relaxed, single-file unified diff into ordinary unified diff
262     syntax. Returns the normalized C<$diff> and an array reference C<$max_offset>
263     containing the permitted whole-hunk relocation for each hunk, in order.
264     Dies on malformed hunks or when no hunks are found.
265    
266     Here is a suitable description for the diff format, e.g. in a tool
267     definition:
268    
269     Apply a unified diff to one regular file. Hunk counts are recomputed,
270     fuzz is disabled, whole-hunk relocation is limited per hunk by distinct
271     old-side lines. Pure insertion is allowed only at the beginning;
272     elsewhere include old-side context.
273    
274     =item $cv = AnyEvent::MCP::apply_udiff $input, $output, $diff
275    
276     Asynchronously applies the relaxed C<$diff> to the input file C<$input>,
277     writing a separate output file C<$output>. C<$diff> must contain bytes;
278     callers working with characters must encode them for the file themselves.
279    
280     Normalizes the diff, runs GNU patch using C<AnyEvent::Util::run_cmd>, and
281     validates its verbose output with C<check_patch_output>. The command uses
282     batch/forward mode, binary mode and fuzz zero. No shell is involved.
283    
284     C<$output> must not exist. It is reserved with mode 0600; patch runs in its
285     directory so incidental temporary files stay there. Input and output paths
286     are made absolute before starting the command. These must be trusted paths
287     in a directory controlled by the caller.
288    
289     Returns a condition variable. Its C<recv> returns the validated hunk array
290     reference, or throws on command/application failure. Setup failures throw
291     synchronously. Failed or partial output is removed. C<$input> is unchanged.
292    
293     The caller owns committing the successful output and removing it when no
294     longer needed. Freshness checks, metadata preservation, atomic replacement
295     and application-specific permissions also belong to the caller.
296    
297     For your reference, the exact options used are:
298    
299     --verbose --batch --forward --binary --fuzz=0
300     --no-backup-if-mismatch
301     --reject-file=- --output=... -- <inputfile>
302    
303     =item $parsed = AnyEvent::MCP::parse_patch_output $output
304 root 1.5
305     Parses C<LC_ALL=C> GNU patch C<--verbose> output without judging whether
306     the application is acceptable. C<$parsed> has two fields:
307    
308 root 1.6 =over
309 root 1.5
310     =item hunks => [$hunk...]
311    
312     Hunk records in output order. Each record contains C<hunk> (the one-based
313     number), C<success>, C<line> (the reported application line), C<fuzz> and
314     the signed C<offset>. Omitted fuzz and offset are zero. Failed and ignored
315     hunks have false C<success>.
316    
317     =item unparsed => [$line...]
318    
319     Lines not recognized as hunk results or GNU patch's verbose framing.
320     The parser preserves them for callers to interpret or reject.
321    
322     =back
323    
324     Use verbose output: ordinary patch output omits exact-position successes,
325     so it cannot account for every hunk.
326    
327 root 1.6 =item $hunks = AnyEvent::MCP::check_patch_output $status, $output, [$max_offset...]
328 root 1.5
329     Parses C<$output> and validates a complete application. C<$status> is the
330     raw process wait status, as returned by C<waitpid> or
331     C<AnyEvent::Util::run_cmd>, not just the exit code.
332    
333     Requires status zero, no unrecognized output, exactly the expected hunks
334     in numbered order, successful application, fuzz zero and each signed offset
335     within its corresponding absolute limit. C<[$max_offset...]> is the array
336     reference returned by C<normalize_udiff>. At least one hunk is required.
337    
338     Returns the parsed hunk array reference on success; otherwise dies with a
339     diagnostic. This is also suitable for callers running patch inside their
340     own sandbox.
341    
342 root 1.6 =back
343 root 1.5
344 root 1.1 =cut
345    
346     package AnyEvent::MCP;
347    
348     use common::sense;
349     use Digest::SHA ();
350    
351     our $VERSION = '0.0';
352    
353 root 1.10 sub json_class {
354     our $JSON_CLASS ||= eval { require JSON::XS; "JSON::XS" }
355     || do { require JSON::PP; "JSON::PP" };
356     }
357    
358 root 1.8 sub utf8enc($) {
359     my $text = shift;
360    
361     utf8::encode $text;
362     $text
363     }
364    
365     sub utf8dec($) {
366     my $bytes = shift;
367    
368     utf8::decode $bytes
369     or die "invalid UTF-8\n";
370     $bytes
371     }
372    
373 root 1.2 sub random_bytes($) {
374     my ($length) = @_;
375    
376     die "Invalid random byte count\n"
377     unless defined $length && $length =~ /\A[0-9]+\z/;
378     return "" unless $length;
379    
380     my $bytes = "";
381    
382     if (open my $fh, "<", "/dev/urandom") {
383     binmode $fh;
384     while (length $bytes < $length) {
385     read ($fh, $bytes, $length - length ($bytes), length $bytes)
386     or last;
387     }
388     close $fh;
389    
390     return $bytes if length $bytes == $length;
391     }
392    
393     if (open my $fh, "-|", "openssl", "rand", $length) {
394     binmode $fh;
395     local $/;
396     $bytes = <$fh>;
397     my $success = close $fh;
398    
399     return $bytes
400     if $success && defined $bytes && length $bytes == $length;
401     }
402    
403     die "Cannot obtain $length random bytes from /dev/urandom or openssl rand\n";
404     }
405    
406 root 1.1 sub hkdf_sha512_expand($$$) {
407     my ($prk, $info, $l) = @_;
408    
409 root 1.2 64 == length $prk
410     or die "hkdf_sha512_expand: prk length mist be 64 octets";
411    
412 root 1.1 my $t = "";
413     my $okm = "";
414     my $i = 0;
415    
416     do {
417     $t = Digest::SHA::hmac_sha512 $t . $info . chr ++$i, $prk;
418     $okm .= $t;
419     } while $l > length $okm;
420    
421     substr $okm, 0, $l
422     }
423    
424 root 1.5 sub normalize_udiff {
425     my $diff = shift;
426     my @line = split /\n/, $diff, -1;
427     my $delta = 0;
428     my $hunks = 0;
429     my @max_offset;
430    
431     pop @line while @line and !length $line[-1];
432    
433     for (my $i = 0; $i < @line; ++$i) {
434     next unless $line[$i] =~ /^@@ /;
435    
436     $line[$i] =~ /^@@ -(\d+)(?:,\d+)?(?: \+\d+(?:,\d+)?)? @@(.*)$/
437     or die "normalize_udiff: bad hunk header '$line[$i]'\n";
438    
439     my ($old_start, $suffix) = ($1, $2);
440     my ($old_count, $new_count) = (0, 0);
441     my %old_line;
442     my $j = $i + 1;
443    
444     # GNU patch mishandles hunks with more prefix than suffix context.
445     # Make the first context line an identity change without losing it.
446     # see https://unix.stackexchange.com/questions/414542/does-patch-work-with-asymmetric-context
447     splice @line, $i + 1, 1, "-$1", "+$1"
448     if $line[$i + 1] =~ /^ (.*)\z/;
449    
450     for (; $j < @line; ++$j) {
451     last if $line[$j] =~ /^@@ /;
452    
453     my $tag = substr $line[$j], 0, 1;
454    
455     if ($tag eq " ") {
456     ++$old_count;
457     ++$new_count;
458     $old_line{substr $line[$j], 1} = 1;
459     } elsif ($tag eq "-") {
460     ++$old_count;
461     $old_line{substr $line[$j], 1} = 1;
462     } elsif ($tag eq "+") {
463     ++$new_count;
464     } elsif ($line[$j] eq "\\ No newline at end of file") {
465     # Marker belongs to the preceding body line and counts neither side.
466     } else {
467     die "normalize_udiff: bad hunk line '$line[$j]'\n";
468     }
469     }
470    
471     $old_count or $new_count
472     or die "normalize_udiff: empty hunk at old line $old_start\n";
473    
474     $old_count or !$old_start
475     or die "normalize_udiff: hunk " . ($hunks + 1)
476     . " needs old-side context for insertion after old line $old_start\n";
477    
478     my $new_start = $old_start + $delta;
479     ++$new_start unless $old_count;
480     --$new_start unless $new_count;
481    
482     $new_start >= 0
483     or die "normalize_udiff: invalid new line $new_start\n";
484    
485     $line[$i] = sprintf "@@ -%d,%d +%d,%d @@%s",
486     $old_start, $old_count, $new_start, $new_count, $suffix;
487    
488     $delta += $new_count - $old_count;
489     ++$hunks;
490     my $max_offset = keys %old_line;
491     --$max_offset
492     if $max_offset;
493     push @max_offset, $max_offset;
494     $i = $j - 1;
495     }
496    
497     $hunks
498     or die "normalize_udiff: no hunks\n";
499    
500     (join ("\n", @line, ""), \@max_offset)
501     }
502    
503     sub parse_patch_output {
504     my ($output) = @_;
505     my (@hunks, @unparsed);
506    
507     for (split /\n/, $output) {
508     if (/^Hunk #(\d+) (succeeded|FAILED|ignored) at (-?\d+)(?: with fuzz (\d+))?(?: \(offset (-?\d+) lines?\))?\.\z/) {
509     push @hunks, {
510     hunk => 0 + $1,
511     success => $2 eq "succeeded",
512     line => 0 + $3,
513     fuzz => 0 + $4,
514     offset => 0 + $5,
515     };
516     } elsif (!length
517     || /^Hmm\.\.\. +Looks like a unified diff to me\.\.\.\z/
518     || /^The text leading up to this was:\z/
519     || /^-+\z/ || /^\|/
520     || /^patching file / || /^checking file /
521     || /^Using Plan [AB]\.\.\.\z/ || /^done\z/) {
522     # GNU patch --verbose framing, not hunk results.
523     } else {
524     push @unparsed, $_;
525     }
526     }
527    
528     { hunks => \@hunks, unparsed => \@unparsed }
529     }
530    
531     sub check_patch_output {
532     my ($status, $output, $max_offset) = @_;
533     my $parsed = parse_patch_output $output;
534     my $hunks = $parsed->{hunks};
535    
536     die "patch failed (wait status $status):\n$output"
537     if $status;
538     die "patch: unrecognized output:\n" . (join "\n", @{$parsed->{unparsed}}) . "\n"
539     if @{$parsed->{unparsed}};
540     die "patch: expected " . @$max_offset . " hunks, got " . @$hunks . "\n"
541     unless @$hunks == @$max_offset && @$hunks;
542    
543     for my $i (0 .. $#$hunks) {
544     my $hunk = $hunks->[$i];
545    
546     die "patch: unexpected hunk number $hunk->{hunk}\n"
547     unless $hunk->{hunk} == $i + 1;
548     die "patch: hunk $hunk->{hunk} failed\n"
549     unless $hunk->{success};
550     die "patch: hunk $hunk->{hunk} used fuzz $hunk->{fuzz}\n"
551     if $hunk->{fuzz};
552     die "patch: hunk $hunk->{hunk} offset $hunk->{offset} exceeds $max_offset->[$i]\n"
553     if abs $hunk->{offset} > $max_offset->[$i];
554     }
555    
556     $hunks
557     }
558    
559     sub apply_udiff {
560     my ($input, $output, $diff) = @_;
561     my ($normalized, $max_offset) = normalize_udiff $diff;
562    
563     require AnyEvent::Util;
564     require File::Spec;
565     require File::Basename;
566     require Fcntl;
567    
568     $input = File::Spec->rel2abs ($input);
569     $output = File::Spec->rel2abs ($output);
570     my $directory = File::Basename::dirname ($output);
571    
572     sysopen my $fh, $output, Fcntl::O_WRONLY () | Fcntl::O_CREAT () | Fcntl::O_EXCL (), 0600
573     or die "$output: $!\n";
574     close $fh or do { my $error = $!; unlink $output; die "$output: $error\n" };
575    
576     my $cv = AE::cv ();
577     my $log;
578     my $process = eval {
579     AnyEvent::Util::run_cmd ([
580     "patch", "--verbose", "--batch", "--forward", "--binary", "--fuzz=0",
581     "--no-backup-if-mismatch", "--reject-file=-", "--output=$output", "--", $input,
582     ],
583     "<" => \$normalized,
584     ">" => \$log,
585     close_all => 1,
586     on_prepare => sub {
587     $ENV{LC_ALL} = "C";
588     chdir $directory or die "$directory: $!\n";
589     defined POSIX::dup2 (1, 2) or die "dup2: $!\n";
590     },
591     );
592     };
593    
594     if ($@) {
595     my $error = $@;
596     unlink $output;
597     die $error;
598     }
599    
600     $process->cb (sub {
601     my $hunks;
602     eval { $hunks = check_patch_output $_[0]->recv, $log, $max_offset; 1 } or do {
603     my $error = $@;
604     unlink $output;
605     $cv->croak ($error);
606     return;
607     };
608    
609     $cv->send ($hunks);
610     });
611    
612     $cv
613     }
614    
615 root 1.1 sub _clean_text($) {
616     my ($text) = @_;
617    
618     my ($prefix) = (join "\n", grep /\S/, split /\n/, $text)
619     =~ /\A([ \t]*)[^\n]*(?:\n\1[^\n]*)*\z/;
620    
621     $text =~ s/^\Q$prefix\E//mg;
622     $text =~ s/\A\s+//;
623     $text =~ s/\s+\z//;
624     $text
625     }
626    
627     package AnyEvent::MCP::Base;
628    
629     sub new {
630     my ($class, %kv) = @_;
631     bless \%kv, $class
632     }
633    
634     sub event {
635     my ($self, $event, @args) = @_;
636     ($self->{"on_$event"} or return)->($self, @args)
637     }
638    
639     =head1 SEE ALSO
640    
641 root 1.16 L<AnyEvent::MCP::Intro>, L<AnyEvent::MCP::Server::Simple>,
642 root 1.1 L<AnyEvent>, L<https://modelcontextprotocol.io/>
643    
644     =head1 AUTHOR
645    
646     The main author of this module is OpenAI ChatGPT.
647    
648     Additional guidance received by:
649    
650     Marc Lehmann <schmorp@schmorp.de>
651     http://home.schmorp.de/
652    
653     =cut
654    
655     1
656