ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/cvsroot/AnyEvent-MCP/lib/AnyEvent/MCP/Permissions/Helper.pod
Revision: 1.2
Committed: Fri Nov 27 04:47:12 2026 UTC (6 days, 5 hours ago) by root
Branch: MAIN
CVS Tags: rel-0_92, HEAD
Changes since 1.1: +21 -53 lines
Log Message:
*** empty log message ***

File Contents

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