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