ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/lib/AnyEvent/MCP.pm
Revision: 1.11
Committed: Sat Oct 10 10:48:51 2026 UTC (5 weeks, 4 days ago) by root
Branch: MAIN
Changes since 1.10: +19 -12 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.6 use AnyEvent::MCP::Server::Simple ();
8 root 1.1
9     mcp_tool ...
10 root 1.3 mcp_start;
11 root 1.1
12     or use the object interface directly:
13    
14 root 1.6 use AnyEvent::MCP::Server ();
15 root 1.1
16     my $server = AnyEvent::MCP::Server->new (...);
17    
18     =head1 DESCRIPTION
19    
20     AnyEvent::MCP provides event-driven Model Context Protocol client and server
21     support.
22    
23     The usual way to implement a small MCP server is
24     L<AnyEvent::MCP::Server::Simple>, which provides a function-based interface and
25     creates the underlying server objects when a transport such as stdio or HTTP is
26     started.
27    
28     The lower-level object interfaces are intended for applications that need to
29     manage MCP connections, servers or reusable tool registries directly.
30    
31     =head2 MODULES
32    
33 root 1.7 =over
34 root 1.1
35     =item L<AnyEvent::MCP::Server::Simple>
36    
37     Function-based interface for implementing ordinary MCP servers.
38    
39     =item L<AnyEvent::MCP::Server>
40    
41     Object-oriented MCP server interface.
42    
43     =item L<AnyEvent::MCP::Client>
44    
45     Object-oriented MCP client interface.
46    
47     =item L<AnyEvent::MCP::Server::Toolset>
48    
49     Reusable registry of MCP tool declarations.
50    
51     =item L<AnyEvent::MCP::Server::Permissions>
52    
53     Permission and capability handling for MCP servers.
54    
55     =back
56    
57 root 1.4 C<mcp-multibroker> combines downstream HTTP and stdio servers under tool-name
58     prefixes. It uses the same client, server and permission helper facilities,
59     including modern input forwarding and local permission prompts for legacy
60     callers. Run C<mcp-multibroker --help> for command-line syntax; its manual
61     describes authentication and configuration.
62    
63 root 1.9 The interfaces are still being designed. The walkthrough below explains the
64     installed programs; module-specific POD documents their Perl APIs.
65    
66     =head1 GETTING STARTED
67    
68     This distribution contains an MCP client/server library and several ready-to-use
69     programs. You do not need to write Perl to use them.
70    
71     =over
72    
73     =item C<mcp-fs>
74    
75     A filesystem and command server. Each operation runs in a Linux bubblewrap
76     sandbox with only the filesystem and other capabilities approved for that
77     operation. Read, write, search, patch, path operations and command execution
78     are exposed as MCP tools.
79    
80     =item C<mcp-multibroker>
81    
82     Combines several MCP servers behind one connection. Each downstream server has
83     a prefix, so a C<file-read> tool belonging to C<files> becomes
84     C<files.file-read>. Its clients may connect over HTTP or be launched over
85     stdio. The multibroker itself can serve HTTP or stdio.
86    
87     =item C<anyevent-mcp> and C<anyevent-mcp-askpermission>
88    
89     Manage shared credentials/rules and ask the local user for permission,
90     respectively. Normally the permission helper is started automatically.
91    
92     =back
93    
94     =head2 Start with one filesystem server
95    
96     Install this Perl distribution first. On Debian or Ubuntu, install the
97     runtime sandbox and optional graphical permission helper with:
98    
99     sudo apt install bubblewrap yad
100    
101     The executable is called C<bwrap>, although the package is C<bubblewrap>.
102     C<yad> provides graphical approval dialogs; without it, the default helper
103     tries C</dev/tty> and denies if no terminal is available. Unprivileged user
104     namespaces must be available. C<mcp-fs> also uses GNU C<find>, C<grep>,
105     C<patch> and C<sed>, and a compatible Perl interpreter. On a minimal
106     Debian installation, these can be installed with:
107    
108     sudo apt install findutils grep patch sed perl
109    
110     Tools whose required programs are missing are omitted at startup.
111    
112     Give the server one or more directories that you actually intend to make
113     available. For example:
114    
115     mcp-fs --name code --port 31741 /home/alice/src/project
116    
117     This starts an authenticated HTTP MCP server. It prints a URL containing
118     an access cookie; keep that URL private. Its clean URL also accepts the same
119     credential as a bearer token. C<--port 0> selects an available port.
120     The permission-rule file is printed on stderr.
121    
122     For a local MCP client that starts its servers as subprocesses, use stdio:
123    
124     mcp-fs --stdio /home/alice/src/project
125    
126     The MCP client, not a human terminal, should start this process: stdin and
127     stdout carry protocol messages. For a quick manual sandbox test without MCP
128     or permission prompting, run from the intended workdir:
129    
130     mcp-fs --exec-cmd workdir-read -- ls
131    
132     C<--exec-cmd> runs the supplied command with exactly the named capabilities,
133     without consulting saved permission rules. It is a local debugging facility.
134    
135     Within MCP, begin with the C<workdirs> tool to inspect the configured
136     workdirs and capabilities. Relative paths are resolved against the selected
137     workdir; access beyond the granted mounts needs additional permission.
138     Providing a workdir does not give arbitrary commands unrestricted host access.
139     See L<mcp-fs/CAPABILITIES> and L<mcp-fs/LIMITATIONS>.
140    
141     Once the client is connected, you can just ask the LLM to use the tools,
142     for example:
143    
144     Show me the available workdirs, find the TODO comments in my project,
145     and suggest the next task. Do not modify any files.
146    
147     The client can call C<workdirs> and C<grep> itself; you need not know the
148     MCP request format or write your own integration.
149    
150     =head2 Combine servers with mcp-multibroker
151    
152     Rather than configure each MCP client with every server, configure them
153     once behind the multibroker. For example, to expose two distinct filesystem
154     servers over one HTTP endpoint:
155    
156     mcp-multibroker code 'stdio:mcp-fs /home/alice/src/project' \
157     notes 'stdio:mcp-fs /home/alice/notes'
158    
159     Each C<stdio:> value is a shell command; quote it as one argument.
160     The multibroker starts the child with the correct stdio environment
161     and an alias equal to its prefix. That alias is also the default
162     C<mcp-fs> permission profile, keeping permissions for C<code> and
163     C<notes> separate.
164    
165     The multibroker prints its own authenticated HTTP URL. A client sees
166     tools such as C<code.file-read>, C<code.file-patch> and
167     C<notes.file-read>. The additional C<discover-brokers>, C<list-tools>
168     and C<call-tool> tools support explicit discovery and dispatch.
169     The client normally can call the prefixed tools directly.
170    
171     If the LLM is still using an old tool list after a downstream server
172     becomes available or changes its tools, simply tell it:
173    
174     Call discover-brokers and list-tools again, then use the newly
175     discovered tools.
176    
177     C<discover-brokers> connects to reachable servers and retrieves their
178     instructions; C<list-tools> requests their current tool lists. C<call-tool>
179     can dispatch a newly discovered prefixed tool even when the client has not
180     refreshed its own direct tool list yet. If the client hides or caches the
181     broker's tools, reconnect or refresh the MCP connection in that client.
182     Changing the broker's configured prefix/URL pairs requires restarting
183     C<mcp-multibroker>; discovery cannot change its command-line configuration.
184    
185     The same broker can mix remote HTTP servers with local subprocesses.
186     For example, an installation might combine office and automation tools:
187    
188     mcp-multibroker \
189     office http://localhost:8766/mcp \
190     homeassistant http://homeassistant.local:8123/api/mcp \
191     --bearer TOKEN \
192     marco http://marco.example.net:31746/COOKIE/
193    
194     Or combine a custom application server, remote machines and a third-party
195     stdio server:
196    
197     mcp-multibroker \
198     agni 'stdio:/opt/agni/bin/agni-mcp' \
199     cerebro http://cerebro.example.net:31748/COOKIE/ \
200     chrome 'stdio:npx -y chrome-devtools-mcp@latest --no-usage-statistics'
201    
202     These are illustrative hostnames and redacted credentials, not usable
203     endpoints. C<--bearer> belongs immediately after the HTTP server it
204     authenticates. A cookie URL already carries its credential. Never publish
205     or check in either kind of secret. The broker does not impose the C<mcp-fs>
206     bubblewrap sandbox on other servers: those processes and services have their
207     own security boundaries. A shell wrapper can use C<exec mcp-multibroker>
208     to replace itself with the broker process.
209    
210     To start the multibroker itself over stdio, let the client set
211     C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio>, or use a command like:
212    
213     PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio \
214     mcp-multibroker code 'stdio:mcp-fs /home/alice/src/project'
215    
216     The broker can also connect to existing HTTP MCP servers:
217    
218     mcp-multibroker files 'stdio:mcp-fs /home/alice/src/project' \
219     remote https://example.org/mcp/ --bearer TOKEN
220    
221     The token is a credential; avoid exposing it in shell history or process
222     arguments in a real deployment. An HTTP client can instead use
223     C<[client PREFIX]> in the private global configuration. See
224     L<mcp-multibroker> and L</GLOBAL CONFIGURATION>.
225    
226     =head2 Connect an AI client
227    
228     These are examples for clients with MCP support. Paths are illustrative;
229     substitute your installed commands and real workdirs. Client interfaces
230     evolve independently of this module, so consult their documentation if an
231     option has changed.
232    
233     =head3 OpenAI Codex CLI
234    
235     Codex can start the broker locally over stdio:
236    
237     codex mcp add mytools --env PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio \
238     -- mcp-multibroker \
239     files 'stdio:mcp-fs /home/alice/src/project'
240     codex mcp list
241    
242     Use C</mcp> within Codex to inspect connections.
243     See L<Codex MCP documentation|https://learn.chatgpt.com/docs/extend/mcp>.
244    
245     =head3 Anthropic Claude Code
246    
247     Claude Code can start the same broker:
248    
249     claude mcp add --transport stdio --scope user mytools \
250     --env PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio -- \
251     mcp-multibroker files 'stdio:mcp-fs /home/alice/src/project'
252     claude mcp list
253    
254     Use C</mcp> within Claude Code for connection status. See
255     L<Claude Code MCP documentation|https://code.claude.com/docs/en/mcp>.
256    
257     =head3 Google Gemini CLI
258    
259     Add a local broker to C<~/.gemini/settings.json> (merge with any existing
260     settings):
261    
262     {
263     "mcpServers": {
264     "mytools": {
265     "command": "mcp-multibroker",
266     "args": [
267     "files", "stdio:mcp-fs /home/alice/src/project"
268     ],
269     "env": {
270     "PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL": "stdio"
271     }
272     }
273     }
274     }
275    
276     Use C</mcp> in Gemini CLI to inspect the connection.
277     See L<Gemini CLI MCP documentation|https://geminicli.com/docs/tools/mcp-server/>.
278    
279     =head3 ChatGPT web
280    
281     ChatGPT is a hosted client and cannot spawn a local stdio process or
282     connect directly to a local loopback server. Start C<mcp-multibroker> in
283     HTTP mode and connect it through ChatGPT's custom MCP plugin setup.
284     For a private local server, use an appropriately configured Secure MCP
285     Tunnel rather than making the machine publicly accessible. The connection
286     is subject to the client's plan, workspace and feature permissions.
287     See L<ChatGPT custom MCP servers|https://developers.openai.com/api/docs/guides/custom-mcp-server>
288     and L<Secure MCP Tunnel|https://developers.openai.com/blog/connect-private-mcp-servers-to-openai-products>.
289    
290     =head2 Permissions and approval dialogs
291    
292     C<mcp-fs> does not treat a connected model as fully trusted. Each tool
293     asks for the authority it needs; you can allow or deny the request once,
294     or save a rule for subsequent matching requests. Its default prompting
295     mode is C<--ask helper>, using C<anyevent-mcp-askpermission> on the
296     server's machine (YAD or C</dev/tty>). Closing the prompt denies once.
297    
298     For a client that supports the newer MCP form-elicitation protocol, try:
299    
300     mcp-fs --ask auto --stdio /home/alice/src/project
301    
302     C<--ask auto> uses MCP elicitation when the client advertises the necessary
303     support, otherwise the local helper. C<--ask mcp> requires elicitation and
304     fails if it is unavailable; it does not silently fall back. Not all MCP
305     clients or versions support the required input/continuation flow, even if
306     they support ordinary tool calls. For an ordinary stdio broker configuration,
307     put the chosen option in the child command:
308    
309     mcp-multibroker files \
310     'stdio:mcp-fs --ask auto /home/alice/src/project'
311    
312     Permission profiles are stored under C<~/.config/anyevent-mcp/> (or
313     C<$XDG_CONFIG_HOME/anyevent-mcp/>). A child launched by the broker
314     normally uses its prefix as the profile name; use C<--profile NAME>
315     to override it. Review persistent rules rather than granting
316     C<world-write> casually. Run C<anyevent-mcp --help> for the credential
317     and rule-management commands; see
318     L<AnyEvent::MCP::Server::Permissions> for rule syntax and ordering.
319    
320     =head2 Further documentation
321    
322     perldoc mcp-fs
323     perldoc mcp-multibroker
324     perldoc anyevent-mcp
325     perldoc AnyEvent::MCP::Server::Simple
326     perldoc AnyEvent::MCP::Server::Permissions
327    
328     The programs describe their own command-line options. If a client reports
329     no tools, first check that the selected program starts and that its required
330     utilities are detected. Stdio servers must not print diagnostics or banners
331     to stdout. For HTTP, check that the client can reach the configured URL and
332     has the correct authentication credentials.
333 root 1.1
334 root 1.2 =head1 GLOBAL CONFIGURATION
335    
336     The shared per-user configuration is C<$XDG_CONFIG_HOME/anyevent-mcp/global.ini>,
337     or C<$HOME/.config/anyevent-mcp/global.ini> when XDG_CONFIG_HOME is unset.
338     L<AnyEvent::MCP::Config> loads and holds it; loading this module does not access
339     configuration files.
340    
341     The file is UTF-8 and uses sections with single-line C<key = value> pairs.
342     Values are unquoted strings. Blank lines and whole-line comments beginning
343     with C<#> or C<;> are ignored; inline comment characters remain part of the
344     value. Later occurrences of a key replace earlier ones in the same section.
345    
346     [global]
347     secret = ...128 hexadecimal digits...
348    
349     [server example]
350 root 1.11 bind = 127.0.0.1:31740
351 root 1.3 url = https://example.net:31740/{cookie}/
352 root 1.2
353     [mcp-fs]
354     utility = /path/to/utility
355    
356     Section names are unrestricted. Application-specific sections, including
357     exports, utility paths and user settings, are documented by their applications.
358    
359     C<[global]> holds C<secret>, a 64-byte master key encoded as 128 hexadecimal
360     digits. The file must be owned by the current user, with no group or other
361     permissions. A missing secret is generated automatically on first configuration
362     access and saved when possible. Existing secrets are never replaced implicitly.
363     An invalid secret is an error.
364    
365     If saving fails, Config warns and retains the secret in memory. Credentials
366     then remain stable only for that process; other processes cannot derive the
367     same credentials. If randomness is unavailable, supply a securely generated
368     secret in the file.
369    
370     C<[server NAME]> holds named-server settings. Its C<url> is a complete template;
371     C<{cookie}> is replaced with the cookie derived for that server and optional
372     username. Scheme, host, port and cookie placement are explicit in the template.
373 root 1.11 HTTP-capable executables use C<--name NAME> to select these settings, with
374     the executable basename as the default name. Names consist of an ASCII
375     letter or underscore followed by ASCII letters, digits, underscores or
376     hyphens. Their C<--bind ADDRESS[:PORT]> overrides the configured C<bind>.
377     The default bind address is IPv4 loopback with a port derived from the name
378     and master secret in the range 16384..32767; C<:0> requests an ephemeral
379     port. C<--print-url> prints the derived cookie URL without listening.
380     Named server settings also include C<path>, C<url_host>, C<url_scheme>,
381     C<cookie>, C<bearer> and C<users>. C<users> is a comma-separated Basic
382     user allowlist whose passwords are derived for the named server.
383    
384     C<mcp_start> resolves named settings and supplies cookie/bearer
385     authentication by default. Explicit authentication settings replace it.
386     The low-level HTTP transport does not resolve configuration itself.
387     Stdio startup does not access global HTTP configuration. Browser origins
388     are permitted by default, but must still pass MCP authentication.
389 root 1.3
390     C<[client NAME]> supplies HTTP client defaults: C<url>, C<bearer>, C<username>,
391     C<password> and C<timeout>. Clients consult it only when explicitly given a
392     C<name>. An unnamed client or HTTP server does not read global configuration.
393     Explicit constructor arguments take precedence over named defaults.
394    
395     =head1 ENVIRONMENT
396    
397     Project-specific environment variables use the C<PERL_ANYEVENT_MCP_> prefix.
398     C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL=stdio> selects stdio in Simple.
399 root 1.11 C<PERL_ANYEVENT_MCP_MULTIBROKER_ALIAS> names a multibroker routing prefix;
400     it does not change the service-instance name.
401 root 1.3 C<PERL_ANYEVENT_MCP_PERMISSION_HELPER> selects the external asking executable.
402     Standard C<HOME> and C<XDG_CONFIG_HOME> keep their standard names.
403 root 1.2
404     =head1 FUNCTIONS
405    
406 root 1.6 =over
407    
408 root 1.10 =item $class = AnyEvent::MCP::json_class
409    
410     Returns C<JSON::XS> if available, otherwise C<JSON::PP>. The caller
411     configures a new coder instance as needed.
412    
413 root 1.8 =item $bytes = AnyEvent::MCP::utf8enc $text
414    
415     Return a UTF-8 byte string for C<$text>, leaving the argument unchanged.
416    
417     =item $text = AnyEvent::MCP::utf8dec $bytes
418    
419     Decode a UTF-8 byte string into characters, dying on invalid UTF-8.
420     The argument is left unchanged. For intentional in-place conversions,
421     use Perl's C<utf8::encode> or C<utf8::decode> directly.
422    
423 root 1.6 =item $bytes = AnyEvent::MCP::random_bytes $length
424 root 1.2
425     Returns exactly C<$length> random bytes. Tries C</dev/urandom>, then an external
426     C<openssl rand> command. No additional random-number module is required.
427     Dies if neither source supplies the requested bytes successfully.
428     C<$length> must be a nonnegative integer; zero returns an empty string.
429    
430 root 1.6 =back
431    
432     =head2 PATCH UTILITIES
433    
434 root 1.7 Since applying patches to files is a common task for MCP servers, the
435 root 1.6 following utility functions can be used to ease that job. Together, they
436 root 1.7 define a common patch format (unified diff or a simplified version of it,
437     with fewer requirements to make it easier for the LLM to generate), helpers
438 root 1.6 to apply the patch and a helper to verify if the patch was applied
439     with sufficient precision.
440    
441 root 1.7 Use C<apply_udiff> to normalize, apply and validate a patch in one operation.
442     It writes a separate output file; the caller checks freshness and metadata
443     and commits the result.
444    
445     For an application-specific applier, the workflow is:
446 root 1.6
447     =over
448    
449     =item 1. AnyEvent::MCP::normalize_udiff
450    
451 root 1.7 Returns a unified diff for GNU patch and the permitted hunk offsets.
452    
453     =item 2. Apply the normalized diff
454 root 1.6
455 root 1.7 Run GNU patch with fuzz zero and capture its verbose output.
456 root 1.6
457 root 1.7 =item 3. AnyEvent::MCP::check_patch_output
458    
459     Checks the process status and output against the permitted offsets.
460     C<parse_patch_output> is available separately when only parsing is needed.
461 root 1.5
462 root 1.6 =back
463    
464 root 1.5 =head3 Input format
465    
466 root 1.6 The patch format accepted by normalize_udiff is an extension to the
467     (essentially undocumented) unified diff format.
468    
469 root 1.5 In a hunk header, only the old start C<-N> matters. It is the old-file line
470     of the first hunk body line, including context, not necessarily the first
471     changed line. Counts and the new-file position are ignored and recomputed.
472     Both ordinary headers and the abbreviated form are accepted:
473    
474     @@ -42,99 +123,99 @@
475     @@ -42 @@
476    
477     Optional text after the closing C<@@> is preserved. File headers and other
478     text before the first hunk are preserved; a diff must describe one file.
479    
480     Hunk body lines use the usual prefixes: a space for unchanged context,
481     C<-> for removed lines and C<+> for added lines. The
482     C<\ No newline at end of file> marker is preserved and counts neither side.
483     Trailing empty lines outside the final hunk are discarded.
484    
485 root 1.7 Pure insertion is permitted only at the beginning, using old start C<0>.
486     For example, C<@@ -0 @@> with one added line becomes C<@@ -0,0 +1,1 @@>.
487     An empty old-side range names the line before the insertion: C<-0,0>
488     means before line 1, whereas C<-1,0> would mean after line 1 and is rejected
489     here. Nonempty ranges use one-based line numbers.
490    
491 root 1.5 An insertion elsewhere needs old-side context. Empty hunks are rejected.
492     New positions include the cumulative line-count changes of preceding hunks.
493    
494     =head3 Applying the result
495    
496 root 1.6 The C<normalize_udiff> function does not apply the patch, check file
497     contents or guard against concurrent edits. The caller must supply those
498     checks, if required.
499 root 1.5
500     Context must match exactly: apply with fuzz zero. For each hunk,
501     C<$max_offset> permits relocation by at most the number of distinct old-side
502     lines minus one, or zero for a pure insertion. Repeated old-side lines do
503     not increase this allowance. The applier must enforce these limits; an
504     unrestricted search for matching context can select the wrong occurrence.
505    
506     For live Vim buffers, also require the expected changedtick to match.
507     File-based users need an equivalent check before replacing the file.
508    
509 root 1.6 To work around GNU patch's handling of asymmetric context, the
510     first context line of each hunk is rewritten as an identity
511     removal/addition. The line contents and old/new line counts are
512     unchanged. This is normalization for the patch applier, not a relaxation
513     of context matching.
514 root 1.5
515 root 1.6 =over
516    
517     =item ($diff, $max_offset) = AnyEvent::MCP::normalize_udiff $diff
518    
519     Normalizes a relaxed, single-file unified diff into ordinary unified diff
520     syntax. Returns the normalized C<$diff> and an array reference C<$max_offset>
521     containing the permitted whole-hunk relocation for each hunk, in order.
522     Dies on malformed hunks or when no hunks are found.
523    
524     Here is a suitable description for the diff format, e.g. in a tool
525     definition:
526    
527     Apply a unified diff to one regular file. Hunk counts are recomputed,
528     fuzz is disabled, whole-hunk relocation is limited per hunk by distinct
529     old-side lines. Pure insertion is allowed only at the beginning;
530     elsewhere include old-side context.
531    
532     =item $cv = AnyEvent::MCP::apply_udiff $input, $output, $diff
533    
534     Asynchronously applies the relaxed C<$diff> to the input file C<$input>,
535     writing a separate output file C<$output>. C<$diff> must contain bytes;
536     callers working with characters must encode them for the file themselves.
537    
538     Normalizes the diff, runs GNU patch using C<AnyEvent::Util::run_cmd>, and
539     validates its verbose output with C<check_patch_output>. The command uses
540     batch/forward mode, binary mode and fuzz zero. No shell is involved.
541    
542     C<$output> must not exist. It is reserved with mode 0600; patch runs in its
543     directory so incidental temporary files stay there. Input and output paths
544     are made absolute before starting the command. These must be trusted paths
545     in a directory controlled by the caller.
546    
547     Returns a condition variable. Its C<recv> returns the validated hunk array
548     reference, or throws on command/application failure. Setup failures throw
549     synchronously. Failed or partial output is removed. C<$input> is unchanged.
550    
551     The caller owns committing the successful output and removing it when no
552     longer needed. Freshness checks, metadata preservation, atomic replacement
553     and application-specific permissions also belong to the caller.
554    
555     For your reference, the exact options used are:
556    
557     --verbose --batch --forward --binary --fuzz=0
558     --no-backup-if-mismatch
559     --reject-file=- --output=... -- <inputfile>
560    
561     =item $parsed = AnyEvent::MCP::parse_patch_output $output
562 root 1.5
563     Parses C<LC_ALL=C> GNU patch C<--verbose> output without judging whether
564     the application is acceptable. C<$parsed> has two fields:
565    
566 root 1.6 =over
567 root 1.5
568     =item hunks => [$hunk...]
569    
570     Hunk records in output order. Each record contains C<hunk> (the one-based
571     number), C<success>, C<line> (the reported application line), C<fuzz> and
572     the signed C<offset>. Omitted fuzz and offset are zero. Failed and ignored
573     hunks have false C<success>.
574    
575     =item unparsed => [$line...]
576    
577     Lines not recognized as hunk results or GNU patch's verbose framing.
578     The parser preserves them for callers to interpret or reject.
579    
580     =back
581    
582     Use verbose output: ordinary patch output omits exact-position successes,
583     so it cannot account for every hunk.
584    
585 root 1.6 =item $hunks = AnyEvent::MCP::check_patch_output $status, $output, [$max_offset...]
586 root 1.5
587     Parses C<$output> and validates a complete application. C<$status> is the
588     raw process wait status, as returned by C<waitpid> or
589     C<AnyEvent::Util::run_cmd>, not just the exit code.
590    
591     Requires status zero, no unrecognized output, exactly the expected hunks
592     in numbered order, successful application, fuzz zero and each signed offset
593     within its corresponding absolute limit. C<[$max_offset...]> is the array
594     reference returned by C<normalize_udiff>. At least one hunk is required.
595    
596     Returns the parsed hunk array reference on success; otherwise dies with a
597     diagnostic. This is also suitable for callers running patch inside their
598     own sandbox.
599    
600 root 1.6 =back
601 root 1.5
602 root 1.1 =cut
603    
604     package AnyEvent::MCP;
605    
606     use common::sense;
607     use Digest::SHA ();
608    
609     our $VERSION = '0.0';
610    
611 root 1.10 sub json_class {
612     our $JSON_CLASS ||= eval { require JSON::XS; "JSON::XS" }
613     || do { require JSON::PP; "JSON::PP" };
614     }
615    
616 root 1.8 sub utf8enc($) {
617     my $text = shift;
618    
619     utf8::encode $text;
620     $text
621     }
622    
623     sub utf8dec($) {
624     my $bytes = shift;
625    
626     utf8::decode $bytes
627     or die "invalid UTF-8\n";
628     $bytes
629     }
630    
631 root 1.2 sub random_bytes($) {
632     my ($length) = @_;
633    
634     die "Invalid random byte count\n"
635     unless defined $length && $length =~ /\A[0-9]+\z/;
636     return "" unless $length;
637    
638     my $bytes = "";
639    
640     if (open my $fh, "<", "/dev/urandom") {
641     binmode $fh;
642     while (length $bytes < $length) {
643     read ($fh, $bytes, $length - length ($bytes), length $bytes)
644     or last;
645     }
646     close $fh;
647    
648     return $bytes if length $bytes == $length;
649     }
650    
651     if (open my $fh, "-|", "openssl", "rand", $length) {
652     binmode $fh;
653     local $/;
654     $bytes = <$fh>;
655     my $success = close $fh;
656    
657     return $bytes
658     if $success && defined $bytes && length $bytes == $length;
659     }
660    
661     die "Cannot obtain $length random bytes from /dev/urandom or openssl rand\n";
662     }
663    
664 root 1.1 sub hkdf_sha512_expand($$$) {
665     my ($prk, $info, $l) = @_;
666    
667 root 1.2 64 == length $prk
668     or die "hkdf_sha512_expand: prk length mist be 64 octets";
669    
670 root 1.1 my $t = "";
671     my $okm = "";
672     my $i = 0;
673    
674     do {
675     $t = Digest::SHA::hmac_sha512 $t . $info . chr ++$i, $prk;
676     $okm .= $t;
677     } while $l > length $okm;
678    
679     substr $okm, 0, $l
680     }
681    
682 root 1.5 sub normalize_udiff {
683     my $diff = shift;
684     my @line = split /\n/, $diff, -1;
685     my $delta = 0;
686     my $hunks = 0;
687     my @max_offset;
688    
689     pop @line while @line and !length $line[-1];
690    
691     for (my $i = 0; $i < @line; ++$i) {
692     next unless $line[$i] =~ /^@@ /;
693    
694     $line[$i] =~ /^@@ -(\d+)(?:,\d+)?(?: \+\d+(?:,\d+)?)? @@(.*)$/
695     or die "normalize_udiff: bad hunk header '$line[$i]'\n";
696    
697     my ($old_start, $suffix) = ($1, $2);
698     my ($old_count, $new_count) = (0, 0);
699     my %old_line;
700     my $j = $i + 1;
701    
702     # GNU patch mishandles hunks with more prefix than suffix context.
703     # Make the first context line an identity change without losing it.
704     # see https://unix.stackexchange.com/questions/414542/does-patch-work-with-asymmetric-context
705     splice @line, $i + 1, 1, "-$1", "+$1"
706     if $line[$i + 1] =~ /^ (.*)\z/;
707    
708     for (; $j < @line; ++$j) {
709     last if $line[$j] =~ /^@@ /;
710    
711     my $tag = substr $line[$j], 0, 1;
712    
713     if ($tag eq " ") {
714     ++$old_count;
715     ++$new_count;
716     $old_line{substr $line[$j], 1} = 1;
717     } elsif ($tag eq "-") {
718     ++$old_count;
719     $old_line{substr $line[$j], 1} = 1;
720     } elsif ($tag eq "+") {
721     ++$new_count;
722     } elsif ($line[$j] eq "\\ No newline at end of file") {
723     # Marker belongs to the preceding body line and counts neither side.
724     } else {
725     die "normalize_udiff: bad hunk line '$line[$j]'\n";
726     }
727     }
728    
729     $old_count or $new_count
730     or die "normalize_udiff: empty hunk at old line $old_start\n";
731    
732     $old_count or !$old_start
733     or die "normalize_udiff: hunk " . ($hunks + 1)
734     . " needs old-side context for insertion after old line $old_start\n";
735    
736     my $new_start = $old_start + $delta;
737     ++$new_start unless $old_count;
738     --$new_start unless $new_count;
739    
740     $new_start >= 0
741     or die "normalize_udiff: invalid new line $new_start\n";
742    
743     $line[$i] = sprintf "@@ -%d,%d +%d,%d @@%s",
744     $old_start, $old_count, $new_start, $new_count, $suffix;
745    
746     $delta += $new_count - $old_count;
747     ++$hunks;
748     my $max_offset = keys %old_line;
749     --$max_offset
750     if $max_offset;
751     push @max_offset, $max_offset;
752     $i = $j - 1;
753     }
754    
755     $hunks
756     or die "normalize_udiff: no hunks\n";
757    
758     (join ("\n", @line, ""), \@max_offset)
759     }
760    
761     sub parse_patch_output {
762     my ($output) = @_;
763     my (@hunks, @unparsed);
764    
765     for (split /\n/, $output) {
766     if (/^Hunk #(\d+) (succeeded|FAILED|ignored) at (-?\d+)(?: with fuzz (\d+))?(?: \(offset (-?\d+) lines?\))?\.\z/) {
767     push @hunks, {
768     hunk => 0 + $1,
769     success => $2 eq "succeeded",
770     line => 0 + $3,
771     fuzz => 0 + $4,
772     offset => 0 + $5,
773     };
774     } elsif (!length
775     || /^Hmm\.\.\. +Looks like a unified diff to me\.\.\.\z/
776     || /^The text leading up to this was:\z/
777     || /^-+\z/ || /^\|/
778     || /^patching file / || /^checking file /
779     || /^Using Plan [AB]\.\.\.\z/ || /^done\z/) {
780     # GNU patch --verbose framing, not hunk results.
781     } else {
782     push @unparsed, $_;
783     }
784     }
785    
786     { hunks => \@hunks, unparsed => \@unparsed }
787     }
788    
789     sub check_patch_output {
790     my ($status, $output, $max_offset) = @_;
791     my $parsed = parse_patch_output $output;
792     my $hunks = $parsed->{hunks};
793    
794     die "patch failed (wait status $status):\n$output"
795     if $status;
796     die "patch: unrecognized output:\n" . (join "\n", @{$parsed->{unparsed}}) . "\n"
797     if @{$parsed->{unparsed}};
798     die "patch: expected " . @$max_offset . " hunks, got " . @$hunks . "\n"
799     unless @$hunks == @$max_offset && @$hunks;
800    
801     for my $i (0 .. $#$hunks) {
802     my $hunk = $hunks->[$i];
803    
804     die "patch: unexpected hunk number $hunk->{hunk}\n"
805     unless $hunk->{hunk} == $i + 1;
806     die "patch: hunk $hunk->{hunk} failed\n"
807     unless $hunk->{success};
808     die "patch: hunk $hunk->{hunk} used fuzz $hunk->{fuzz}\n"
809     if $hunk->{fuzz};
810     die "patch: hunk $hunk->{hunk} offset $hunk->{offset} exceeds $max_offset->[$i]\n"
811     if abs $hunk->{offset} > $max_offset->[$i];
812     }
813    
814     $hunks
815     }
816    
817     sub apply_udiff {
818     my ($input, $output, $diff) = @_;
819     my ($normalized, $max_offset) = normalize_udiff $diff;
820    
821     require AnyEvent::Util;
822     require File::Spec;
823     require File::Basename;
824     require Fcntl;
825    
826     $input = File::Spec->rel2abs ($input);
827     $output = File::Spec->rel2abs ($output);
828     my $directory = File::Basename::dirname ($output);
829    
830     sysopen my $fh, $output, Fcntl::O_WRONLY () | Fcntl::O_CREAT () | Fcntl::O_EXCL (), 0600
831     or die "$output: $!\n";
832     close $fh or do { my $error = $!; unlink $output; die "$output: $error\n" };
833    
834     my $cv = AE::cv ();
835     my $log;
836     my $process = eval {
837     AnyEvent::Util::run_cmd ([
838     "patch", "--verbose", "--batch", "--forward", "--binary", "--fuzz=0",
839     "--no-backup-if-mismatch", "--reject-file=-", "--output=$output", "--", $input,
840     ],
841     "<" => \$normalized,
842     ">" => \$log,
843     close_all => 1,
844     on_prepare => sub {
845     $ENV{LC_ALL} = "C";
846     chdir $directory or die "$directory: $!\n";
847     defined POSIX::dup2 (1, 2) or die "dup2: $!\n";
848     },
849     );
850     };
851    
852     if ($@) {
853     my $error = $@;
854     unlink $output;
855     die $error;
856     }
857    
858     $process->cb (sub {
859     my $hunks;
860     eval { $hunks = check_patch_output $_[0]->recv, $log, $max_offset; 1 } or do {
861     my $error = $@;
862     unlink $output;
863     $cv->croak ($error);
864     return;
865     };
866    
867     $cv->send ($hunks);
868     });
869    
870     $cv
871     }
872    
873 root 1.1 sub _clean_text($) {
874     my ($text) = @_;
875    
876     my ($prefix) = (join "\n", grep /\S/, split /\n/, $text)
877     =~ /\A([ \t]*)[^\n]*(?:\n\1[^\n]*)*\z/;
878    
879     $text =~ s/^\Q$prefix\E//mg;
880     $text =~ s/\A\s+//;
881     $text =~ s/\s+\z//;
882     $text
883     }
884    
885     package AnyEvent::MCP::Base;
886    
887     sub new {
888     my ($class, %kv) = @_;
889     bless \%kv, $class
890     }
891    
892     sub event {
893     my ($self, $event, @args) = @_;
894     ($self->{"on_$event"} or return)->($self, @args)
895     }
896    
897     =head1 SEE ALSO
898    
899     L<AnyEvent>, L<https://modelcontextprotocol.io/>
900    
901     =head1 AUTHOR
902    
903     The main author of this module is OpenAI ChatGPT.
904    
905     Additional guidance received by:
906    
907     Marc Lehmann <schmorp@schmorp.de>
908     http://home.schmorp.de/
909    
910     =cut
911    
912     1
913