Group
Extension

AnyEvent-MCP/lib/AnyEvent/MCP/Permissions/Helper.pod

=head1 NAME

AnyEvent::MCP::Permissions::Helper - writing and integrating permission helpers

=head1 SYNOPSIS

A permission helper is an executable. It receives a description of an
operation on stdin and returns a permission decision on stdout. It does not
need to be written in Perl, link against AnyEvent, or implement MCP.

For example, a helper that always refuses unresolved permission requests:

   #!/bin/sh
   cat >/dev/null || exit 2
   exit 1

Select a custom helper in the environment of the server or multibroker:

   export PERL_ANYEVENT_MCP_PERMISSION_HELPER=/absolute/path/to/my-helper

The default helper is L<anyevent-mcp-askpermission>, which asks the user
using YAD or a terminal. To use an existing general-purpose MCP form
renderer instead, run C<anyevent-mcp-askpermission --form> as the helper.

=head1 INTRODUCTION

An MCP server sometimes needs a decision before it can perform an operation.
The permission engine first consults its configured and saved rules. If
these do not decide the request, it offers the operation to a permission
helper.

The helper is a delegated decision-maker, not necessarily a dialog program.
It can implement a policy, consult another service, display a graphical
dialog, ask on a terminal, or combine these approaches. The engine tells
it what choices are available. The helper selects one of them. The engine
validates the answer, constructs any persistent rule, and determines
the sandbox privileges actually granted to the operation.

This separation is useful in three different kinds of helpers:

=over

=item Application-specific helpers

Understand a particular server and its operation metadata. For example,
a helper for a known file server can recognize a particular operation
in a particular working directory.

=item Generic permission helpers

Understand decisions, sandbox grants, scope choices and lifetimes.
They can display or select these without understanding what an individual
server's action or dimension means.

=item Generic form renderers

Understand neither permissions nor application metadata. They display
ordinary MCP elicitation forms and return form answers. The bundled
permission-to-form adapter handles the rest.

=back

You can implement any of these without knowing how rule files are written,
how the engine constructs matchers, or how MCP continuations work.
This document describes the external contract and how to integrate it.
For the Perl calling interface, see L<AnyEvent::MCP::Permissions::Ask>.
For using permissions and choosing where to ask, see
L<AnyEvent::MCP::Intro>. For the authorization engine and rule format,
see L<AnyEvent::MCP::Server::Permissions>.

=head1 TUTORIAL

=head2 Your first helper

Save the following as F<deny-helper> and make it executable:

   #!/bin/sh
   cat >/dev/null || exit 2
   exit 1

Configure a server to use it, e.g. (substitute an existing workdir):

   chmod +x ./deny-helper
   PERL_ANYEVENT_MCP_PERMISSION_HELPER="$PWD/deny-helper" \
      mcp-fs --stdio --ask helper --name project /srv/project

Run the server through your usual MCP client. The helper is invoked only
when a permission check needs a decision; existing allow and deny rules
still apply. The new helper denies those unresolved requests without
displaying a dialog.

Why does it read stdin if it doesn't care about the request? The caller
sends a complete JSON object, then closes its input side of the connection.
The helper must consume all input through EOF before exiting. An early
exit can cause the caller's write to fail. The helper's stdout is reserved
for its answer; send diagnostic messages to stderr.

The helper equivalent to an unconditional allow-once is:

   #!/bin/sh
   cat >/dev/null

Use this only when every otherwise-unresolved permission request in that
server's policy is supposed to be approved. It approves the requested
sandbox grants as well as the operation, including broad privileges
when requested. It does not just suppress an annoying dialog.

B<Migration warning:> before the semantic helper protocol, empty output
with exit status zero was an error. It now means approval. Inspect existing
custom helpers, wrappers and dismissal paths before upgrading. In
particular, do not let a failed check or a closed dialog accidentally
return empty output with exit status zero.

=head2 Inspect a real request

To see what a server asks for, temporarily use this helper in a trusted
test setup:

   #!/bin/sh
   cat >&2 || exit 2
   exit 1

It sends the request to the server's diagnostic output, then refuses it.
Depending on the server's logging arrangement, stderr might end up in a
log file. Permission requests can contain paths, commands, source code,
mail-related information and other private data; do not leave such a
diagnostic helper enabled indiscriminately.

Here is a complete example request from a small illustrative file server
called C<example-files>. It has two sandbox grants, with
C<workdir-write> implying C<workdir-read>. Unlike real C<mcp-fs>, it
offers only these two grants. It asks to read a file in a known project:

   {
      "version": 1,
      "program": "example-files",
      "name": "project",
      "tool": "read-file",
      "action": "read",
      "action_description": "Read file contents",
      "reason": "Inspect the project README",
      "sandbox_implementation": "bubblewrap",
      "sandbox_grants": ["workdir-read"],
      "sandbox_grant_closure": ["workdir-read"],
      "sandbox_grant_choices": ["workdir-read", "workdir-write"],
      "sandbox_grant_descriptions": {
         "workdir-read": "Read files in the selected workdir",
         "workdir-write": "Modify files in the selected workdir"
      },
      "selected_workdir": "/srv/project",
      "paths": ["/srv/project/README"],
      "dimension_order": ["workdir", "subject"],
      "dimensions": {
         "workdir": {
            "label": "Workdir",
            "value": "/srv/project",
            "choices": [
               {"id": "exact", "label": "This workdir"},
               {"id": "any", "label": "All workdirs"}
            ],
            "default": "exact",
            "custom_regex": true
         },
         "subject": {
            "label": "File",
            "value": "/srv/project/README",
            "choices": [
               {"id": "exact", "label": "This file"},
               {"id": "directory", "label": "Files in this directory"}
            ],
            "default": "exact"
         }
      },
      "decisions": ["allow-once", "deny-once", "allow-always", "deny-always"],
      "lifetimes": [
         {"value": "indefinite", "label": "Indefinite"},
         {"value": "900", "label": "15 minutes"},
         {"value": "3600", "label": "1 hour"},
         {"value": "57600", "label": "16 hours"}
      ],
      "lifetime_default": "indefinite"
   }

The actual input is a single JSON line followed by EOF. Pretty-printing
here is just for readability. Save this example as F<offer.json> if you
want to experiment with the following programs without a running server.

A choice's C<id> is what you return to the engine, and its C<label> is
what you show to the user. Neither is the current value of the dimension.
For example, C<exact> in the workdir dimension means this particular
workdir, even when the next request names a different one.

Notice also that C<paths> lists affected filenames independently of
the dimensions. Another server might not offer a subject dimension at
all. A generic helper must not assume that workdirs, filenames, hosts,
or even sandbox grants are meaningful to every server.

=head2 Make a decision automatically

Here is a small Perl helper using the core JSON::PP module. It approves
the example server's read operations in one configured workdir when its
effective requested grants are exactly C<workdir-read>. Everything else
is refused.

   #!/opt/perl/bin/perl
   use strict;
   use JSON::PP ();

   binmode STDIN, ":raw";
   binmode STDOUT, ":raw";

   my $request = JSON::PP::decode_json (do { local $/; <STDIN> });

   $request->{version} == 1 or exit 2;

   if (($request->{program} // "") eq "example-files"
       && ($request->{name} // "") eq "project"
       && ($request->{sandbox_implementation} // "") eq "bubblewrap"
       && $request->{action} eq "read"
       && ($request->{dimensions}{workdir}{value} // "") eq "/srv/project"
       && @{$request->{sandbox_grant_closure}} == 1
       && $request->{sandbox_grant_closure}[0] eq "workdir-read") {
      print JSON::PP::encode_json { decision => "allow-once" }, "\n";
      exit 0;
   }

   print JSON::PP::encode_json {
      decision => "deny-once",
      message  => "Outside the configured read policy.",
   }, "\n";

Adjust the Perl interpreter pathname for your installation. With the
example offer, the helper prints:

   {"decision":"allow-once"}

If the engine instead requests C<workdir-write>, this policy refuses
the operation, even though the grant also implies C<workdir-read>.
The implication closure, rather than a search for the name C<read> in
a description, makes this distinction easy.

This example assumes that you control the server and trust it to describe
and enforce its own operation semantics. The strings C<program>, C<name>
and C<sandbox_implementation> are not authentication credentials. Do not
reuse this policy for an arbitrary remote server just because it claims
to be the example application.

=head2 Delegate requests you don't recognize

Usually you don't want to refuse every operation that your automatic
policy does not understand. Delegate the rest to the standard interactive
helper. Since the original request has already been read, pass it to a new
helper process, for example:

   #!/opt/perl/bin/perl
   use strict;
   use JSON::PP ();

   binmode STDIN, ":raw";
   binmode STDOUT, ":raw";

   my $input = do { local $/; <STDIN> };
   my $request = JSON::PP::decode_json $input;
   $request->{version} == 1 or exit 2;

   # insert your application-specific policy here
   if (($request->{program} // "") eq "example-files"
       && ($request->{name} // "") eq "project"
       && ($request->{sandbox_implementation} // "") eq "bubblewrap"
       && $request->{action} eq "read"
       && ($request->{dimensions}{workdir}{value} // "") eq "/srv/project"
       && @{$request->{sandbox_grant_closure}} == 1
       && $request->{sandbox_grant_closure}[0] eq "workdir-read") {
      print '{"decision":"allow-once"}', "\n";
      exit 0;
   }

   open my $helper, "|-", "anyevent-mcp-askpermission"
      or die "Cannot start permission helper: $!\n";
   binmode $helper, ":raw";
   print {$helper} $input or die "Cannot write permission request: $!\n";
   close $helper and exit 0;
   exit 2;

The delegated helper inherits stdout and stderr. It returns its explicit
JSON answer directly to the original caller. This example delegates to
the bundled helper, which normally returns explicit JSON and exits zero,
including on refusal. For a different helper using the exit-status
shorthand, propagate a deliberate normal exit 1 as well; do not confuse
a signal or arbitrary failure with an approval.

You can also use the asynchronous helper runner in
L<AnyEvent::MCP::Permissions::Ask>. That is useful if your program has
its own event loop or must manage the lifetime of a delegated process.
In a production wrapper, arrange for cancellation to reach any
subprocesses you start. The caller can terminate the wrapper without
necessarily terminating its descendants.

=head2 Return a persistent choice

For the example offer, this answer creates an allowance covering files
in the same directory, on the selected workdir, for one hour:

   {
      "decision": "allow-always",
      "scopes": {
         "workdir": "exact",
         "subject": "directory"
      },
      "sandbox_grants": ["workdir-read"],
      "lifetime": "3600"
   }

The engine constructs the rule and computes the expiry. There is no
absolute timestamp, matcher or rule-file pathname in the answer.

You can select a different set of grants for future invocations:

   {
      "decision": "allow-always",
      "scopes": {"workdir": "exact", "subject": "exact"},
      "sandbox_grants": ["workdir-write"],
      "lifetime": "900"
   }

In this example, the current invocation still receives only
C<workdir-read>. The saved rule permits future requests needing
C<workdir-write> (and its implied read authority), provided their action
and other scopes match. It does not authorize a different action, such
as writing a file when the server calls that action C<write>.

A persistent denial can carry a message and select an affected file:

   {
      "decision": "deny-always",
      "scopes": {"workdir": "exact", "subject": "directory"},
      "path": "/srv/project/README",
      "message": "Read the maintained documentation instead.",
      "lifetime": "3600"
   }

Here a future request must match the selected workdir and subject
scope and include that exact path to match this denial. To deny across
all paths within the selected dimensions, use C<"path": null>.

For a generic helper, a perfectly reasonable rule editor just displays
one choice per dimension and uses the offered defaults as initial
selections. To produce the persistent answer, copy the selected IDs,
the selected grant names and the selected lifetime into the result.
Don't try to manufacture wider scopes from labels or values.

=head2 Use a generic form renderer

If your program already displays MCP forms, it doesn't have to implement
a permission rule editor. Create a permission helper wrapper:

   #!/bin/sh
   exec anyevent-mcp-askpermission --form

Set C<PERL_ANYEVENT_MCP_PERMISSION_HELPER> to that wrapper and
C<PERL_ANYEVENT_MCP_ELICITATION_HELPER> to your form renderer. These are
separate executables. The adapter receives a semantic permission offer,
creates a normal form, and invokes the renderer. If the answer selects
a persistent decision, the adapter invokes the renderer again with
the scope, lifetime and grant form. Back returns to the first form.
The adapter returns one final semantic answer to the caller.

The renderer sees an object such as this (a small ordinary form, not
a permission offer):

   {
      "mode": "form",
      "message": "Choose which grants to allow",
      "requestedSchema": {
         "type": "object",
         "required": ["decision"],
         "properties": {
            "decision": {
               "type": "string",
               "enum": ["back", "allow-always"],
               "default": "allow-always"
            },
            "sandbox_grants": {
               "type": "array",
               "items": {
                  "anyOf": [
                     {"const": "workdir-read", "title": "Read files"},
                     {"const": "workdir-write", "title": "Modify files"}
                  ]
               },
               "default": ["workdir-read"]
            }
         }
      }
   }

A form answer is ordinary MCP elicitation content, e.g.:

   {
      "action": "accept",
      "content": {
         "decision": "allow-always",
         "sandbox_grants": ["workdir-read"]
      }
   }

C<action> here describes the form interaction, not the permission
decision. An accepted form can contain a permission denial. Declining
or cancelling a permission form means deny once.

Unlike the permission helper, a form renderer must write a JSON
response even for cancellation or refusal. Empty successful output
is an error. See L<anyevent-mcp-form-elicitation> for the supported
form interface. The built-in renderer is available on Unix via YAD
or a terminal. Your own renderer can use other UI facilities without
linking against AnyEvent.

=head1 PROCESS PROTOCOL REFERENCE

=head2 Invocation and framing

A helper is started for one permission request. There is no initialization
handshake or ongoing session. It inherits the caller's environment and
runs under the caller's OS user, outside the tool's worker sandbox.

Stdin contains exactly one UTF-8 encoded JSON object, serialized on one
line, followed by LF and EOF. JSON escapes embedded newlines in strings.
Read through EOF even if you already have the answer. In particular,
bare C</bin/true> and C</bin/false> are not reliable helpers with the
current transport, because they can exit without consuming the input.

Write exactly one complete UTF-8 JSON object to stdout, optionally
followed or surrounded by JSON whitespace, then exit. Output need not
be on one line. Use a JSON encoder for strings and non-ASCII data.
Do not print prompts, banners, progress messages or diagnostics on
stdout. Do not use protocol stdin for interactive input; open a separate
terminal or graphical interface.

There is one final answer for the whole request. The helper can present
multiple screens or make multiple internal decisions, but cannot send
an intermediate answer or ask the engine to prepare another screen.
The form adapter described above is a local utility for doing so.

=head2 Exit status and output

The result is interpreted after the process has exited and stdout has
reached EOF:

=over

=item Normal exit 0, exactly zero stdout bytes

Equivalent to C<{"decision":"allow-once"}>.

=item Normal exit 1, exactly zero stdout bytes

Equivalent to C<{"decision":"deny-once"}>.

=item Normal exit 0, one valid JSON object on stdout

Interpret the object as a semantic permission answer, as specified below.
A syntactically valid object can still be rejected by the engine.

=item All other combinations

Helper failure. This includes whitespace-only output, JSON values other
than objects, multiple JSON values, exit 1 with output, other nonzero
exit statuses, and termination by signal. Use exit 2 or another status
above 1 for errors with no answer.

=back

A process-start or transport error, timeout, cancellation or output
size overflow is also a failure, regardless of exit status. No failure
grants permission. The default permission helper timeout is 300 seconds
and the default output limit is 1 MiB. Callers may configure other limits.
The caller can cancel a pending helper; close your UI and terminate any
subprocesses you own when interrupted. Do not return a successful empty
answer from an error or cancellation handler.

The timeout includes the complete helper interaction. In native MCP mode,
the server also has a continuation deadline; time spent in a broker's
queue or displaying a dialog counts against that deadline.

=head1 SEMANTIC REQUEST REFERENCE

All requests have the following common fields. JSON object member order
has no significance. Read the fields supplied by the engine rather than
reconstructing an offer from the server's name or current application
configuration. Ignore unfamiliar descriptive fields that your helper
does not need; do not automatically approve operations whose authority
you do not understand.

=over

=item version (integer)

Protocol version, currently C<1>. A helper that cannot interpret the
version should report a failure rather than guess.

=item action (string)

The server-defined class of authority being requested. E.g. C<read>,
C<exec>, or a completely different application-specific action. It is
not necessarily the MCP tool name. Persistent decisions are scoped to
this action; the helper cannot change it.

=item reason (string)

A nonblank human-readable explanation of the operation. It can be
multiline and can contain text supplied by an MCP caller. It is not
proof that the operation has the effects claimed in the explanation.

=item decisions (array of strings)

Available decision values. The current engine always offers
C<allow-once> and C<deny-once>. It also offers C<allow-always> and
C<deny-always> unless a dimension has no persistent scope choices.
Use the offered list; do not display or return unavailable decisions.

=item sandbox_grants (array of strings)

Grant names requested for this operation. An empty array is valid.
These are the names that would normally be approved by allow-once.
The server may have expanded the caller's requested grants to describe
actual effective worker privileges.

=item sandbox_grant_closure (array of strings)

The requested grants including all transitively implied grant names,
sorted by name. For example, if C<write> implies C<read>, requesting
C<write> can produce C<["read","write"]> here. This field is useful
for automatic policies checking what authority an operation needs.
It is not a list of additional grants the helper must explicitly
return. The engine computes grant implications; the offer does not
include the complete implication graph for arbitrary selections.

=item sandbox_grant_choices (array of strings)

All available grant names, sorted by name. A helper can select a subset
of this list for an allowance, including the empty set. This is not
limited to the grants requested by the current operation.

=item sandbox_grant_descriptions (object)

Maps grant names to explanatory text. It can be empty, and individual
names need not have descriptions. The server may customize the text for
a particular workdir. Display grant names as well as their descriptions.
Descriptions are not an authorization language.

=item dimensions (object)

Maps dimension names to objects describing independent scope axes.
An empty object means there are no dimension constraints to choose.
See L</Dimension objects> below.

=item lifetimes (array of objects)

Available persistent rule lifetimes, in presentation order. Each object
has C<value> (a string identifying the lifetime) and C<label> (display
text). Currently the values are C<indefinite>, C<900>, C<3600> and
C<57600>. Numeric-looking values are strings representing seconds.
Select an offered value, not an absolute timestamp or a new duration.

=item lifetime_default (string)

The proposed initial lifetime selection. The engine uses this value
if a persistent answer omits the lifetime. The default is normally
C<indefinite>, but may reflect remembered user preferences.

=back

=head2 Additional request metadata

These fields enrich the request without introducing new saved-rule
dimensions. Not every server supplies them; some of the string-valued
fields can be JSON null. Treat missing and null optional context as
unavailable, not as a wildcard identity.

=over

=item name (string or null)

The permission profile's name, often also the configured server
instance name. This is not necessarily the program name.

=item program (string or null)

Application/program name, e.g. C<mcp-fs>. Useful for selecting an
application-specific helper or presenting a heading. Simple servers
normally derive this from their executable name unless configured
otherwise.

=item multibroker_alias (string, optional)

The alias under which a child is known to a multibroker, when supplied
by the server's environment. Not a substitute for authenticated
server identity.

=item tool (string or null)

The dispatched MCP tool name when known, otherwise the application's
supplied tool context. It can differ from C<action>. The permission
rule is not selected by changing this field.

=item action_description (string or null)

A server-provided human-readable description of the action.

=item sandbox_implementation (string or null)

Description of the worker enforcement mechanism, e.g. C<bubblewrap>
or C<NONE - UNSANDBOXED (full host-user privileges)>. Do not infer
that a worker is isolated merely because a grant list is present.

=item selected_workdir (string, optional)

The logical workdir identity selected for the operation, currently
supplied by mcp-fs. It can be present even when no workdir permission
dimension is needed, for example when the requested privileges span
all workdirs. Do not confuse it with a resolved physical mount path.

=item dimension_order (array of strings, optional)

Preferred display order of dimension names. Names not included in
this list follow in alphabetical order. It has no effect on matching.

=item paths (array of strings, optional)

Affected filenames. They can be shown as context and selected for
an exact-file persistent denial. They do not offer a path-based
allowance or constrain sandbox access. See L</Answer fields> for
the exact denial semantics.

=item details (object, optional)

Maps plain display labels to Unicode text, e.g.
C<"View patch"> to the proposed patch or C<"View stdin"> to a
command's input. These details can be large and contain control
characters. Display them as text, not as markup, terminal commands
or executable content. If you truncate a preview, identify it as
incomplete. A producer may itself supply an explicitly marked
preview rather than the full underlying bytes.

The bundled UI limits each displayed detail to 65536 characters.
That is a display limit, not a limit on the semantic helper's input.
The details are not automatically saved as rule constraints.

=item context (object, optional)

Application-specific structured information about the actual operation.
A generic permission helper need not interpret it. An application-specific
helper should consult the documentation or code of the application
it supports. This is not a standardized set of tool arguments.

For example, mcp-fs exec currently supplies a context such as:

   {
      "argv": ["perl", "-Ilib", "-c", "lib/Foo.pm"],
      "stdin_bytes": 0,
      "stdin_encoding": "utf-8"
   }

C<argv> is the actual argument vector, not a shell command line.
C<stdin_bytes> counts the encoded input octets. C<stdin_encoding>
is C<utf-8>, C<latin1> or C<base64>. Nonempty UTF-8 stdin is supplied
as C<details> text; non-UTF-8 input uses an escaped byte preview
(currently limited to 4096 bytes). Do not mistake that preview for
the original input or assume that two equal argv vectors execute the
same program if their input differs.

In the same example, mcp-fs offers a C<subject> dimension whose
value is a JSON-encoded argv vector. Its choices have semantic IDs
C<command> (exact argv), C<prefix> (through the first separate
C<--> argument, if present), C<executable> (any arguments to the
same executable), and C<any-command>. The application defines these
scope semantics. Prefer C<context.argv> to parsing a displayed command
label, and return an offered scope ID rather than constructing an
argv regex.

=back

=head2 Dimension objects

Dimension names match C<[a-z][a-z0-9_-]*>. Names and their meanings are
chosen by the application. The engine can also add a C<user> dimension
for an authenticated user, with C<exact> and C<any> choices.

Each dimension has the following members:

=over

=item label (string)

Human-readable name of the dimension, e.g. C<Workdir> or C<Origin>.

=item value (nonempty string)

The current value, e.g. C</srv/project>. It is the identity against
which the saved matcher operates. It can be a structured value encoded
as a string, as with an exec argv vector.

=item choices (array of objects)

Ordered list of available persistent scopes. Every entry has:

   {"id": "exact", "label": "This workdir"}

C<id> is the exact selection value to return. It is unique within this
dimension. Application-defined stable IDs match C<[a-z][a-z0-9_-]*>.
If the application did not give a choice an ID, the engine supplies
C<#0>, C<#1>, etc., using the zero-based position in the offered list.
These anonymous IDs are only meaningful in the current offer.

Even a stable ID identifies a scope I<kind>, not the actual object
or matcher. Its meaning is defined by the application's action and
dimension, not by the generic protocol. Do not assume that IDs such
as C<exact> or C<any> exist for all dimensions.

An empty choice list prevents persistent decisions for the whole offer.
A single choice need not be explicitly selected in a persistent
answer. Multiple choices require an explicit selection.

=item default (string, present when choices exist)

ID of the proposed initial selection. It can come from the application's
default, a remembered stable choice, or the first choice. Use it to
preselect an option, not to infer that the user has already approved it.
The engine does not implicitly fill in an omitted multi-choice scope
from this value.

=item custom_regex (boolean true, optional)

A local helper may supply a custom Perl regular expression in place
of a choice ID. The engine only offers this when the dimension already
has a completely unrestricted matcher. It is absent from native MCP
offers, including permission-aware ones. Omission means custom regexes
are not available.

=back

=head1 SEMANTIC ANSWER REFERENCE

The answer is a JSON object with C<decision> and, when needed, further
selection fields. Return only the fields relevant to that decision.
Unknown top-level answer fields are rejected. Do not send back the
request, its matchers, a rule, or a fabricated offer.

=head2 Decisions

=over

=item allow-once

Approve the current permission request. If no grant selection is
supplied, approve all requested grants. You can explicitly approve a
smaller set.

   {"decision":"allow-once"}

   {"decision":"allow-once","sandbox_grants":["workdir-read"]}

=item deny-once

Refuse this permission request, optionally with a message. No rule is
saved.

   {"decision":"deny-once","message":"Use the dedicated read tool."}

=item allow-always

Approve an operation and save an allowance for future matching requests.
Select each multi-choice dimension and the future grant set. A rule can
expire; C<always> means persistent rather than necessarily indefinite.

   {
      "decision":"allow-always",
      "scopes":{"workdir":"exact","subject":"directory"},
      "sandbox_grants":["workdir-read"],
      "lifetime":"3600"
   }

=item deny-always

Refuse the operation and save a denial for future matching requests.
Select each multi-choice dimension and, if affected paths were offered,
the exact path or all-path scope. A message and lifetime are optional.

   {
      "decision":"deny-always",
      "scopes":{"workdir":"exact","subject":"directory"},
      "path":null,
      "message":"Not in this project."
   }

=back

Only return decision values present in the offer. There is no semantic
C<back>, C<cancel>, C<ask>, or C<allow> decision. Implement Back within
your UI; for an ordinary refused or dismissed permission prompt, return
C<deny-once>. A cancelled or failed process must not approve anything.

=head2 Answer fields

=over

=item decision (string, required)

One of the offered decisions described above.

=item sandbox_grants (array of strings, allowance only)

Selected names from C<sandbox_grant_choices>. Omission for allow-once
means the requested grants; an explicit empty array means no sandbox
grants. For allow-always an explicit array is required when any grants
are available, even when the selected array is empty. For a grant-free
server it can be omitted.

The engine takes grant implications into account. For the present
operation, it grants at most the intersection of the closure of the
requested grants and the closure of the selected grants. If all
requested authority is covered, it returns the original requested
names to the application. Otherwise it returns the names in the
intersection. The worker may refuse to proceed if an essential grant
was removed.

For allow-always, the rule stores the selected names for future
operations, not just the intersection. For example, selecting
C<write> for a current C<read> request cannot give the current worker
write authority, but can allow a future matching request for write
authority if C<write> implies C<read>.

Denial rules do not have a helper-selected grant set. The engine
uses the original requested grants. A denial without an exact path
normally matches future requests that include all the denied grants,
including implications. An exact-path denial instead checks the
affected paths and ignores the grant-set restriction.

=item scopes (object, persistent decisions only)

Map each dimension name to the selected offered ID. Omit a dimension
only if it offers exactly one choice. If there are no dimensions,
C<scopes> may be omitted or be an empty object. Do not include
unoffered dimension names.

For a dimension that advertises C<custom_regex>, a local semantic helper
may instead supply an object containing exactly one C<regex> member:

   {
      "decision": "allow-always",
      "scopes": {
         "workdir": {"regex": "^/srv/project(?:/|$)"},
         "subject": "exact"
      },
      "sandbox_grants": ["workdir-read"]
   }

The expression is a Perl regex string beginning with a literal C<^>.
It must compile and match the dimension's actual current value.
Executable Perl code in a regex is not supported. Use JSON escaping
for any regex backslashes. The engine only allows this escape hatch
when it already offers unrestricted scope for that dimension. The
expression cannot change the action or any other dimension.

A regex is not evaluated against the human-readable label or
C<context>. It operates on the dimension's C<value> string. It will
also be used for future rule matching, so keep it efficient and
understand what it will match. Use an ordinary offered scope whenever
possible. Native MCP clients cannot supply custom regexes, and the
bundled interactive helper/form adapter doesn't offer a regex editor.

=item lifetime (string, persistent decisions only)

One of the offered C<lifetimes> values. If omitted, the engine uses the
C<lifetime_default> from the offer that was presented, not a later
preference setting. Use the string C<"indefinite"> for no expiry.
The engine converts a finite duration into an absolute expiry when
it saves the rule. The helper does not calculate it.

=item path (string or null, deny-always only)

If C<paths> contains affected filenames, select one exact offered
nonempty filename, or JSON null for a denial not restricted by filename.
This selection is required when paths are offered; do not silently
omit it to broaden the denial. Without offered paths it can be
omitted.

A path-specific denial still uses all selected dimensions and the
original action. It matches if the future operation includes the exact
path, even when it also affects other paths or requests different grants.
There is no path-specific allowance in this interface.

=item message (string or null, denials only)

Optional explanation returned to the caller with the denial.
Maximum 2048 characters, without CR or LF. Whitespace-only messages
are treated as absent. On a persistent denial the explanation is saved
with the rule. Do not put secrets in it or assume that only the user
who saw the dialog will see it. Messages do not change the scope.

=back

The engine rechecks the original permission request and policy when
an answer arrives, under its rule-file lock where applicable. A policy
change can supersede the helper's decision. Otherwise the engine
validates the selections against the original offer, constructs any
rule, saves it and remembers applicable stable IDs and lifetime
preferences. A save failure is an error, not a successful permanent
approval. Concurrent preference changes alone do not invalidate an
otherwise matching offer.

=head1 CONFIGURATION AND INTEGRATION

=head2 Selecting your executable

Set the following environment variables on the process that will invoke
your helper:

=over

=item PERL_ANYEVENT_MCP_PERMISSION_HELPER

Path or name of a permission helper executable. The default is
C<anyevent-mcp-askpermission>. This variable is not a shell command;
it does not parse shell syntax, split arguments, or expand a tilde.
Use a wrapper executable for arguments, pipelines or other shell logic.

=item PERL_ANYEVENT_MCP_ELICITATION_HELPER

Path or name of an ordinary MCP form renderer, not a permission
helper. Used by the generic form adapter and local ordinary form
handling. Default C<anyevent-mcp-form-elicitation>. For forced
C<--tty> or C<--yad> mode the adapter uses the corresponding bundled
renderer instead.

=back

Select C<--ask helper> when testing a replacement executable. Otherwise
the configured asking mode may bypass it entirely, for example by
using native MCP elicitation or forcing a bundled UI. See
L<AnyEvent::MCP::Intro/Choose where to ask> for the asking modes and
their configuration.

A Perl server can select a helper executable and arguments directly
when constructing its permission engine:

   my $permissions = AnyEvent::MCP::Server::Permissions->new (
      name   => "example",
      ask    => "helper",
      helper => ["anyevent-mcp-askpermission", "--form"],
   );

The constructor also accepts a local asynchronous C<ask> callback
that receives the public semantic offer and returns a semantic
answer via its completion callback. See the engine's Perl API.
Do not pass its private prepared request to an external helper.

=head2 Multibrokers

The multibroker can collect permission decisions for downstream servers.
For example, configure the helper on the multibroker machine:

   PERL_ANYEVENT_MCP_PERMISSION_HELPER=/absolute/path/to/my-helper \
      mcp-multibroker --stdio --ask helper \
         files 'stdio:mcp-fs --name project /srv/project'

Spawned stdio children normally delegate permission prompts to the
multibroker. Independently started HTTP children must be configured
to delegate them as well. See L<mcp-multibroker> for the delegation
and asking modes.

In local helper mode, the multibroker recognizes permission offers
using the native extension below and invokes the semantic permission
helper on the multibroker machine. Ordinary MCP elicitation requests
go to the ordinary form renderer instead, including forms from a child
that does not implement the extension. The multibroker serializes
its local prompts. No special broker protocol is needed in your
helper executable.

=head2 Native MCP integration

You only need this section if you are implementing an MCP client or
broker, not if you are implementing an executable permission helper.

The modern MCP input-required/retry mechanism (as in MCP 2026-07-28)
can carry ordinary C<elicitation/create> form requests inside
C<inputRequests>. An ordinary form-capable client needs no
AnyEvent::MCP-specific extension to present permission forms.
The server first asks for a decision and, if a persistent decision
was selected, asks for the rule settings in another form. Back
returns to the first form. The server keeps the intermediate state.
The permission helper itself never receives these intermediate forms.

A client which understands semantic permission offers can avoid the
second network round trip. Advertise both form elicitation and the
following extension in the request's
C<_meta["io.modelcontextprotocol/clientCapabilities"]>:

   {
      "elicitation": {"form": {}},
      "extensions": {
         "de.schmorp.anyevent-mcp/permission": {"version": 1}
      }
   }

Only advertise the extension if you can actually handle the complete
form and associated offer. It is an application extension, not part
of MCP's standard elicitation schema. It does not grant new authority
or change which operations require permission.

For an unresolved permission check, the server now returns
C<resultType: "input_required">, an opaque C<requestState>, and an
ordinary, complete C<elicitation/create> form under
C<inputRequests.permission>. The enclosing result's C<_meta> contains
a map under C<de.schmorp.anyevent-mcp/permission>, keyed by the
corresponding input request ID. The value is the semantic offer
described above, without C<custom_regex>.

Structurally, the result is:

   resultType:    "input_required"
   requestState:  OPAQUE STATE
   inputRequests:
      permission:
         method:  "elicitation/create"
         params:  COMPLETE MCP FORM PARAMETERS
   _meta:
      de.schmorp.anyevent-mcp/permission:
         permission: SEMANTIC OFFER

The above is a schematic representation, not literal JSON.
The offer is in the outer result metadata, not inside elicitation
parameters and not in the response's metadata. This allows the form
itself and its response to remain ordinary flat MCP data.

Invoke your permission helper with the semantic offer once. Turn
its final answer into C<{"action":"accept","content":{...}}> using the
following mapping:

=over

=item decision, message, sandbox_grants, lifetime

Use the corresponding semantic answer fields unchanged where relevant
and offered by the schema. Grants are an array of strings, not a
comma-separated string. If no grant choices exist, the schema omits
that field; omit it from the form answer too.

=item scopes

Flatten each selected C<scopes.NAME> ID into a string-valued
C<dim_NAME> form field. Do not include the nested scopes object.
The complete form includes singleton dimensions as optional fields,
so they can still be omitted. Custom regex objects are not allowed.

=item path

Use the selected exact path string, or the empty string for all paths.
JSON null is the semantic representation of all paths, not the form
representation.

=back

The complete form contains the relevant decision, message and grant
fields and, when persistence is offered, fields for scopes, lifetime
and any denial path. Since ordinary MCP form schemas are flat, these
additional fields are optional in the schema. The engine requires the
appropriate selections according to the chosen decision. A client
must not simply omit a multi-choice scope or an offered denial path
and expect the server to assume a default.

For example, the persistent allowance from the tutorial, after
flattening, becomes this ordinary input response:

   {
      "action": "accept",
      "content": {
         "decision": "allow-always",
         "dim_workdir": "exact",
         "dim_subject": "directory",
         "sandbox_grants": ["workdir-read"],
         "lifetime": "3600"
      }
   }

An explicit semantic denial can likewise be returned using
C<action: "accept"> with C<decision: "deny-once"> or C<deny-always>
in the content. C<action: "decline"> and C<action: "cancel"> both
mean deny once, and cannot carry persistent scope choices.
The empty-output shorthand is interpreted by the local helper runner,
not sent as empty MCP input.

Retry the original MCP method and arguments with the returned
C<requestState> and the form response under
C<inputResponses.permission>. For example, for the tutorial's
fictional read-file tool:

   {
      "name": "read-file",
      "arguments": {"path": "/srv/project/README"},
      "requestState": "STATE-RETURNED-BY-SERVER",
      "inputResponses": {
         "permission": {
            "action": "accept",
            "content": {"decision": "allow-once"}
         }
      }
   }

The state string above is a placeholder; copy the actual opaque
state verbatim. Keep the original authenticated user, method and
arguments. Each state is single-use and expires. A subsequent
input-required result can request a different permission check in
the same tool invocation; handle that new offer separately.
A complete form is one round for one permission check, not a guarantee
that the tool will never ask again.

With the Perl client implementation, C<on_request> receives a
L<AnyEvent::MCP::Client::Request> object containing the outer
metadata in C<input_result_meta>. Use
C<AnyEvent::MCP::Permissions::Ask::permission_offer> to identify
a permission offer and the C<elicitation> method to invoke the helper,
flatten the answer and reply:

   use AnyEvent::MCP::Permissions::Ask ();

   # options for AnyEvent::MCP::Client::HTTP or ::JSONL
   my %options = (
      client_capabilities => {
         elicitation => { form => {} },
         extensions  => {
            "de.schmorp.anyevent-mcp/permission" => { version => 1 },
         },
      },
      on_request => sub {
         my ($client, $req) = @_;

         if (AnyEvent::MCP::Permissions::Ask::permission_offer $req) {
            AnyEvent::MCP::Permissions::Ask->elicitation ($req);
         } elsif ($req->{method} eq "elicitation/create") {
            $req->reply ({ action => "decline" });
         } else {
            $req->error (-32601, "Unsupported input request");
         }
      },
   );

This example deliberately declines unrelated forms. In a general client,
route those forms to your own renderer instead. The Perl client manages
the continuation and cancellation for C<call>; raw C<rpc> returns
input-required results intact. See L<AnyEvent::MCP::Client>.

=head1 TRUST AND IMPLEMENTATION NOTES

The engine decides what authority can be selected, not whether selecting
it is a good idea. A configured helper is trusted to make that latter
decision. It can authorize every offered operation, including one with
broad sandbox grants, without user interaction. It also executes with
the caller's operating-system privileges. Install and configure helper
executables with the same care as other trusted server-side code.

A native MCP client selected to make permission decisions is likewise
trusted, including the original user assertions accepted by the
permission engine in that mode. A remote server's program name, profile,
labels and context do not establish its identity; use a trusted connection
and routing configuration for application-specific policies.

The helper does not execute the authorized operation. It does not
construct the sandbox. The server checks and enforces the returned
authority when it performs the operation. Returning an allowance is
not a guarantee that the operation will succeed, especially if grants
were reduced or the policy changed during prompting.

For a persistent decision, all selected dimensions constrain the
rule. Information that is merely displayed or supplied in C<context>
does not automatically constrain later operations. For example, a rule
covering the exact command C<perl -> in mcp-fs can cover a future
invocation with different stdin. If your approval depends on information
not covered by an offered scope, prefer a one-time decision.

=head1 SEE ALSO

L<anyevent-mcp-askpermission>, L<anyevent-mcp-form-elicitation>,
L<AnyEvent::MCP::Permissions::Ask>, L<AnyEvent::MCP::Helper>,
L<AnyEvent::MCP::Server::Permissions>, L<AnyEvent::MCP::Server::Simple>,
L<AnyEvent::MCP::Client>, L<mcp-multibroker>, L<AnyEvent::MCP::Intro>.

=cut


Powered by Groonga
Maintained by Kenichi Ishigaki <ishigaki@cpan.org>. If you find anything, submit it on GitHub.