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