ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/lib/AnyEvent/MCP/Permissions/Helper.pod
Revision: 1.1
Committed: Fri Nov 27 04:27:58 2026 UTC (7 days, 9 hours ago) by root
Branch: MAIN
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 root 1.1 =head1 NAME
2    
3     AnyEvent::MCP::Permissions::Helper - writing and integrating permission helpers
4    
5     =head1 SYNOPSIS
6    
7     A permission helper is an executable. It receives a description of an
8     operation on stdin and returns a permission decision on stdout. It does not
9     need to be written in Perl, link against AnyEvent, or implement MCP.
10    
11     For example, a helper that always refuses unresolved permission requests:
12    
13     #!/bin/sh
14     cat >/dev/null || exit 2
15     exit 1
16    
17     Select a custom helper in the environment of the server or multibroker:
18    
19     export PERL_ANYEVENT_MCP_PERMISSION_HELPER=/absolute/path/to/my-helper
20    
21     The default helper is L<anyevent-mcp-askpermission>, which asks the user
22     using YAD or a terminal. To use an existing general-purpose MCP form
23     renderer instead, run C<anyevent-mcp-askpermission --form> as the helper.
24    
25     =head1 INTRODUCTION
26    
27     An MCP server sometimes needs a decision before it can perform an operation.
28     The permission engine first consults its configured and saved rules. If
29     these do not decide the request, it offers the operation to a permission
30     helper.
31    
32     The helper is a delegated decision-maker, not necessarily a dialog program.
33     It can implement a policy, consult another service, display a graphical
34     dialog, ask on a terminal, or combine these approaches. The engine tells
35     it what choices are available. The helper selects one of them. The engine
36     validates the answer, constructs any persistent rule, and determines
37     the sandbox privileges actually granted to the operation.
38    
39     This separation is useful in three different kinds of helpers:
40    
41     =over
42    
43     =item Application-specific helpers
44    
45     Understand a particular server and its operation metadata. For example,
46     a helper for a known file server can recognize a particular operation
47     in a particular working directory.
48    
49     =item Generic permission helpers
50    
51     Understand decisions, sandbox grants, scope choices and lifetimes.
52     They can display or select these without understanding what an individual
53     server's action or dimension means.
54    
55     =item Generic form renderers
56    
57     Understand neither permissions nor application metadata. They display
58     ordinary MCP elicitation forms and return form answers. The bundled
59     permission-to-form adapter handles the rest.
60    
61     =back
62    
63     You can implement any of these without knowing how rule files are written,
64     how the engine constructs matchers, or how MCP continuations work.
65     This document describes the external contract and how to integrate it.
66     For the Perl calling interface, see L<AnyEvent::MCP::Permissions::Ask>.
67     For the authorization engine and rule format, see
68     L<AnyEvent::MCP::Server::Permissions>.
69    
70     =head1 TUTORIAL
71    
72     =head2 Your first helper
73    
74     Save the following as F<deny-helper> and make it executable:
75    
76     #!/bin/sh
77     cat >/dev/null || exit 2
78     exit 1
79    
80     Configure a server to use it, e.g. (substitute an existing workdir):
81    
82     chmod +x ./deny-helper
83     PERL_ANYEVENT_MCP_PERMISSION_HELPER="$PWD/deny-helper" \
84     mcp-fs --stdio --ask helper --name project /srv/project
85    
86     Run the server through your usual MCP client. The helper is invoked only
87     when a permission check needs a decision; existing allow and deny rules
88     still apply. The new helper denies those unresolved requests without
89     displaying a dialog.
90    
91     Why does it read stdin if it doesn't care about the request? The caller
92     sends a complete JSON object, then closes its input side of the connection.
93     The helper must consume all input through EOF before exiting. An early
94     exit can cause the caller's write to fail. The helper's stdout is reserved
95     for its answer; send diagnostic messages to stderr.
96    
97     The helper equivalent to an unconditional allow-once is:
98    
99     #!/bin/sh
100     cat >/dev/null
101    
102     Use this only when every otherwise-unresolved permission request in that
103     server's policy is supposed to be approved. It approves the requested
104     sandbox grants as well as the operation, including broad privileges
105     when requested. It does not just suppress an annoying dialog.
106    
107     B<Migration warning:> before the semantic helper protocol, empty output
108     with exit status zero was an error. It now means approval. Inspect existing
109     custom helpers, wrappers and dismissal paths before upgrading. In
110     particular, do not let a failed check or a closed dialog accidentally
111     return empty output with exit status zero.
112    
113     =head2 Inspect a real request
114    
115     To see what a server asks for, temporarily use this helper in a trusted
116     test setup:
117    
118     #!/bin/sh
119     cat >&2 || exit 2
120     exit 1
121    
122     It sends the request to the server's diagnostic output, then refuses it.
123     Depending on the server's logging arrangement, stderr might end up in a
124     log file. Permission requests can contain paths, commands, source code,
125     mail-related information and other private data; do not leave such a
126     diagnostic helper enabled indiscriminately.
127    
128     Here is a complete example request from a small illustrative file server
129     called C<example-files>. It has two sandbox grants, with
130     C<workdir-write> implying C<workdir-read>. Unlike real C<mcp-fs>, it
131     offers only these two grants. It asks to read a file in a known project:
132    
133     {
134     "version": 1,
135     "program": "example-files",
136     "name": "project",
137     "tool": "read-file",
138     "action": "read",
139     "action_description": "Read file contents",
140     "reason": "Inspect the project README",
141     "sandbox_implementation": "bubblewrap",
142     "sandbox_grants": ["workdir-read"],
143     "sandbox_grant_closure": ["workdir-read"],
144     "sandbox_grant_choices": ["workdir-read", "workdir-write"],
145     "sandbox_grant_descriptions": {
146     "workdir-read": "Read files in the selected workdir",
147     "workdir-write": "Modify files in the selected workdir"
148     },
149     "selected_workdir": "/srv/project",
150     "paths": ["/srv/project/README"],
151     "dimension_order": ["workdir", "subject"],
152     "dimensions": {
153     "workdir": {
154     "label": "Workdir",
155     "value": "/srv/project",
156     "choices": [
157     {"id": "exact", "label": "This workdir"},
158     {"id": "any", "label": "All workdirs"}
159     ],
160     "default": "exact",
161     "custom_regex": true
162     },
163     "subject": {
164     "label": "File",
165     "value": "/srv/project/README",
166     "choices": [
167     {"id": "exact", "label": "This file"},
168     {"id": "directory", "label": "Files in this directory"}
169     ],
170     "default": "exact"
171     }
172     },
173     "decisions": ["allow-once", "deny-once", "allow-always", "deny-always"],
174     "lifetimes": [
175     {"value": "indefinite", "label": "Indefinite"},
176     {"value": "900", "label": "15 minutes"},
177     {"value": "3600", "label": "1 hour"},
178     {"value": "57600", "label": "16 hours"}
179     ],
180     "lifetime_default": "indefinite"
181     }
182    
183     The actual input is a single JSON line followed by EOF. Pretty-printing
184     here is just for readability. Save this example as F<offer.json> if you
185     want to experiment with the following programs without a running server.
186    
187     A choice's C<id> is what you return to the engine, and its C<label> is
188     what you show to the user. Neither is the current value of the dimension.
189     For example, C<exact> in the workdir dimension means this particular
190     workdir, even when the next request names a different one.
191    
192     Notice also that C<paths> lists affected filenames independently of
193     the dimensions. Another server might not offer a subject dimension at
194     all. A generic helper must not assume that workdirs, filenames, hosts,
195     or even sandbox grants are meaningful to every server.
196    
197     =head2 Make a decision automatically
198    
199     Here is a small Perl helper using the core JSON::PP module. It approves
200     the example server's read operations in one configured workdir when its
201     effective requested grants are exactly C<workdir-read>. Everything else
202     is refused.
203    
204     #!/opt/perl/bin/perl
205     use strict;
206     use JSON::PP ();
207    
208     binmode STDIN, ":raw";
209     binmode STDOUT, ":raw";
210    
211     my $request = JSON::PP::decode_json (do { local $/; <STDIN> });
212    
213     $request->{version} == 1 or exit 2;
214    
215     if (($request->{program} // "") eq "example-files"
216     && ($request->{name} // "") eq "project"
217     && ($request->{sandbox_implementation} // "") eq "bubblewrap"
218     && $request->{action} eq "read"
219     && ($request->{dimensions}{workdir}{value} // "") eq "/srv/project"
220     && @{$request->{sandbox_grant_closure}} == 1
221     && $request->{sandbox_grant_closure}[0] eq "workdir-read") {
222     print JSON::PP::encode_json { decision => "allow-once" }, "\n";
223     exit 0;
224     }
225    
226     print JSON::PP::encode_json {
227     decision => "deny-once",
228     message => "Outside the configured read policy.",
229     }, "\n";
230    
231     Adjust the Perl interpreter pathname for your installation. With the
232     example offer, the helper prints:
233    
234     {"decision":"allow-once"}
235    
236     If the engine instead requests C<workdir-write>, this policy refuses
237     the operation, even though the grant also implies C<workdir-read>.
238     The implication closure, rather than a search for the name C<read> in
239     a description, makes this distinction easy.
240    
241     This example assumes that you control the server and trust it to describe
242     and enforce its own operation semantics. The strings C<program>, C<name>
243     and C<sandbox_implementation> are not authentication credentials. Do not
244     reuse this policy for an arbitrary remote server just because it claims
245     to be the example application.
246    
247     =head2 Delegate requests you don't recognize
248    
249     Usually you don't want to refuse every operation that your automatic
250     policy does not understand. Delegate the rest to the standard interactive
251     helper. Since the original request has already been read, pass it to a new
252     helper process, for example:
253    
254     #!/opt/perl/bin/perl
255     use strict;
256     use JSON::PP ();
257    
258     binmode STDIN, ":raw";
259     binmode STDOUT, ":raw";
260    
261     my $input = do { local $/; <STDIN> };
262     my $request = JSON::PP::decode_json $input;
263     $request->{version} == 1 or exit 2;
264    
265     # insert your application-specific policy here
266     if (($request->{program} // "") eq "example-files"
267     && ($request->{name} // "") eq "project"
268     && ($request->{sandbox_implementation} // "") eq "bubblewrap"
269     && $request->{action} eq "read"
270     && ($request->{dimensions}{workdir}{value} // "") eq "/srv/project"
271     && @{$request->{sandbox_grant_closure}} == 1
272     && $request->{sandbox_grant_closure}[0] eq "workdir-read") {
273     print '{"decision":"allow-once"}', "\n";
274     exit 0;
275     }
276    
277     open my $helper, "|-", "anyevent-mcp-askpermission"
278     or die "Cannot start permission helper: $!\n";
279     binmode $helper, ":raw";
280     print {$helper} $input or die "Cannot write permission request: $!\n";
281     close $helper and exit 0;
282     exit 2;
283    
284     The delegated helper inherits stdout and stderr. It returns its explicit
285     JSON answer directly to the original caller. This example delegates to
286     the bundled helper, which normally returns explicit JSON and exits zero,
287     including on refusal. For a different helper using the exit-status
288     shorthand, propagate a deliberate normal exit 1 as well; do not confuse
289     a signal or arbitrary failure with an approval.
290    
291     You can also use the asynchronous helper runner in
292     L<AnyEvent::MCP::Permissions::Ask>. That is useful if your program has
293     its own event loop or must manage the lifetime of a delegated process.
294     In a production wrapper, arrange for cancellation to reach any
295     subprocesses you start. The caller can terminate the wrapper without
296     necessarily terminating its descendants.
297    
298     =head2 Return a persistent choice
299    
300     For the example offer, this answer creates an allowance covering files
301     in the same directory, on the selected workdir, for one hour:
302    
303     {
304     "decision": "allow-always",
305     "scopes": {
306     "workdir": "exact",
307     "subject": "directory"
308     },
309     "sandbox_grants": ["workdir-read"],
310     "lifetime": "3600"
311     }
312    
313     The engine constructs the rule and computes the expiry. There is no
314     absolute timestamp, matcher or rule-file pathname in the answer.
315    
316     You can select a different set of grants for future invocations:
317    
318     {
319     "decision": "allow-always",
320     "scopes": {"workdir": "exact", "subject": "exact"},
321     "sandbox_grants": ["workdir-write"],
322     "lifetime": "900"
323     }
324    
325     In this example, the current invocation still receives only
326     C<workdir-read>. The saved rule permits future requests needing
327     C<workdir-write> (and its implied read authority), provided their action
328     and other scopes match. It does not authorize a different action, such
329     as writing a file when the server calls that action C<write>.
330    
331     A persistent denial can carry a message and select an affected file:
332    
333     {
334     "decision": "deny-always",
335     "scopes": {"workdir": "exact", "subject": "directory"},
336     "path": "/srv/project/README",
337     "message": "Read the maintained documentation instead.",
338     "lifetime": "3600"
339     }
340    
341     Here a future request must match the selected workdir and subject
342     scope and include that exact path to match this denial. To deny across
343     all paths within the selected dimensions, use C<"path": null>.
344    
345     For a generic helper, a perfectly reasonable rule editor just displays
346     one choice per dimension and uses the offered defaults as initial
347     selections. To produce the persistent answer, copy the selected IDs,
348     the selected grant names and the selected lifetime into the result.
349     Don't try to manufacture wider scopes from labels or values.
350    
351     =head2 Use a generic form renderer
352    
353     If your program already displays MCP forms, it doesn't have to implement
354     a permission rule editor. Create a permission helper wrapper:
355    
356     #!/bin/sh
357     exec anyevent-mcp-askpermission --form
358    
359     Set C<PERL_ANYEVENT_MCP_PERMISSION_HELPER> to that wrapper and
360     C<PERL_ANYEVENT_MCP_ELICITATION_HELPER> to your form renderer. These are
361     separate executables. The adapter receives a semantic permission offer,
362     creates a normal form, and invokes the renderer. If the answer selects
363     a persistent decision, the adapter invokes the renderer again with
364     the scope, lifetime and grant form. Back returns to the first form.
365     The adapter returns one final semantic answer to the caller.
366    
367     The renderer sees an object such as this (a small ordinary form, not
368     a permission offer):
369    
370     {
371     "mode": "form",
372     "message": "Choose which grants to allow",
373     "requestedSchema": {
374     "type": "object",
375     "required": ["decision"],
376     "properties": {
377     "decision": {
378     "type": "string",
379     "enum": ["back", "allow-always"],
380     "default": "allow-always"
381     },
382     "sandbox_grants": {
383     "type": "array",
384     "items": {
385     "anyOf": [
386     {"const": "workdir-read", "title": "Read files"},
387     {"const": "workdir-write", "title": "Modify files"}
388     ]
389     },
390     "default": ["workdir-read"]
391     }
392     }
393     }
394     }
395    
396     A form answer is ordinary MCP elicitation content, e.g.:
397    
398     {
399     "action": "accept",
400     "content": {
401     "decision": "allow-always",
402     "sandbox_grants": ["workdir-read"]
403     }
404     }
405    
406     C<action> here describes the form interaction, not the permission
407     decision. An accepted form can contain a permission denial. Declining
408     or cancelling a permission form means deny once.
409    
410     Unlike the permission helper, a form renderer must write a JSON
411     response even for cancellation or refusal. Empty successful output
412     is an error. See L<anyevent-mcp-form-elicitation> for the supported
413     form interface. The built-in renderer is available on Unix via YAD
414     or a terminal. Your own renderer can use other UI facilities without
415     linking against AnyEvent.
416    
417     =head1 PROCESS PROTOCOL REFERENCE
418    
419     =head2 Invocation and framing
420    
421     A helper is started for one permission request. There is no initialization
422     handshake or ongoing session. It inherits the caller's environment and
423     runs under the caller's OS user, outside the tool's worker sandbox.
424    
425     Stdin contains exactly one UTF-8 encoded JSON object, serialized on one
426     line, followed by LF and EOF. JSON escapes embedded newlines in strings.
427     Read through EOF even if you already have the answer. In particular,
428     bare C</bin/true> and C</bin/false> are not reliable helpers with the
429     current transport, because they can exit without consuming the input.
430    
431     Write exactly one complete UTF-8 JSON object to stdout, optionally
432     followed or surrounded by JSON whitespace, then exit. Output need not
433     be on one line. Use a JSON encoder for strings and non-ASCII data.
434     Do not print prompts, banners, progress messages or diagnostics on
435     stdout. Do not use protocol stdin for interactive input; open a separate
436     terminal or graphical interface.
437    
438     There is one final answer for the whole request. The helper can present
439     multiple screens or make multiple internal decisions, but cannot send
440     an intermediate answer or ask the engine to prepare another screen.
441     The form adapter described above is a local utility for doing so.
442    
443     =head2 Exit status and output
444    
445     The result is interpreted after the process has exited and stdout has
446     reached EOF:
447    
448     =over
449    
450     =item Normal exit 0, exactly zero stdout bytes
451    
452     Equivalent to C<{"decision":"allow-once"}>.
453    
454     =item Normal exit 1, exactly zero stdout bytes
455    
456     Equivalent to C<{"decision":"deny-once"}>.
457    
458     =item Normal exit 0, one valid JSON object on stdout
459    
460     Interpret the object as a semantic permission answer, as specified below.
461     A syntactically valid object can still be rejected by the engine.
462    
463     =item All other combinations
464    
465     Helper failure. This includes whitespace-only output, JSON values other
466     than objects, multiple JSON values, exit 1 with output, other nonzero
467     exit statuses, and termination by signal. Use exit 2 or another status
468     above 1 for errors with no answer.
469    
470     =back
471    
472     A process-start or transport error, timeout, cancellation or output
473     size overflow is also a failure, regardless of exit status. No failure
474     grants permission. The default permission helper timeout is 300 seconds
475     and the default output limit is 1 MiB. Callers may configure other limits.
476     The caller can cancel a pending helper; close your UI and terminate any
477     subprocesses you own when interrupted. Do not return a successful empty
478     answer from an error or cancellation handler.
479    
480     The timeout includes the complete helper interaction. In native MCP mode,
481     the server also has a continuation deadline; time spent in a broker's
482     queue or displaying a dialog counts against that deadline.
483    
484     =head1 SEMANTIC REQUEST REFERENCE
485    
486     All requests have the following common fields. JSON object member order
487     has no significance. Read the fields supplied by the engine rather than
488     reconstructing an offer from the server's name or current application
489     configuration. Ignore unfamiliar descriptive fields that your helper
490     does not need; do not automatically approve operations whose authority
491     you do not understand.
492    
493     =over
494    
495     =item version (integer)
496    
497     Protocol version, currently C<1>. A helper that cannot interpret the
498     version should report a failure rather than guess.
499    
500     =item action (string)
501    
502     The server-defined class of authority being requested. E.g. C<read>,
503     C<exec>, or a completely different application-specific action. It is
504     not necessarily the MCP tool name. Persistent decisions are scoped to
505     this action; the helper cannot change it.
506    
507     =item reason (string)
508    
509     A nonblank human-readable explanation of the operation. It can be
510     multiline and can contain text supplied by an MCP caller. It is not
511     proof that the operation has the effects claimed in the explanation.
512    
513     =item decisions (array of strings)
514    
515     Available decision values. The current engine always offers
516     C<allow-once> and C<deny-once>. It also offers C<allow-always> and
517     C<deny-always> unless a dimension has no persistent scope choices.
518     Use the offered list; do not display or return unavailable decisions.
519    
520     =item sandbox_grants (array of strings)
521    
522     Grant names requested for this operation. An empty array is valid.
523     These are the names that would normally be approved by allow-once.
524     The server may have expanded the caller's requested grants to describe
525     actual effective worker privileges.
526    
527     =item sandbox_grant_closure (array of strings)
528    
529     The requested grants including all transitively implied grant names,
530     sorted by name. For example, if C<write> implies C<read>, requesting
531     C<write> can produce C<["read","write"]> here. This field is useful
532     for automatic policies checking what authority an operation needs.
533     It is not a list of additional grants the helper must explicitly
534     return. The engine computes grant implications; the offer does not
535     include the complete implication graph for arbitrary selections.
536    
537     =item sandbox_grant_choices (array of strings)
538    
539     All available grant names, sorted by name. A helper can select a subset
540     of this list for an allowance, including the empty set. This is not
541     limited to the grants requested by the current operation.
542    
543     =item sandbox_grant_descriptions (object)
544    
545     Maps grant names to explanatory text. It can be empty, and individual
546     names need not have descriptions. The server may customize the text for
547     a particular workdir. Display grant names as well as their descriptions.
548     Descriptions are not an authorization language.
549    
550     =item dimensions (object)
551    
552     Maps dimension names to objects describing independent scope axes.
553     An empty object means there are no dimension constraints to choose.
554     See L</Dimension objects> below.
555    
556     =item lifetimes (array of objects)
557    
558     Available persistent rule lifetimes, in presentation order. Each object
559     has C<value> (a string identifying the lifetime) and C<label> (display
560     text). Currently the values are C<indefinite>, C<900>, C<3600> and
561     C<57600>. Numeric-looking values are strings representing seconds.
562     Select an offered value, not an absolute timestamp or a new duration.
563    
564     =item lifetime_default (string)
565    
566     The proposed initial lifetime selection. The engine uses this value
567     if a persistent answer omits the lifetime. The default is normally
568     C<indefinite>, but may reflect remembered user preferences.
569    
570     =back
571    
572     =head2 Additional request metadata
573    
574     These fields enrich the request without introducing new saved-rule
575     dimensions. Not every server supplies them; some of the string-valued
576     fields can be JSON null. Treat missing and null optional context as
577     unavailable, not as a wildcard identity.
578    
579     =over
580    
581     =item name (string or null)
582    
583     The permission profile's name, often also the configured server
584     instance name. This is not necessarily the program name.
585    
586     =item program (string or null)
587    
588     Application/program name, e.g. C<mcp-fs>. Useful for selecting an
589     application-specific helper or presenting a heading. Simple servers
590     normally derive this from their executable name unless configured
591     otherwise.
592    
593     =item multibroker_alias (string, optional)
594    
595     The alias under which a child is known to a multibroker, when supplied
596     by the server's environment. Not a substitute for authenticated
597     server identity.
598    
599     =item tool (string or null)
600    
601     The dispatched MCP tool name when known, otherwise the application's
602     supplied tool context. It can differ from C<action>. The permission
603     rule is not selected by changing this field.
604    
605     =item action_description (string or null)
606    
607     A server-provided human-readable description of the action.
608    
609     =item sandbox_implementation (string or null)
610    
611     Description of the worker enforcement mechanism, e.g. C<bubblewrap>
612     or C<NONE - UNSANDBOXED (full host-user privileges)>. Do not infer
613     that a worker is isolated merely because a grant list is present.
614    
615     =item selected_workdir (string, optional)
616    
617     The logical workdir identity selected for the operation, currently
618     supplied by mcp-fs. It can be present even when no workdir permission
619     dimension is needed, for example when the requested privileges span
620     all workdirs. Do not confuse it with a resolved physical mount path.
621    
622     =item dimension_order (array of strings, optional)
623    
624     Preferred display order of dimension names. Names not included in
625     this list follow in alphabetical order. It has no effect on matching.
626    
627     =item paths (array of strings, optional)
628    
629     Affected filenames. They can be shown as context and selected for
630     an exact-file persistent denial. They do not offer a path-based
631     allowance or constrain sandbox access. See L</Answer fields> for
632     the exact denial semantics.
633    
634     =item details (object, optional)
635    
636     Maps plain display labels to Unicode text, e.g.
637     C<"View patch"> to the proposed patch or C<"View stdin"> to a
638     command's input. These details can be large and contain control
639     characters. Display them as text, not as markup, terminal commands
640     or executable content. If you truncate a preview, identify it as
641     incomplete. A producer may itself supply an explicitly marked
642     preview rather than the full underlying bytes.
643    
644     The bundled UI limits each displayed detail to 65536 characters.
645     That is a display limit, not a limit on the semantic helper's input.
646     The details are not automatically saved as rule constraints.
647    
648     =item context (object, optional)
649    
650     Application-specific structured information about the actual operation.
651     A generic permission helper need not interpret it. An application-specific
652     helper should consult the documentation or code of the application
653     it supports. This is not a standardized set of tool arguments.
654    
655     For example, mcp-fs exec currently supplies a context such as:
656    
657     {
658     "argv": ["perl", "-Ilib", "-c", "lib/Foo.pm"],
659     "stdin_bytes": 0,
660     "stdin_encoding": "utf-8"
661     }
662    
663     C<argv> is the actual argument vector, not a shell command line.
664     C<stdin_bytes> counts the encoded input octets. C<stdin_encoding>
665     is C<utf-8>, C<latin1> or C<base64>. Nonempty UTF-8 stdin is supplied
666     as C<details> text; non-UTF-8 input uses an escaped byte preview
667     (currently limited to 4096 bytes). Do not mistake that preview for
668     the original input or assume that two equal argv vectors execute the
669     same program if their input differs.
670    
671     In the same example, mcp-fs offers a C<subject> dimension whose
672     value is a JSON-encoded argv vector. Its choices have semantic IDs
673     C<command> (exact argv), C<prefix> (through the first separate
674     C<--> argument, if present), C<executable> (any arguments to the
675     same executable), and C<any-command>. The application defines these
676     scope semantics. Prefer C<context.argv> to parsing a displayed command
677     label, and return an offered scope ID rather than constructing an
678     argv regex.
679    
680     =back
681    
682     =head2 Dimension objects
683    
684     Dimension names match C<[a-z][a-z0-9_-]*>. Names and their meanings are
685     chosen by the application. The engine can also add a C<user> dimension
686     for an authenticated user, with C<exact> and C<any> choices.
687    
688     Each dimension has the following members:
689    
690     =over
691    
692     =item label (string)
693    
694     Human-readable name of the dimension, e.g. C<Workdir> or C<Origin>.
695    
696     =item value (nonempty string)
697    
698     The current value, e.g. C</srv/project>. It is the identity against
699     which the saved matcher operates. It can be a structured value encoded
700     as a string, as with an exec argv vector.
701    
702     =item choices (array of objects)
703    
704     Ordered list of available persistent scopes. Every entry has:
705    
706     {"id": "exact", "label": "This workdir"}
707    
708     C<id> is the exact selection value to return. It is unique within this
709     dimension. Application-defined stable IDs match C<[a-z][a-z0-9_-]*>.
710     If the application did not give a choice an ID, the engine supplies
711     C<#0>, C<#1>, etc., using the zero-based position in the offered list.
712     These anonymous IDs are only meaningful in the current offer.
713    
714     Even a stable ID identifies a scope I<kind>, not the actual object
715     or matcher. Its meaning is defined by the application's action and
716     dimension, not by the generic protocol. Do not assume that IDs such
717     as C<exact> or C<any> exist for all dimensions.
718    
719     An empty choice list prevents persistent decisions for the whole offer.
720     A single choice need not be explicitly selected in a persistent
721     answer. Multiple choices require an explicit selection.
722    
723     =item default (string, present when choices exist)
724    
725     ID of the proposed initial selection. It can come from the application's
726     default, a remembered stable choice, or the first choice. Use it to
727     preselect an option, not to infer that the user has already approved it.
728     The engine does not implicitly fill in an omitted multi-choice scope
729     from this value.
730    
731     =item custom_regex (boolean true, optional)
732    
733     A local helper may supply a custom Perl regular expression in place
734     of a choice ID. The engine only offers this when the dimension already
735     has a completely unrestricted matcher. It is absent from native MCP
736     offers, including permission-aware ones. Omission means custom regexes
737     are not available.
738    
739     =back
740    
741     =head1 SEMANTIC ANSWER REFERENCE
742    
743     The answer is a JSON object with C<decision> and, when needed, further
744     selection fields. Return only the fields relevant to that decision.
745     Unknown top-level answer fields are rejected. Do not send back the
746     request, its matchers, a rule, or a fabricated offer.
747    
748     =head2 Decisions
749    
750     =over
751    
752     =item allow-once
753    
754     Approve the current permission request. If no grant selection is
755     supplied, approve all requested grants. You can explicitly approve a
756     smaller set.
757    
758     {"decision":"allow-once"}
759    
760     {"decision":"allow-once","sandbox_grants":["workdir-read"]}
761    
762     =item deny-once
763    
764     Refuse this permission request, optionally with a message. No rule is
765     saved.
766    
767     {"decision":"deny-once","message":"Use the dedicated read tool."}
768    
769     =item allow-always
770    
771     Approve an operation and save an allowance for future matching requests.
772     Select each multi-choice dimension and the future grant set. A rule can
773     expire; C<always> means persistent rather than necessarily indefinite.
774    
775     {
776     "decision":"allow-always",
777     "scopes":{"workdir":"exact","subject":"directory"},
778     "sandbox_grants":["workdir-read"],
779     "lifetime":"3600"
780     }
781    
782     =item deny-always
783    
784     Refuse the operation and save a denial for future matching requests.
785     Select each multi-choice dimension and, if affected paths were offered,
786     the exact path or all-path scope. A message and lifetime are optional.
787    
788     {
789     "decision":"deny-always",
790     "scopes":{"workdir":"exact","subject":"directory"},
791     "path":null,
792     "message":"Not in this project."
793     }
794    
795     =back
796    
797     Only return decision values present in the offer. There is no semantic
798     C<back>, C<cancel>, C<ask>, or C<allow> decision. Implement Back within
799     your UI; for an ordinary refused or dismissed permission prompt, return
800     C<deny-once>. A cancelled or failed process must not approve anything.
801    
802     =head2 Answer fields
803    
804     =over
805    
806     =item decision (string, required)
807    
808     One of the offered decisions described above.
809    
810     =item sandbox_grants (array of strings, allowance only)
811    
812     Selected names from C<sandbox_grant_choices>. Omission for allow-once
813     means the requested grants; an explicit empty array means no sandbox
814     grants. For allow-always an explicit array is required when any grants
815     are available, even when the selected array is empty. For a grant-free
816     server it can be omitted.
817    
818     The engine takes grant implications into account. For the present
819     operation, it grants at most the intersection of the closure of the
820     requested grants and the closure of the selected grants. If all
821     requested authority is covered, it returns the original requested
822     names to the application. Otherwise it returns the names in the
823     intersection. The worker may refuse to proceed if an essential grant
824     was removed.
825    
826     For allow-always, the rule stores the selected names for future
827     operations, not just the intersection. For example, selecting
828     C<write> for a current C<read> request cannot give the current worker
829     write authority, but can allow a future matching request for write
830     authority if C<write> implies C<read>.
831    
832     Denial rules do not have a helper-selected grant set. The engine
833     uses the original requested grants. A denial without an exact path
834     normally matches future requests that include all the denied grants,
835     including implications. An exact-path denial instead checks the
836     affected paths and ignores the grant-set restriction.
837    
838     =item scopes (object, persistent decisions only)
839    
840     Map each dimension name to the selected offered ID. Omit a dimension
841     only if it offers exactly one choice. If there are no dimensions,
842     C<scopes> may be omitted or be an empty object. Do not include
843     unoffered dimension names.
844    
845     For a dimension that advertises C<custom_regex>, a local semantic helper
846     may instead supply an object containing exactly one C<regex> member:
847    
848     {
849     "decision": "allow-always",
850     "scopes": {
851     "workdir": {"regex": "^/srv/project(?:/|$)"},
852     "subject": "exact"
853     },
854     "sandbox_grants": ["workdir-read"]
855     }
856    
857     The expression is a Perl regex string beginning with a literal C<^>.
858     It must compile and match the dimension's actual current value.
859     Executable Perl code in a regex is not supported. Use JSON escaping
860     for any regex backslashes. The engine only allows this escape hatch
861     when it already offers unrestricted scope for that dimension. The
862     expression cannot change the action or any other dimension.
863    
864     A regex is not evaluated against the human-readable label or
865     C<context>. It operates on the dimension's C<value> string. It will
866     also be used for future rule matching, so keep it efficient and
867     understand what it will match. Use an ordinary offered scope whenever
868     possible. Native MCP clients cannot supply custom regexes, and the
869     bundled interactive helper/form adapter doesn't offer a regex editor.
870    
871     =item lifetime (string, persistent decisions only)
872    
873     One of the offered C<lifetimes> values. If omitted, the engine uses the
874     C<lifetime_default> from the offer that was presented, not a later
875     preference setting. Use the string C<"indefinite"> for no expiry.
876     The engine converts a finite duration into an absolute expiry when
877     it saves the rule. The helper does not calculate it.
878    
879     =item path (string or null, deny-always only)
880    
881     If C<paths> contains affected filenames, select one exact offered
882     nonempty filename, or JSON null for a denial not restricted by filename.
883     This selection is required when paths are offered; do not silently
884     omit it to broaden the denial. Without offered paths it can be
885     omitted.
886    
887     A path-specific denial still uses all selected dimensions and the
888     original action. It matches if the future operation includes the exact
889     path, even when it also affects other paths or requests different grants.
890     There is no path-specific allowance in this interface.
891    
892     =item message (string or null, denials only)
893    
894     Optional explanation returned to the caller with the denial.
895     Maximum 2048 characters, without CR or LF. Whitespace-only messages
896     are treated as absent. On a persistent denial the explanation is saved
897     with the rule. Do not put secrets in it or assume that only the user
898     who saw the dialog will see it. Messages do not change the scope.
899    
900     =back
901    
902     The engine rechecks the original permission request and policy when
903     an answer arrives, under its rule-file lock where applicable. A policy
904     change can supersede the helper's decision. Otherwise the engine
905     validates the selections against the original offer, constructs any
906     rule, saves it and remembers applicable stable IDs and lifetime
907     preferences. A save failure is an error, not a successful permanent
908     approval. Concurrent preference changes alone do not invalidate an
909     otherwise matching offer.
910    
911     =head1 CONFIGURATION AND INTEGRATION
912    
913     =head2 Standalone servers
914    
915     The shared server permission settings are described in
916     L<AnyEvent::MCP::Server::Permissions> and
917     L<AnyEvent::MCP::Server::Simple>. In particular:
918    
919     =over
920    
921     =item PERL_ANYEVENT_MCP_PERMISSION_HELPER
922    
923     Path or name of a permission helper executable. The default is
924     C<anyevent-mcp-askpermission>. This variable is not a shell command;
925     it does not parse shell syntax, split arguments, or expand a tilde.
926     Use a wrapper executable for arguments, pipelines or other shell logic.
927    
928     =item PERL_ANYEVENT_MCP_PERMISSION_ASK
929    
930     Default asking mode. The shared C<--ask MODE> option overrides it,
931     as does an explicit application setting. The default is C<helper>.
932    
933     =item --ask helper
934    
935     Use the configured local permission helper. This is the mode to
936     choose if the MCP client does not itself make permission decisions.
937    
938     =item --ask tty / --ask yad
939    
940     Force the bundled interactive helper in the specified mode, ignoring
941     the custom executable setting. Neither mode falls back to another UI.
942    
943     =item --ask mcp
944    
945     Delegate to a trusted modern MCP client that advertises form
946     elicitation. Do not invoke a server-local helper if native forms are
947     unavailable or declined.
948    
949     =item --ask auto
950    
951     Use native forms when available for the request, otherwise the local
952     helper. A native refusal does not cause a second local prompt.
953    
954     =item --ask none
955    
956     Deny otherwise-unresolved permission checks without prompting.
957     Existing automatic and saved rules still apply.
958    
959     =item PERL_ANYEVENT_MCP_ELICITATION_HELPER
960    
961     Path or name of an ordinary MCP form renderer, not a permission
962     helper. Used by the generic form adapter and local ordinary form
963     handling. Default C<anyevent-mcp-form-elicitation>. For forced
964     C<--tty> or C<--yad> mode the adapter uses the corresponding bundled
965     renderer instead.
966    
967     =back
968    
969     A Perl server can select a helper executable and arguments directly
970     when constructing its permission engine:
971    
972     my $permissions = AnyEvent::MCP::Server::Permissions->new (
973     name => "example",
974     ask => "helper",
975     helper => ["anyevent-mcp-askpermission", "--form"],
976     );
977    
978     The constructor also accepts a local asynchronous C<ask> callback
979     that receives the public semantic offer and returns a semantic
980     answer via its completion callback. See the engine's Perl API.
981     Do not pass its private prepared request to an external helper.
982    
983     =head2 Multibrokers
984    
985     The multibroker can collect permission decisions for downstream servers.
986     For example, configure the helper on the multibroker machine:
987    
988     PERL_ANYEVENT_MCP_PERMISSION_HELPER=/absolute/path/to/my-helper \
989     mcp-multibroker --stdio --ask helper \
990     files 'stdio:mcp-fs --name project /srv/project'
991    
992     By default, the multibroker sets C<PERL_ANYEVENT_MCP_PERMISSION_ASK=mcp>
993     for spawned stdio children. The child asks its MCP client (the
994     multibroker), which handles the prompt locally or forwards it upstream.
995     An explicit child asking mode overrides this default. Independently
996     running HTTP servers must be configured to delegate permission prompts
997     if you want the multibroker to handle them.
998    
999     In local helper mode, the multibroker recognizes permission offers
1000     using the native extension below and invokes the semantic permission
1001     helper. Ordinary MCP elicitation requests go to the ordinary form
1002     renderer instead. The multibroker serializes its local prompts.
1003    
1004     With C<--ask mcp>, modern native input requests are forwarded upstream
1005     instead. With C<--ask auto>, native forms are forwarded when the
1006     upstream client advertises support; otherwise they are handled locally.
1007     C<--ask none> declines downstream form requests. With C<--ask tty>
1008     or C<--ask yad>, the built-in renderer appropriate to the request
1009     is forced. For a child which doesn't support the permission extension,
1010     the multibroker can only handle the ordinary form the child sends.
1011    
1012     =head2 Native MCP integration
1013    
1014     You only need this section if you are implementing an MCP client or
1015     broker, not if you are implementing an executable permission helper.
1016    
1017     The modern MCP input-required/retry mechanism (as in MCP 2026-07-28)
1018     can carry ordinary C<elicitation/create> form requests inside
1019     C<inputRequests>. An ordinary form-capable client needs no
1020     AnyEvent::MCP-specific extension to present permission forms.
1021     The server first asks for a decision and, if a persistent decision
1022     was selected, asks for the rule settings in another form. Back
1023     returns to the first form. The server keeps the intermediate state.
1024     The permission helper itself never receives these intermediate forms.
1025    
1026     A client which understands semantic permission offers can avoid the
1027     second network round trip. Advertise both form elicitation and the
1028     following extension in the request's
1029     C<_meta["io.modelcontextprotocol/clientCapabilities"]>:
1030    
1031     {
1032     "elicitation": {"form": {}},
1033     "extensions": {
1034     "de.schmorp.anyevent-mcp/permission": {"version": 1}
1035     }
1036     }
1037    
1038     Only advertise the extension if you can actually handle the complete
1039     form and associated offer. It is an application extension, not part
1040     of MCP's standard elicitation schema. It does not grant new authority
1041     or change which operations require permission.
1042    
1043     For an unresolved permission check, the server now returns
1044     C<resultType: "input_required">, an opaque C<requestState>, and an
1045     ordinary, complete C<elicitation/create> form under
1046     C<inputRequests.permission>. The enclosing result's C<_meta> contains
1047     a map under C<de.schmorp.anyevent-mcp/permission>, keyed by the
1048     corresponding input request ID. The value is the semantic offer
1049     described above, without C<custom_regex>.
1050    
1051     Structurally, the result is:
1052    
1053     resultType: "input_required"
1054     requestState: OPAQUE STATE
1055     inputRequests:
1056     permission:
1057     method: "elicitation/create"
1058     params: COMPLETE MCP FORM PARAMETERS
1059     _meta:
1060     de.schmorp.anyevent-mcp/permission:
1061     permission: SEMANTIC OFFER
1062    
1063     The above is a schematic representation, not literal JSON.
1064     The offer is in the outer result metadata, not inside elicitation
1065     parameters and not in the response's metadata. This allows the form
1066     itself and its response to remain ordinary flat MCP data.
1067    
1068     Invoke your permission helper with the semantic offer once. Turn
1069     its final answer into C<{"action":"accept","content":{...}}> using the
1070     following mapping:
1071    
1072     =over
1073    
1074     =item decision, message, sandbox_grants, lifetime
1075    
1076     Use the corresponding semantic answer fields unchanged where relevant
1077     and offered by the schema. Grants are an array of strings, not a
1078     comma-separated string. If no grant choices exist, the schema omits
1079     that field; omit it from the form answer too.
1080    
1081     =item scopes
1082    
1083     Flatten each selected C<scopes.NAME> ID into a string-valued
1084     C<dim_NAME> form field. Do not include the nested scopes object.
1085     The complete form includes singleton dimensions as optional fields,
1086     so they can still be omitted. Custom regex objects are not allowed.
1087    
1088     =item path
1089    
1090     Use the selected exact path string, or the empty string for all paths.
1091     JSON null is the semantic representation of all paths, not the form
1092     representation.
1093    
1094     =back
1095    
1096     The complete form contains the relevant decision, message and grant
1097     fields and, when persistence is offered, fields for scopes, lifetime
1098     and any denial path. Since ordinary MCP form schemas are flat, these
1099     additional fields are optional in the schema. The engine requires the
1100     appropriate selections according to the chosen decision. A client
1101     must not simply omit a multi-choice scope or an offered denial path
1102     and expect the server to assume a default.
1103    
1104     For example, the persistent allowance from the tutorial, after
1105     flattening, becomes this ordinary input response:
1106    
1107     {
1108     "action": "accept",
1109     "content": {
1110     "decision": "allow-always",
1111     "dim_workdir": "exact",
1112     "dim_subject": "directory",
1113     "sandbox_grants": ["workdir-read"],
1114     "lifetime": "3600"
1115     }
1116     }
1117    
1118     An explicit semantic denial can likewise be returned using
1119     C<action: "accept"> with C<decision: "deny-once"> or C<deny-always>
1120     in the content. C<action: "decline"> and C<action: "cancel"> both
1121     mean deny once, and cannot carry persistent scope choices.
1122     The empty-output shorthand is interpreted by the local helper runner,
1123     not sent as empty MCP input.
1124    
1125     Retry the original MCP method and arguments with the returned
1126     C<requestState> and the form response under
1127     C<inputResponses.permission>. For example, for the tutorial's
1128     fictional read-file tool:
1129    
1130     {
1131     "name": "read-file",
1132     "arguments": {"path": "/srv/project/README"},
1133     "requestState": "STATE-RETURNED-BY-SERVER",
1134     "inputResponses": {
1135     "permission": {
1136     "action": "accept",
1137     "content": {"decision": "allow-once"}
1138     }
1139     }
1140     }
1141    
1142     The state string above is a placeholder; copy the actual opaque
1143     state verbatim. Keep the original authenticated user, method and
1144     arguments. Each state is single-use and expires. A subsequent
1145     input-required result can request a different permission check in
1146     the same tool invocation; handle that new offer separately.
1147     A complete form is one round for one permission check, not a guarantee
1148     that the tool will never ask again.
1149    
1150     With the Perl client implementation, C<on_request> receives a
1151     L<AnyEvent::MCP::Client::Request> object containing the outer
1152     metadata in C<input_result_meta>. Use
1153     C<AnyEvent::MCP::Permissions::Ask::permission_offer> to identify
1154     a permission offer and the C<elicitation> method to invoke the helper,
1155     flatten the answer and reply:
1156    
1157     use AnyEvent::MCP::Permissions::Ask ();
1158    
1159     # options for AnyEvent::MCP::Client::HTTP or ::JSONL
1160     my %options = (
1161     client_capabilities => {
1162     elicitation => { form => {} },
1163     extensions => {
1164     "de.schmorp.anyevent-mcp/permission" => { version => 1 },
1165     },
1166     },
1167     on_request => sub {
1168     my ($client, $req) = @_;
1169    
1170     if (AnyEvent::MCP::Permissions::Ask::permission_offer $req) {
1171     AnyEvent::MCP::Permissions::Ask->elicitation ($req);
1172     } elsif ($req->{method} eq "elicitation/create") {
1173     $req->reply ({ action => "decline" });
1174     } else {
1175     $req->error (-32601, "Unsupported input request");
1176     }
1177     },
1178     );
1179    
1180     This example deliberately declines unrelated forms. In a general client,
1181     route those forms to your own renderer instead. The Perl client manages
1182     the continuation and cancellation for C<call>; raw C<rpc> returns
1183     input-required results intact. See L<AnyEvent::MCP::Client>.
1184    
1185     =head1 TRUST AND IMPLEMENTATION NOTES
1186    
1187     The engine decides what authority can be selected, not whether selecting
1188     it is a good idea. A configured helper is trusted to make that latter
1189     decision. It can authorize every offered operation, including one with
1190     broad sandbox grants, without user interaction. It also executes with
1191     the caller's operating-system privileges. Install and configure helper
1192     executables with the same care as other trusted server-side code.
1193    
1194     A native MCP client selected to make permission decisions is likewise
1195     trusted, including the original user assertions accepted by the
1196     permission engine in that mode. A remote server's program name, profile,
1197     labels and context do not establish its identity; use a trusted connection
1198     and routing configuration for application-specific policies.
1199    
1200     The helper does not execute the authorized operation. It does not
1201     construct the sandbox. The server checks and enforces the returned
1202     authority when it performs the operation. Returning an allowance is
1203     not a guarantee that the operation will succeed, especially if grants
1204     were reduced or the policy changed during prompting.
1205    
1206     For a persistent decision, all selected dimensions constrain the
1207     rule. Information that is merely displayed or supplied in C<context>
1208     does not automatically constrain later operations. For example, a rule
1209     covering the exact command C<perl -> in mcp-fs can cover a future
1210     invocation with different stdin. If your approval depends on information
1211     not covered by an offered scope, prefer a one-time decision.
1212    
1213     =head1 SEE ALSO
1214    
1215     L<anyevent-mcp-askpermission>, L<anyevent-mcp-form-elicitation>,
1216     L<AnyEvent::MCP::Permissions::Ask>, L<AnyEvent::MCP::Helper>,
1217     L<AnyEvent::MCP::Server::Permissions>, L<AnyEvent::MCP::Server::Simple>,
1218     L<AnyEvent::MCP::Client>, L<mcp-multibroker>, L<AnyEvent::MCP::Intro>.
1219    
1220     =cut