AnyEvent-MCP

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

	  MIME decoding, HTML link preservation and grouped IMAP FETCH calls.
	- allow mcp-imap messages to fetch selected UIDs without SEARCH.
	- actually truncate bounded IMAP part/raw responses to max_bytes,
	  not just flag them as truncated.
	- use a 15-second HTTP read-inactivity timeout by default, suspended
	  while processing complete requests; respect explicit handle rtimeout.
	- load MIME::Base64 in the HTTP server itself for encoded modern
	  Mcp-Name headers, without depending on the HTTP client loading it.
	- log ordinary HTTP 404 responses at trace rather than warn,
	  including GET /; keep other HTTP rejection warnings.
	- return 404 to GET / even when / is the MCP POST endpoint; drop
	  the unhelpful connection object address from HTTP rejection logs
	  while retaining the remote address and sanitized URI.
	- reuse the latest saved per-dimension scope as the next permission
	  rule editor's default where offered, otherwise keep the original
	  conservative choice; native, YAD and terminal forms agree.
	- handle the common token-only HTTP endpoint in warning logs:
	  redact known tokens without misclassifying unrelated paths.
	- include bounded, JSON-escaped request paths in rejected HTTP request
	  warnings; omit queries and redact configured and attempted URL tokens.
	- show captured helper status, stderr and stdout when the permission
	  UI test fails, and report remote file-patch results and file content
	  when the mock remote filesystem test fails (CPAN Testers diagnostics).

0.82  Fri 06 Nov 2026 15:53:46 CET
	- add a first-permission-dialog walkthrough to Intro.pod, explaining
	  one-time versus persistent grants, rule scopes and exec stdin risks;

Changes  view on Meta::CPAN

        - fix many bugs in the testsuite.

0.62  Thu 22 Oct 2026 13:32:52 CEST
	- INCOMPATIBLE API CHANGE: mcp_getoptions now returns a hash reference instead of
          a key/value list.
	- Simple accepts server_name/server_version independently of the local
	  instance name, leaving server_info as an unmodified protocol override.
	- query multibroker children in parallel for tool and broker discovery,
	  preserving tool order and returning partial results after 15 seconds
	  instead of blocking on an unresponsive child.
	- accept a missing trailing slash on HTTP MCP endpoint URLs, working
	  around Claude's MCP connector wrongly dropping it from the configured URL,
	  thus corrupting it.
	- allow omitted ports in reverse extension URLs, defaulting to port 80.
	- fix MCP client/server version fields serialized as JSON numbers in 0.61.

0.61  Thu 22 Oct 2026 08:57:42 CEST
	- resolve bind hostnames via AnyEvent::Socket instead of Socket::getaddrinfo.
	- honor user-selected file permissions and preserve them across replacements.
	- fix permission test fixture grants.
	- fix activity log timestamp formatting on older perl versions.

README  view on Meta::CPAN

       mcp-fs --name code --bind :31741 /home/alice/src/project

    In another terminal, obtain the matching connection URL:

       mcp-fs --name code --bind :31741 --print-url

    The second command prints a credential-bearing URL and exits without
    opening a listener. Configure that URL in the client. The default
    address is IPv4 loopback, so this example is reachable from the same
    machine only. A hosted client needs a suitable tunnel or reachable
    endpoint; its own "localhost" is not your computer.

    Repeat the same name and listener overrides when printing the URL. Both
    commands must use the same user and configuration directory. Port zero
    chooses an ephemeral port, which "--print-url" cannot predict; use an
    explicit port for this walkthrough.

    The HTTP server generates and saves its private master secret when
    needed. You can initialize it explicitly with "anyevent-mcp init", but
    that command is unnecessary when configuration already exists and will
    refuse to replace it. Keep the printed URL private: possession of its

README  view on Meta::CPAN


    Standalone "mcp-ask-user" also supports these modes and defaults to the
    local helper. A question is different from an approval: answering it
    does not grant a filesystem worker any authority.

COMBINING SERVERS
    Once the first connection works, "mcp-multibroker" lets you give the
    client one connection for several MCP servers. It works with the servers
    in this distribution and with third-party MCP servers, including ones
    written in other languages. Each downstream server can be a local
    subprocess communicating over stdio or an existing HTTP endpoint; you
    can mix both in one broker. The broker discovers their tools and
    forwards calls to the appropriate server without changing how that
    server implements its tools.

    For example, combine two filesystem instances:

       mcp-multibroker --name tools --bind :31740 \
          code 'stdio:mcp-fs --name code /home/alice/src/project' \
          notes 'stdio:mcp-fs --name notes /home/alice/notes'

README  view on Meta::CPAN

    The hello is a raw JSON line, followed by ordinary MCP JSONL on the same
    socket; the HTTP-shaped URL is an address and credential, not an HTTP
    request. "https://" reverse URLs enable verified TLS; "http://" uses
    plaintext. A certificate mismatch is an error, not a reason to fall back
    to HTTP. With "--tls-cert" and "--tls-key" on the listener,
    "--print-url" gives HTTPS and HTTP URL prefixes. For HTTPS, use a
    trusted certificate whose hostname matches the URL. An HTTP listener is
    already active by default when upstream is HTTP.

  Add an HTTP child
    A broker can mix spawned stdio servers and existing HTTP endpoints,
    including independently implemented third-party servers:

       mcp-multibroker --stdio \
          code 'stdio:mcp-fs --name code /home/alice/src/project' \
          remote https://example.org/mcp/ --bearer TOKEN

    "--bearer" immediately after the HTTP pair belongs to that child.
    "--token" before all pairs configures the multibroker's own HTTP
    listener. They authenticate different connections.

    To avoid putting a child's bearer token in the startup command, add:

       [client remote]
       bearer = TOKEN
       timeout = 300

    to the private global configuration, and omit "--bearer" from the
    command. The prefix "remote" selects these client defaults. The
    command-line URL still chooses the endpoint. Use the actual credential
    accepted by that server, not the literal placeholder "TOKEN".

    A token already present in a child's URL needs no separate bearer
    option. The bundled servers use static URL-safe tokens; they do not
    validate OAuth access tokens or implement HTTP Basic authentication. Use
    TLS or an appropriate tunnel when credentials cross untrusted networks.

    The multibroker does not put every child inside the mcp-fs sandbox. Each
    process or remote service has its own authority and enforcement.

README  view on Meta::CPAN

    permission prompts, cancellation and execution timeouts. See "USERSCRIPT
    INSTALLATION AND USE" in mcp-webbrowser for setup, compatibility and the
    current ScriptCat discarded-tab limitation.

    If the multibroker launches the browser broker, keep that child running
    from startup so browser tabs can connect:

       mcp-multibroker --stdio browser --- mcp-webbrowser --- --eager

HTTP TOKENS AND SERVER IDENTITY
    For the ordinary bundled HTTP endpoints, a client can present an
    accepted token in either of these ways:

       POST /TOKEN/
       POST /                 Authorization: Bearer TOKEN

    URL tokens are path components, not browser cookies. For another
    configured endpoint, "/TOKEN" prefixes that endpoint path. The HTTP
    server also accepts "/TOKEN" and the corresponding bare path without the
    final slash when the endpoint is configured with one. This works around
    clients (observed with Claude) that drop the final slash from a
    configured URL. Managed tokens authenticate distinct users for saved
    permissions. Existing rules without match.user still apply to every
    user.

    To add a user and obtain their multibroker URL:

       anyevent-mcp create-user chatgpt
       mcp-multibroker --print-url=chatgpt

README  view on Meta::CPAN


    For reverse "--connect" servers, check the connecting process's log as
    well as the multibroker. "https://" requires a certificate trusted by
    the connecting process and a hostname matching the URL. A TLS error
    stops that reverse server immediately; it does not retry with plaintext.
    TCP connection refusal is retried for up to sixty attempts.

  Authentication fails
    Obtain the URL with the same name, bind/token overrides and
    configuration environment as the running process. Use the complete path;
    the final slash is optional for endpoints whose configured path ends in
    one. A clean URL needs an accepted bearer token.

    A multibroker child credential is not necessarily the upstream
    listener's credential. "--bearer" after a child pair and "--token"
    before the pairs configure different sides of the connection.

    For IMAP OAuth2, obtaining an access token does not by itself prove that
    IMAP authentication will work. Check the authorized browser account,
    requested IMAP scope and saved "user" name. Copy the complete redirected
    address-bar URL after authorization, even when the browser displays an

bin/mcp-imap  view on Meta::CPAN

=back

=head2 OAuth2 keys (C<method oauth2>)

=over

=item C<oauth-client-id ID>

OAuth client ID registered with the provider (required).

=item C<oauth-authorization-endpoint URL>

Provider authorization endpoint, HTTPS (required).

=item C<oauth-token-endpoint URL>

Provider token endpoint, HTTPS (required).

=item C<oauth-scope TEXT>

Space-separated OAuth scopes (required).

=item C<oauth-redirect-uri URI>

Registered callback URI, HTTPS or HTTP loopback without query or fragment
(required). The program does not listen on this URI; copy the full URL
from the browser address bar after authorization.

=item C<oauth-client-secret SECRET>

Optional client secret for confidential OAuth clients. Supplied as a login
setting, not as an IMAP password.

=item C<oauth-client-auth none|client_secret_post|client_secret_basic>

OAuth token-endpoint authentication. Default C<none> without a client
secret, otherwise C<client_secret_post>. Non-C<none> modes require
C<oauth-client-secret>.

=item C<oauth-pkce 0|1>

Use PKCE S256, enabled by default (C<1>). Disable (C<0>) only if the
provider registration does not support PKCE.

=item C<oauth-sasl xoauth2|oauthbearer>

bin/mcp-imap  view on Meta::CPAN


Replace the example address. This reports possible IMAP settings and
login commands; provider-specific OAuth client registrations may be
restricted to their original application. For a password-based provider,
for example:

   mcp-imap --name personal login method password \
      server imap.example.net user alice@example.net tls connect port 993

The password is read interactively. For OAuth2, run C<login method oauth2>
with your provider-approved client ID, authorization/token endpoints,
scope and redirect URI. For example, the structure of such a command
(the provider URLs and registration below are placeholders) is:

   mcp-imap --name personal login method oauth2 \
      server imap.example.net user alice@example.net tls connect port 993 \
      oauth-client-id REGISTERED_CLIENT_ID \
      oauth-authorization-endpoint https://login.example.net/authorize \
      oauth-token-endpoint https://login.example.net/token \
      oauth-scope MAIL_SCOPE \
      oauth-redirect-uri http://127.0.0.1:1

The redirect URI must be allowed by the OAuth client registration. Some
providers additionally require C<oauth-auth-access_type offline> or
other authorization parameters to issue a refresh token. After opening
the printed authorization URL, authorize the intended account and paste
the B<full> redirect URL from the browser's address bar even if the browser
reports an unreachable loopback page. Login checks IMAP authentication
before saving the account.

bin/mcp-imap  view on Meta::CPAN


         "Login keys (KEY VALUE, not --options):",
         ["method password|oauth2", "Authentication method (default password)"],
         ["server HOST", "IMAP hostname (prompts if missing)"],
         ["user USER", "IMAP username (prompts if missing)"],
         ["tls connect|starttls|none", "TLS from connection (default), STARTTLS upgrade, or explicitly no encryption"],
         ["port PORT", "Defaults: 993 for connect; 143 for starttls or none"],

         "OAuth2 login keys (method oauth2):",
         ["oauth-client-id ID", "Required OAuth client ID"],
         ["oauth-authorization-endpoint URL", "Required HTTPS authorization endpoint"],
         ["oauth-token-endpoint URL", "Required HTTPS token endpoint"],
         ["oauth-scope TEXT", "Required scope string"],
         ["oauth-redirect-uri URI", "Required registered HTTPS or loopback URI"],
         ["oauth-client-secret SECRET", "Optional OAuth client secret"],
         ["oauth-client-auth MODE", "none, client_secret_post, client_secret_basic"],
         ["oauth-pkce 0|1", "PKCE S256 (default 1)"],
         ["oauth-sasl MODE", "xoauth2 (default), oauthbearer"],
         ["oauth-auth-NAME VALUE", "Additional authorization parameter, e.g. access_type offline"],
      ],
      examples    => "  mcp-imap --name personal providers alice\@example.net\n"
         . "  mcp-imap --name personal login server imap.example.net user alice\@example.net tls connect\n"

bin/mcp-imap  view on Meta::CPAN

      %connection, method => "password",
      password => MIME::Base64::decode_base64 ($kv->{"password-base64"}),
   }
}

sub login {
   @ARGV % 2 == 0 or die "login expects key/value pairs\n";
   my %input;
   while (@ARGV) {
      my ($key, $value) = splice @ARGV, 0, 2;
      $key =~ /\A(?:method|server|user|tls|port|oauth-(?:client-id|client-secret|client-auth|authorization-endpoint|token-endpoint|scope|pkce|redirect-uri|sasl|auth-[A-Za-z0-9_]+))\z/
         or die "Unknown login key '$key' (passwords and tokens cannot be given on argv)\n";
      $value = AnyEvent::MCP::utf8dec $value;
      $value !~ /[\r\n\x00]/ or die "Invalid $key\n";
      $input{$key} = $value;
   }
   my $old = load_account ();
   my $method = $input{method} || $old->{method} || "password";
   $method =~ /\A(?:password|oauth2)\z/ or die "Unknown login method\n";

   my %kv = %$old;

bin/mcp-multibroker  view on Meta::CPAN

It uses the same accepted tokens as HTTP. Authentication grants registration
under any free alias; configured or connected aliases cannot be replaced.

The connecting program remains the MCP server. The multibroker attaches an
MCP client and discovers its tools immediately. Forms and cancellation follow
the same routes as other downstream connections. An unexpected disconnect
fails pending calls, removes the registration and starts a new connection
period. Refused TCP connections are retried every second, up to sixty times.
Other TCP setup failures and TLS verification failures log an error and stop;
there is no automatic downgrade to plaintext. No interrupted operation is
replayed. Plain HTTP endpoint URLs do not provide transport encryption;
use a trusted connection or tunnel as needed.

=head2 Process lifetime

Each downstream connection advertises C<anyevent-mcp/multibroker> version 1
in its client capabilities. A spawned stdio child can request managed idle
shutdown with C<anyevent-mcp/idle-exit>. When no calls are outstanding, the
broker may send C<anyevent-mcp/shutdown>; the child acknowledges before
exiting. This is optional and never makes HTTP children exit. Unexpected
disconnects are logged, not proactively restarted. A later use reconnects.

bin/mcp-multibroker  view on Meta::CPAN


AnyEvent::detect; # initialise child watchers before starting subprocesses.
$| = 1;

my $usage = "Usage: $0 [OPTION]... PREFIX (URL | --- PROGRAM ARG... ---) [CHILD-OPTION] ...\n";
Getopt::Long::Configure ("require_order");
my $server_options = mcp_getoptions
   {
      usage       => $usage,
      path        => "/",
      description => "Combine MCP servers behind one endpoint, with tools named PREFIX.TOOL.\n"
         . "Each server is HTTP(S), stdio:COMMAND, or --- PROGRAM ARG... ---; downstream options follow its entry.",
      options     => [
         "Broker-wide options:",
         ["--listen", "Keep the upstream HTTP listener active alongside stdio or --connect"],
         "Downstream options (after the URL or closing ---):",
         ["--eager", "Start the preceding stdio child at broker startup"],
         ["--required", "Require stdio child; implies --eager, exit on failure"],
         ["--bearer TOKEN", "Authenticate to the preceding HTTP child"],
         ["--hidden", "Hide child's tools from default discovery; explicit list-tools and calls still work"],
         ["--disable", "Exclude the preceding child entirely, keeping its prefix reserved"],

bin/mcp-sctl  view on Meta::CPAN

eight-character code in that extension's External Access settings. The code
expires after two minutes. Long-term keys are stored in a private JSON file
under C<$XDG_CONFIG_HOME/anyevent-mcp/> (or C<~/.config/anyevent-mcp/>).
A pairing code grants the extension access to the bridge; the MCP permissions
independently control what an AI client may call.

C<list> discovers connected instances and their advertised methods;
C<search> looks up methods and, when available, parameter/result schemas;
C<call> invokes a method with uninterpreted JSON input. Method permission
is independent of instance permission. CDP uses the same C<call> tool with
C<debugger.send>; there is no Playwright/CDP endpoint or high-level page
automation here.

Protocol metadata is advisory, not an authorization source. It is cached
under C<$XDG_CACHE_HOME/anyevent-mcp/> and refreshed over HTTPS as needed.
Only methods advertised by the live extension can be invoked, even if a
downloaded description lists more.

=head1 FIRST USE

With C<mcp-multibroker>, add an eager child:

bin/mcp-sctl  view on Meta::CPAN

authenticated instances, disconnects, tool requests and call outcomes.
Calls include abbreviated arguments and elapsed time; script listings,
source retrieval and searches report counts or ranges, never complete
source bodies. Pairing codes and authentication keys are not logged.
C<--quiet> suppresses operator activity logging; ordinary debug/trace
diagnostics use the configured AnyEvent::Log verbosity.

=head1 OPTIONS

Use the shared C<--bind> option for both the extension WebSocket and MCP HTTP
listener. C<--print-url> prints both the authenticated MCP endpoint and the
token-free extension WebSocket endpoint.
The shared switches are documented in
L<AnyEvent::MCP::Server::Simple/COMMON COMMAND-LINE OPTIONS>.

=cut

use common::sense;

use JSON::XS ();
use Time::HiRes qw(time);
use Digest::SHA qw(hmac_sha256 hmac_sha256_hex sha256_hex);

bin/mcp-vim  view on Meta::CPAN


   my $save = {
      xpcse   => $self,
      vim     => $vim,
      session => $session,
      hdrs    => $hdrs,
      force   => $force ? 1 : 0,
      data    => [],
   };

   # the queue and Vim input own the save; neither endpoint is kept alive by it.
   Scalar::Util::weaken ($save->{xpcse});
   Scalar::Util::weaken ($save->{vim});
   push @{$self->{saves}}, $save;
   $self->send_data;
   $save
}

sub xpcse::send_data {
   my ($self) = @_;

lib/AnyEvent/MCP/Client.pm  view on Meta::CPAN

An interrupted connection does not mean the server did nothing. A tool might
have completed its side effects just before the connection failed. For that
reason, the client never replays a tool call automatically. Applications that
want retries must decide whether the operation is safe to repeat.

Modern clients use discovery and per-request metadata. Legacy clients use
initialization and ordinary request/response. Legacy server-initiated requests
are accepted on JSONL; legacy HTTP GET streams are not implemented.

For a runnable call, see L<AnyEvent::MCP::Client::HTTP/FIRST CALL> when
connecting to an HTTP endpoint or
L<AnyEvent::MCP::Client::JSONL/FIRST CALL> when launching a subprocess.
Both use C<call> from this module. In its callback, C<$success> reports
JSON-RPC/transport success; a tool can still return C<isError> true.
Keep the client alive while its callbacks are pending.

=head1 METHODS

=over

=item $client = AnyEvent::MCP::Client->new (%config)

lib/AnyEvent/MCP/Client/HTTP.pm  view on Meta::CPAN

   use AnyEvent::MCP::Client::HTTP;

   my $client = AnyEvent::MCP::Client::HTTP->new (
      name => "example", url => $url, bearer => $token,
      timeout => 30,
   );

=head1 DESCRIPTION

Use this transport to talk to an MCP server through HTTP. The caller supplies
the endpoint and, if needed, credentials; the common Client layer handles
discovery and tool calls. Unlike a browser, this client does not follow
redirects or silently retry requests. A redirected request could disclose
credentials to another host, and retrying a tool call could perform an
operation twice.

=head1 FIRST CALL

For a bundled MCP server already listening on HTTP, use the full URL
it prints with C<--print-url>:

lib/AnyEvent/MCP/Client/HTTP.pm  view on Meta::CPAN


=item $client = AnyEvent::MCP::Client::HTTP->new (%config)

Accepts the common L<AnyEvent::MCP::Client> options and these transport
options. Options are flat, rather than nested in an HTTP configuration hash.

=over

=item url => $url

Complete endpoint URL, optionally including a URL-path token. Required
unless supplied by the named client configuration.

=item bearer => $token

Supplies C<Authorization: Bearer TOKEN>. Without it, the URL alone is
used; a bearer token is not inferred from a URL. The server must accept
the selected credential. With the bundled servers, the URL-path token
and bearer header present the same static credential.

=item name => $name

lib/AnyEvent/MCP/Client/HTTP.pm  view on Meta::CPAN


=back

C<proxy>, C<tls_ctx>, C<handle_params>, C<sessionid>, C<on_prepare>,
C<on_connect> and C<tcp_connect> are passed to L<AnyEvent::HTTP>.
No HTTP cookies or Basic authentication are supplied by this module.
Redirects and automatic HTTP retries are disabled.

Legacy session IDs are retained from initialization. An expired session fails
outstanding requests; a later operation can initialize again. Legacy GET
streams and the old separate SSE endpoint transport are not implemented.

=back

=cut

package AnyEvent::MCP::Client::HTTP;

use common::sense;
use parent "AnyEvent::MCP::Client";
use AnyEvent::HTTP ();

lib/AnyEvent/MCP/Extension.pm  view on Meta::CPAN

and accepted token. Authenticate before calling the protocol-specific handler.
Invalid hellos close the connection. The callback takes ownership of the same
handle, including buffered bytes after the hello. Remaining array fields belong
to the selected protocol. An optional C<$reject> callback releases any
listener ownership on rejection; otherwise the handle is destroyed.

=item ($host, $port, $token, $alias, $scheme) = AnyEvent::MCP::Extension::parse_url $url

Parse C<http[s]://host[:port]/token/alias>, including bracketed IPv6 hosts.
An omitted port defaults to 80 for HTTP and 443 for HTTPS. The URL names a
raw extension endpoint sharing an HTTP listener; no HTTP request is sent.
Tokens use the ordinary
listener token syntax and aliases use ASCII letters, digits, underscores and hyphens.

=back

=cut

package AnyEvent::MCP::Extension;

use common::sense;

lib/AnyEvent/MCP/IMAP/OAuth2.pm  view on Meta::CPAN

   my $s = MIME::Base64::encode_base64 ($bytes, "");
   $s =~ tr{+/}{-_};
   $s =~ s/=+\z//;
   $s
}

sub https {
   my ($url) = @_;
   defined $url && $url =~ m{\Ahttps://[A-Za-z0-9.-]+(?::[0-9]+)?(?:/|\?|\z)}i
      && $url !~ /[\s\x00-\x1f\x7f#@]/
      or die "OAuth endpoint must be an HTTPS URL with a hostname\n";
   $url
}

sub validate {
   my ($kv) = @_;
   for my $key (qw(oauth-client-id oauth-authorization-endpoint oauth-token-endpoint oauth-scope oauth-redirect-uri)) {
      defined $kv->{$key} && !ref $kv->{$key} && length $kv->{$key}
         or die "Missing $key for OAuth2 login\n";
   }
   https $kv->{"oauth-authorization-endpoint"};
   https $kv->{"oauth-token-endpoint"};
   $kv->{"oauth-redirect-uri"} =~ m{\A(?:https://[A-Za-z0-9.-]+(?::[0-9]+)?(?:/[^\s?#]*)?|http://(?:127\.0\.0\.1|localhost)(?::[0-9]+)?(?:/[^\s?#]*)?)\z}i
      or die "OAuth redirect URI must be HTTPS or HTTP loopback, without a query or fragment\n";
   for my $key (qw(oauth-client-id oauth-scope oauth-client-secret)) {
      next unless defined $kv->{$key};
      $kv->{$key} !~ /[\r\n\x00]/ or die "Invalid $key\n";
   }
   $kv->{"oauth-pkce"} //= 1;
   $kv->{"oauth-pkce"} =~ /\A[01]\z/ or die "oauth-pkce must be 0 or 1\n";
   $kv->{"oauth-client-auth"} //= defined $kv->{"oauth-client-secret"} ? "client_secret_post" : "none";
   $kv->{"oauth-client-auth"} =~ /\A(?:none|client_secret_post|client_secret_basic)\z/

lib/AnyEvent/MCP/IMAP/OAuth2.pm  view on Meta::CPAN

      state => $state,
      (defined $verifier ? (
         code_challenge => b64url (Digest::SHA::sha256 ($verifier)),
         code_challenge_method => "S256",
      ) : ()),
   );
   for my $key (grep /^oauth-auth-/, keys %$kv) {
      (my $param = $key) =~ s/^oauth-auth-//;
      $params{$param} = $kv->{$key};
   }
   my $url = $kv->{"oauth-authorization-endpoint"};
   $url .= ($url =~ /\?/ ? "&" : "?") . form (%params);
   ($url, $state, $verifier)
}

sub callback_code {
   my ($kv, $state, $url) = @_;
   my $base = $kv->{"oauth-redirect-uri"};
   my $query;
   if ($url =~ /^\Q$base\E\?([^#]*)\z/) {
      $query = $1;

lib/AnyEvent/MCP/IMAP/OAuth2.pm  view on Meta::CPAN

   if ($kv->{"oauth-client-auth"} eq "client_secret_basic") {
      $headers{Authorization} = "Basic " . MIME::Base64::encode_base64 (
         encode ($kv->{"oauth-client-id"}) . ":" . encode ($kv->{"oauth-client-secret"}), ""
      );
   }

   my $body = "";
   my $oversize;
   my $cv = AE::cv;
   my $guard = AnyEvent::HTTP::http_request
      POST => $kv->{"oauth-token-endpoint"},
      body => form (%data),
      headers => \%headers,
      recurse => 0, persistent => 0, proxy => undef, tls_ctx => "high", timeout => 30,
      on_body => sub {
         $oversize = 1, return 0 if length ($body) + length ($_[0]) > 65536;
         $body .= $_[0];
         1
      },
      sub { $cv->send ($_[1]) };
   my $hdr = $cv->recv;
   undef $guard;
   $oversize and die "OAuth token response too large\n";
   my $status = $hdr->{Status} || 0;
   $status >= 200 && $status < 300 or die "OAuth token endpoint returned HTTP $status\n";
   my $result = eval { JSON::XS::decode_json ($body) };
   ref $result eq "HASH" && defined $result->{access_token} && !ref $result->{access_token}
      && length $result->{access_token}
      or die "OAuth token endpoint returned no valid access token\n";
   !defined $result->{token_type} || lc $result->{token_type} eq "bearer"
      or die "OAuth token endpoint returned a non-Bearer token\n";
   if (exists $result->{refresh_token}) {
      defined $result->{refresh_token} && !ref $result->{refresh_token}
         && length $result->{refresh_token}
         or die "OAuth token endpoint returned invalid refresh token\n";
   }
   $result
}

sub finish {
   my ($kv, $state, $verifier, $url) = @_;
   my $code = callback_code ($kv, $state, $url);
   token ($kv,
      grant_type => "authorization_code",
      code => $code,

lib/AnyEvent/MCP/IMAP/OAuth2.pm  view on Meta::CPAN

sub refresh {
   my ($file, $kv) = @_;
   my $lock = AnyEvent::MCP::file_lock $file;
   my $sections = AnyEvent::MCP::Config::parse_ini (AnyEvent::MCP::file_load ($file), $file);
   for (@$sections) {
      $_->[0] eq "" || $_->[0] eq "account"
         or die "$file: invalid account section\n";
   }
   my %current = %{AnyEvent::MCP::Config::merge_sections ($sections, "account")->{account}};
   for my $key (qw(method server user tls port oauth-client-id oauth-client-secret
                   oauth-client-auth oauth-token-endpoint oauth-scope oauth-sasl)) {
      ($current{$key} // "") eq ($kv->{$key} // "")
         or die "IMAP OAuth account changed; restart mcp-imap\n";
   }
   my $encoded = $current{"oauth-refresh-token-base64"};
   defined $encoded && $encoded =~ /\A[A-Za-z0-9+\/]*={0,2}\z/
      or die "Missing OAuth refresh token; run mcp-imap login again\n";
   my $old = AnyEvent::MCP::utf8dec (MIME::Base64::decode_base64 $encoded);
   length $old or die "Empty OAuth refresh token\n";
   my $new = token ($kv, grant_type => "refresh_token", refresh_token => $old);
   if (defined $new->{refresh_token} && $new->{refresh_token} ne $old) {

lib/AnyEvent/MCP/IMAP/Providers.pm  view on Meta::CPAN


sub print_login {
   my ($name, $server, $method, $oauth) = @_;
   my @kv = (method => $method);
   for my $key (qw(server tls port user)) {
      push @kv, $key => $server->{$key} if defined $server->{$key};
   }
   if ($method eq "oauth2") {
      push @kv, "oauth-client-id" => $oauth->{clientId};
      push @kv, "oauth-client-secret" => $oauth->{clientSecret} if defined $oauth->{clientSecret};
      push @kv, "oauth-authorization-endpoint" => $oauth->{authorizationEndpoint};
      push @kv, "oauth-token-endpoint" => $oauth->{tokenEndpoint};
      push @kv, "oauth-scope" => $oauth->{scope};
      push @kv, "oauth-pkce" => $oauth->{usePKCE} && $oauth->{usePKCE} eq "true" ? 1 : 0;
      my $redirect = $oauth->{redirectionEndpoint} || "http://127.0.0.1";
      $redirect .= ":1" if $redirect =~ m{\Ahttp://(?:127\.0\.0\.1|localhost)\z};
      push @kv, "oauth-redirect-uri" => $redirect;
   }
   print "mcp-imap --name ", quote ($name), " login", @kv ? " \\\n" : "\n";
   while (@kv) {
      my ($key, $value) = splice @kv, 0, 2;
      print "  $key ", quote ($value), @kv ? " \\\n" : "\n";

lib/AnyEvent/MCP/Intro.pod  view on Meta::CPAN


   mcp-fs --name code --bind :31741 /home/alice/src/project

In another terminal, obtain the matching connection URL:

   mcp-fs --name code --bind :31741 --print-url

The second command prints a credential-bearing URL and exits without
opening a listener. Configure that URL in the client. The default address
is IPv4 loopback, so this example is reachable from the same machine only.
A hosted client needs a suitable tunnel or reachable endpoint; its own
C<localhost> is not your computer.

Repeat the same name and listener overrides when printing the URL.
Both commands must use the same user and configuration directory.
Port zero chooses an ephemeral port, which C<--print-url> cannot predict;
use an explicit port for this walkthrough.

The HTTP server generates and saves its private master secret when needed.
You can initialize it explicitly with C<anyevent-mcp init>, but that
command is unnecessary when configuration already exists and will refuse

lib/AnyEvent/MCP/Intro.pod  view on Meta::CPAN

Standalone C<mcp-ask-user> also supports these modes and defaults to the
local helper. A question is different from an approval: answering it does
not grant a filesystem worker any authority.

=head1 COMBINING SERVERS

Once the first connection works, C<mcp-multibroker> lets you give the
client one connection for several MCP servers. It works with the servers
in this distribution and with third-party MCP servers, including ones
written in other languages. Each downstream server can be a local
subprocess communicating over stdio or an existing HTTP endpoint; you
can mix both in one broker. The broker discovers their tools and
forwards calls to the appropriate server without changing how that
server implements its tools.

For example, combine two filesystem instances:

   mcp-multibroker --name tools --bind :31740 \
      code 'stdio:mcp-fs --name code /home/alice/src/project' \
      notes 'stdio:mcp-fs --name notes /home/alice/notes'

lib/AnyEvent/MCP/Intro.pod  view on Meta::CPAN

socket; the HTTP-shaped URL is an address and credential, not an HTTP request.
C<https://> reverse URLs enable verified TLS; C<http://> uses plaintext.
A certificate mismatch is an error, not a reason to fall back to HTTP.
With C<--tls-cert> and C<--tls-key> on the listener, C<--print-url> gives
HTTPS and HTTP URL prefixes. For HTTPS, use a trusted certificate whose
hostname matches the URL. An HTTP listener is already active by default
when upstream is HTTP.

=head2 Add an HTTP child

A broker can mix spawned stdio servers and existing HTTP endpoints,
including independently implemented third-party servers:

   mcp-multibroker --stdio \
      code 'stdio:mcp-fs --name code /home/alice/src/project' \
      remote https://example.org/mcp/ --bearer TOKEN

C<--bearer> immediately after the HTTP pair belongs to that child.
C<--token> before all pairs configures the multibroker's own HTTP listener.
They authenticate different connections.

To avoid putting a child's bearer token in the startup command, add:

   [client remote]
   bearer = TOKEN
   timeout = 300

to the private global configuration, and omit C<--bearer> from the command.
The prefix C<remote> selects these client defaults. The command-line URL
still chooses the endpoint. Use the actual credential accepted by that
server, not the literal placeholder C<TOKEN>.

A token already present in a child's URL needs no separate bearer option.
The bundled servers use static URL-safe tokens; they do not validate
OAuth access tokens or implement HTTP Basic authentication.
Use TLS or an appropriate tunnel when credentials cross untrusted networks.

The multibroker does not put every child inside the mcp-fs sandbox.
Each process or remote service has its own authority and enforcement.

lib/AnyEvent/MCP/Intro.pod  view on Meta::CPAN

L<mcp-webbrowser/USERSCRIPT INSTALLATION AND USE> for setup, compatibility
and the current ScriptCat discarded-tab limitation.

If the multibroker launches the browser broker, keep that child running
from startup so browser tabs can connect:

   mcp-multibroker --stdio browser --- mcp-webbrowser --- --eager

=head1 HTTP TOKENS AND SERVER IDENTITY

For the ordinary bundled HTTP endpoints, a client can present an accepted
token in either of these ways:

   POST /TOKEN/
   POST /                 Authorization: Bearer TOKEN

URL tokens are path components, not browser cookies.
For another configured endpoint, C</TOKEN> prefixes that endpoint path.
The HTTP server also accepts C</TOKEN> and the corresponding bare path
without the final slash when the endpoint is configured with one. This
works around clients (observed with Claude) that drop the final slash
from a configured URL.
Managed tokens authenticate distinct users for saved permissions. Existing
rules without match.user still apply to every user.

To add a user and obtain their multibroker URL:

   anyevent-mcp create-user chatgpt
   mcp-multibroker --print-url=chatgpt

lib/AnyEvent/MCP/Intro.pod  view on Meta::CPAN

For reverse C<--connect> servers, check the connecting process's log as
well as the multibroker. C<https://> requires a certificate trusted by
the connecting process and a hostname matching the URL. A TLS error
stops that reverse server immediately; it does not retry with plaintext.
TCP connection refusal is retried for up to sixty attempts.

=head2 Authentication fails

Obtain the URL with the same name, bind/token overrides and configuration
environment as the running process. Use the complete path; the final
slash is optional for endpoints whose configured path ends in one.
A clean URL needs an accepted bearer token.

A multibroker child credential is not necessarily the upstream listener's
credential. C<--bearer> after a child pair and C<--token> before the pairs
configure different sides of the connection.

For IMAP OAuth2, obtaining an access token does not by itself prove that
IMAP authentication will work. Check the authorized browser account,
requested IMAP scope and saved C<user> name. Copy the complete redirected
address-bar URL after authorization, even when the browser displays an

lib/AnyEvent/MCP/Server/Connect.pm  view on Meta::CPAN


   my $server = AnyEvent::MCP::Server::Connect->new (
      connect => "http://127.0.0.1:31740/TOKEN/files",
      toolsets => [$tools],
   );
   $server->start;
   AE::cv->recv;

C<$tools> is an L<AnyEvent::MCP::Server::Toolset> registered by your
application. The URL identifies a raw extension listener, not an HTTP POST
endpoint. HTTPS verifies the server certificate and hostname before sending
the JSON hello. See
L<mcp-multibroker/Reverse connections> for setting up the other side.

=head1 METHODS

=over

=item $server->start

Attempt a connection immediately. Retry refused TCP connections every second,

lib/AnyEvent/MCP/Server/Connect.pm  view on Meta::CPAN

use AnyEvent::Socket ();
use AnyEvent ();
use JSON::XS ();
use Errno qw(ECONNREFUSED);
use Scalar::Util qw(weaken);

sub new {
   my ($class, %kv) = @_;

   my $self = $class->SUPER::new (%kv);
   $self->{endpoint} = [AnyEvent::MCP::Extension::parse_url $self->{connect}];
   my $on_close = $self->{on_connection_close};
   weaken (my $weak = $self);
   $self->{on_connection_close} = sub {
      $on_close->(@_) if $on_close;
      delete $weak->{tls_connecting} if $weak;
      $weak->start if $weak && !$weak->{_closed};
   };

   $self
}

lib/AnyEvent/MCP/Server/Connect.pm  view on Meta::CPAN

   $self->{retry} = AE::timer 0, 1, sub {
      return unless $self;
      return if $self->{connector} || $self->{tls_connecting};

      if (++$self->{attempts} > 60) {
         AE::log error => "MCP reverse connection: giving up after sixty attempts";
         $self->close;
         return
      }

      my ($host, $port, $token, $alias, $scheme) = @{$self->{endpoint}};
      $self->{connector} = AnyEvent::Socket::tcp_connect $host, $port, sub {
         delete $self->{connector} if $self;
         my ($fh) = @_;
         return unless $self && !$self->{_closed};

         unless ($fh) {
            if ($! == ECONNREFUSED) {
               AE::log debug => "MCP reverse connection '$alias': $!";
               return
            }

lib/AnyEvent/MCP/Server/HTTP.pm  view on Meta::CPAN

If your application already parses HTTP, you can pass decoded requests to
L<AnyEvent::MCP::Server> instead of running another HTTP implementation.

Requests sharing one connection are dispatched in sequence, preserving their
HTTP response order; requests on other connections are independent.
Ordinary requests return JSON. When a client accepts C<text/event-stream>,
notifications from an outstanding request switch that POST response to
chunked SSE, carrying the notifications followed by the JSON-RPC result.
Without notifications the response remains JSON. SSE streams close after
their final response. This implements request-scoped Streamable HTTP, not
the old separate SSE endpoint. GET streams and subscriptions are unsupported.

Request bodies need C<Content-Length>: chunked transfer encoding is not
supported. The server does not assign protocol sessions. Legacy clients
use the 2025 request/response subset.

C<Mcp-Param-*> headers from C<x-mcp-header> tool schema annotations are not
currently validated against the body. The built-in protocol headers
C<Mcp-Protocol-Version>, C<Mcp-Method> and, where applicable, C<Mcp-Name>
must agree with modern request metadata and parameters; a mismatch is
rejected. Custom schema-derived headers do not receive this check.

lib/AnyEvent/MCP/Server/HTTP.pm  view on Meta::CPAN

      port   => 31740,
      path   => "/mcp/",
      tokens => ["a-long-random-secret", "another-long-random-secret"],
   );
   $server->listen;

Each token authorizes the same requests. For either token, a client may
POST to C</TOKEN/mcp/> without an Authorization header, or POST to
C</mcp/> with C<Authorization: Bearer TOKEN>. URL credentials are path
components, B<not> HTTP cookies. C<url> advertises the first token;
C<url (0)> returns the clean endpoint. A trailing slash may be omitted
from either request path when the configured endpoint path ends in one;
this accommodates clients that strip it from a configured URL.

The accepted tokens are static, URL-safe strings. HTTP Basic and OAuth
access-token validation are not implemented here. There is no automatic
fallback to the master-secret-derived token: that belongs to C<mcp_start>
or L<AnyEvent::MCP::Config/http_settings>.

Authentication defaults to C<tokens>, and construction B<fails> unless a
nonempty array of valid tokens is provided. To deliberately delegate
authentication to a trusted embedding layer (for example, a reverse proxy

lib/AnyEvent/MCP/Server/HTTP.pm  view on Meta::CPAN

=item host => $host

The listening address, defaulting to C<127.0.0.1>.

=item port => $port

The listening port, defaulting to zero for an automatically assigned port.

=item path => $path

The MCP endpoint path, defaulting to C</mcp/>. Bearer authentication uses
C<$path> directly; URL tokens prefix it with C</TOKEN>. If this path ends
in C</>, requests without that final slash are also accepted. Other
path differences are not normalized.

=item connection_close => $boolean

When true, disables persistent connections, sends C<Connection: close> and
closes the socket after draining each response. Defaults to false.
This is useful when an existing listener routes sockets by their first
request and cannot route subsequent requests independently.

lib/AnyEvent/MCP/Server/HTTP.pm  view on Meta::CPAN


=item on_extension => $callback->($server, $handle, $hello)

Accept raw extension connections on the HTTP listener. A first byte of C<[>
selects a bounded, newline-terminated JSON hello whose first two fields are
the protocol name and an accepted listener token. Authenticate before invoking
this callback, which validates the protocol-specific fields and takes ownership
of the handle, preserving buffered input. Throw an exception to reject it.
HTTP connections continue through the normal parser. This dispatch examines
decrypted bytes when TLS is configured, but the built-in reverse connector
currently supports only plain C<http://> endpoints.

=item on_http_request => $callback->($server, $request, $reply)

Called for every complete, syntactically valid HTTP request before MCP routing
or authentication. C<$request> is a hash containing the parsed HTTP fields
(including C<method>, C<uri>, and C<http_version>) and a C<body> field holding
the raw request body. Return false to use the normal MCP handling, or true to
handle the request yourself.

C<$reply-E<gt>($status, $reason, \%headers, $body)> sends a response, either
immediately or asynchronously after the callback returns. C<%headers> is
optional; C<Content-Type> defaults to C<application/json>, and the server
generates C<Content-Length> and manages persistent connections. The body is
an octet string. Reply at most once, and return true when taking ownership
of the request, even if the response will be sent later. The next request on
the same connection is not read until that response is sent.

The hook runs B<before> MCP authentication and CORS checks. Application
endpoints must perform their own authentication and browser request checks.
It does not replace or bypass the normal authentication of unhandled MCP
requests. Malformed or oversized requests are rejected before the hook.

=item on_connection_error => $callback->($server, $handle, $message)

Called for socket errors before closing the connection.

=item on_close => $callback->($server)

Called once after C<close> stops the listener and closes all connections.

lib/AnyEvent/MCP/Server/HTTP.pm  view on Meta::CPAN

}

# Retain useful paths in rejection logs, without leaking URL credentials.
sub _log_uri {
   my ($self, $uri) = @_;

   return '"[non-path URI]"' unless $uri =~ m{\A/};
   $uri =~ s/[?#].*//s;

   if ($self->{tokens}) {
      (my $endpoint = $self->{path}) =~ s{/\z}{};
      $endpoint = "/" unless length $endpoint;
      $uri =~ s{\A/[^/]+(?=\Q$endpoint\E(?:/|\z))}{/<token>}
         unless $endpoint eq "/";
      $uri =~ s/\Q$_\E/<token>/g for @{$self->{tokens}};
   }

   $uri = substr ($uri, 0, 160) . "..." if length $uri > 160;
   JSON::XS::encode_json $uri
}

sub _read {
   my ($self, $handle, $immediate) = @_;

lib/AnyEvent/MCP/Server/HTTP.pm  view on Meta::CPAN

      my $replied;
      my $reply = sub {
         return if $replied++ || !$self || $handle->{mcp_closed};
         my ($status, $reason, $headers, $content) = @_;
         $self->_respond ($handle, $status, $reason, $content, $headers);
      };

      return if $hook->($self, { %$hdr, body => $body }, $reply);
   }

   # ordinary root probes are not MCP requests, even when / is the endpoint
   return $self->_respond ($handle, 404, "Not Found", "")
      if $hdr->{method} eq "GET" && $hdr->{uri} eq "/";

   # some MCP clients strip a trailing slash from the configured URL.
   my $uri = $hdr->{uri};
   $uri .= "/" if $self->{path} =~ m{/$} && $uri !~ m{/$};
   my ($path_token) = $self->{tokens}
      ? grep $uri eq $self->_token_path ($_), @{$self->{tokens}} : ();
   my $token_path = defined $path_token;

lib/AnyEvent/MCP/Server/Permissions.pm  view on Meta::CPAN

prompt; see L</RULE FILES>.

For HTTP, the transport must authenticate callers before dispatching MCP
requests. This module then authorizes operations for the accepted caller. The tool
must enforce the returned grants, for example by constructing a restricted
sandbox. The permission engine does not construct that sandbox or enforce
worker isolation itself.

=head2 The three separate questions

Authentication establishes who may call the MCP endpoint.
The permission engine answers whether a requested B<action> on a
B<subject> may proceed and which B<sandbox grants> the user approved.
The application's sandbox or other enforcement then determines what
the operation can actually do. None of the three substitutes for the others.

For example, a user may approve C<write> on a project but only with
C<workdir-write> authority. This does not authorize an arbitrary
command with network access, and an approval to write a buffer does not
imply approval to save it. Ask before side effects: permission prompts
can restart the tool callback. See

lib/AnyEvent/MCP/Server/Simple.pm  view on Meta::CPAN

Sanitize sensitive arguments before passing them.

=item mcp_start %config

Starts and runs the usual server. When C<stdio> is true or
C<PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL> is C<stdio>, uses C<mcp_stdio>.
Otherwise starts HTTP without printing its URL. HTTP-capable executables
provide C<--print-url> to retrieve the URL explicitly.

The HTTP defaults are IPv4 loopback, a stable name-derived port in
16384..32767, and C</> as the endpoint path.
Without explicit C<tokens>, one server-specific token is derived from
the private global secret. The selected token authenticates either its URL
path or an
C<Authorization: Bearer TOKEN> header at the clean URL returned by
C<< $server->url (0) >>. The corresponding executable's C<--print-url>
option prints the first accepted token in its URL.

C<name> selects the C<[instance NAME]> configuration section and credential.
It defaults to C<default>.
Named settings C<bind>, C<path>, C<url_host>, C<url_scheme>, C<tokens>,

t/c04_client.t  view on Meta::CPAN

my $url = $server->url;
chop $url;
$client = AnyEvent::MCP::Client::HTTP->new (url => $url);
($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
ok $success, "URL token works without trailing slash";
$client->close;
$url = $server->url (0);
chop $url;
$client = AnyEvent::MCP::Client::HTTP->new (url => $url, bearer => "secret");
($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
ok $success, "bearer-authenticated endpoint works without trailing slash";
$client->close;
$url = $server->url;
$url =~ s{/secret/mcp/\z}{/wrong/mcp};
$client = AnyEvent::MCP::Client::HTTP->new (url => $url);
($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
ok !$success && $result->{transport} && $result->{message} =~ /404/,
   "unknown URL token without trailing slash still rejected";
$client->close;
$client = AnyEvent::MCP::Client::HTTP->new (url => $server->url . "extra");
($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });

t/c04_client.t  view on Meta::CPAN

$client->close;
$server->close;

$server = AnyEvent::MCP::Server::HTTP->new (toolsets => [$toolset],
   tokens => ["secret"], path => "/custom/");
$server->listen;
$url = $server->url;
chop $url;
$client = AnyEvent::MCP::Client::HTTP->new (url => $url);
($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
ok $success, "configured endpoint path accepts omitted trailing slash";
$client->close;
$server->close;

$server = AnyEvent::MCP::Server::HTTP->new (toolsets => [$toolset],
   tokens => ["secret"], path => "/custom");
$server->listen;
$client = AnyEvent::MCP::Client::HTTP->new (url => $server->url . "/");
($success, $result) = wait_for (sub { $client->rpc ("ping", {}, $_[0]) });
ok !$success && $result->{transport} && $result->{message} =~ /404/,
   "endpoint without trailing slash still rejects an added slash";
$client->close;
$server->close;

$server = AnyEvent::MCP::Server::HTTP->new (toolsets => [$toolset], tokens => ["alpha", "beta"]);
$server->listen;
$client = AnyEvent::MCP::Client::HTTP->new (url => $server->url (0), bearer => "beta");
($success, $result) = wait_for (sub { $client->call (echo => {}, $_[0]) });
ok $success, "second token accepted in Authorization header";
$client->close;
$server->close;

t/c15_getoptions.t  view on Meta::CPAN

{
   local @ARGV = ("--name", "memory", "--custom-instructions", "Use for lasting memories.");
   my $options = mcp_getoptions;
   is $options->{custom_instructions}, "Use for lasting memories.",
      "common custom-instructions option returns instance purpose";
}

{
   local @ARGV = ("--name", "example");
   my $options = mcp_getoptions ({ path => "/custom/", auth => "none" });
   is $options->{path}, "/custom/", "custom endpoint path is returned for startup";
   is $options->{auth}, "none", "explicit unauthenticated mode passed to startup";
}

{
   local @ARGV = ("--bad-option");
   my $error;
   {
      local *STDERR;
      open STDERR, ">", "/dev/null" or die "open /dev/null: $!";
      eval { mcp_getoptions ({ usage => "custom usage\n" }) };

t/c15_getoptions.t  view on Meta::CPAN

is $status, 0, "shared print-url exits without starting a listener";
is $out, "http://127.0.0.1:31740/first/custom/\n", "print-url uses first CLI token and effective URL";
is $err, "", "print-url has no diagnostics";

($status, $out, $err) = command (
   'mcp_getoptions ({ path => "/custom/", print_url_extra => sub { '
      . 'my $http = shift; print "ws://$http->{host}:$http->{port}/\n"; } });',
   "--bind", "127.0.0.1:31740", "--token", "first", "--print-url");
is $status, 0, "application-specific URL printing succeeds";
is $out, "http://127.0.0.1:31740/first/custom/\nws://127.0.0.1:31740/\n",
   "supplementary URL follows normal credentialed endpoint";

($status, $out, $err) = command ($script, "--name", "demo", "--bind", ":31740",
   "--token", "first", "--tls-key", "combined.pem", "--print-url");
is $status, 0, "combined TLS PEM URL discovery succeeds";
is $out, "https://127.0.0.1:31740/first/custom/\nhttp://127.0.0.1:31740/first/custom/\n",
   "TLS URL discovery prints HTTPS first and HTTP second";
is $err, "", "TLS URL discovery has no diagnostics";

($status, $out) = command ($script, "--name", "demo", "--help");
is $status, 0, "standard --help succeeds";

t/c15_getoptions.t  view on Meta::CPAN

   && $out =~ /Examples:\n  fixture --extra yes/, "caller option descriptions and examples appear";

($status, $out, $err) = command ($script, "--name", "demo", "--bind", ":0", "--print-url");
ok $status && $err =~ /port is not known/, "ephemeral port cannot be printed offline";

open my $fh, ">>", "$dir/anyevent-mcp/global.ini" or die $!;
print {$fh} "\n[instance named]\npath = /named/\n[instance mail\@doom.example+test]\npath = /mailbox/\n";
close $fh or die $!;
($status, $out, $err) = command ('mcp_getoptions;', "--name", "named",
   "--bind", ":31740", "--token", "static", "--print-url");
is $status, 0, "named endpoint URL discovery succeeds";
is $out, "http://127.0.0.1:31740/static/named/\n",
   "shared print-url retains named server path";
($status, $out, $err) = command ('mcp_getoptions;', "--name", "mail\@doom.example+test",
   "--bind", ":31740", "--token", "static", "--print-url");
is $status, 0, "email-like name accepted by shared option parser";
is $out, "http://127.0.0.1:31740/static/mailbox/\n",
   "email-like name selects its configured path";

($status, $out, $err) = command ('mcp_getoptions;', "--name", "named",
   "--set", "path=/overridden/", "--bind", ":31740",
   "--token", "static", "--print-url");
is $status, 0, "--set overrides instance configuration for URL discovery";
is $out, "http://127.0.0.1:31740/static/overridden/\n",
   "shared configuration override affects the effective endpoint path";

my $set_probe = 'mcp_getoptions; my $c = AnyEvent::MCP::Config::global_config (); '
   . 'print join "\\n", map { $c->{section}{"instance named"}{$_} } '
   . 'qw(path executable.perl prepend-path), "\\n";';
($status, $out, $err) = command ($set_probe, "--name", "named",
   "--set", "path=/first/", "-s", "path=/last/",
   "-s", "executable.perl=/special/perl=debug", "--set", "prepend-path=");
is $status, 0, "repeated -s/--set accepts trusted instance keys";
is $out, "/last/\n/special/perl=debug\n\n",
   "last assignment wins; values retain equals signs and may be empty";

t/c15_getoptions.t  view on Meta::CPAN

   ($status, $out, $err) = command ($error_probe);
}
is $status, 0, "connection error log probe exits cleanly";
unlike $err, qr/MCP connection/, "connection errors are silent at debug level";
{
   local $ENV{PERL_ANYEVENT_LOG} = "filter=trace";
   ($status, $out, $err) = command ($error_probe);
}
is $status, 0, "trace connection error log probe exits cleanly";
like $err, qr/MCP connection id=[a-f0-9]+ remote=127\.0\.0\.1:12345 client="two\\nlines": Broken pipe\n/,
   "trace connection errors identify the remote endpoint and escaped client name";
like $err, qr/MCP connection id=[a-f0-9]+: Broken pipe\n/,
   "unidentified connections still receive a connection id";

my $http_probe = q{
   use AnyEvent;
   use AnyEvent::Handle;
   use AnyEvent::MCP::Server::HTTP;
   use Socket qw(AF_UNIX SOCK_STREAM PF_UNSPEC);

   my $server = AnyEvent::MCP::Server::HTTP->new (

t/c15_getoptions.t  view on Meta::CPAN

         defined $length or die "HTTP response missing content length\n";
         $handle->push_read (chunk => $length, sub { $done->send });
      });

      $done->recv;
      $client->destroy;
   }

   $server->close;

   # / is a legitimate MCP POST endpoint; a casual GET must still be 404.
   $server = AnyEvent::MCP::Server::HTTP->new (
      path => "/", tokens => ["real-token"],
   );
   my $body = '{"jsonrpc":"2.0","id":1,"method":"ping","params":{}}';
   for my $request (
      "GET / HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "POST / HTTP/1.1\r\nContent-Type: application/json\r\n"
         . "Authorization: Bearer real-token\r\nContent-Length: " . length ($body) . "\r\n\r\n$body",
   ) {
      socketpair my $a, my $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
      my $handle = $server->accept ($a);
      $handle->{mcp_remote} = "192.0.2.1:1234";
      my $client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
      my $done = AE::cv;
      $client->push_write ($request);
      $client->push_read (line => "\r\n\r\n", sub {
         my ($handle, $header) = @_;
         my $expected = $request =~ /\AGET/ ? 404 : 200;
         die "Root endpoint: expected $expected\n" unless $header =~ /\AHTTP\/1\.1 $expected /;
         my ($length) = $header =~ /Content-Length: ([0-9]+)/i;
         defined $length or die "HTTP response missing content length\n";
         $handle->push_read (chunk => $length, sub { $done->send });
      });
      $done->recv;
      $client->destroy;
   }
   $server->close;
};
{

t/c15_getoptions.t  view on Meta::CPAN

is scalar (() = $err =~ /MCP HTTP remote=/g), 3, "only non-404 HTTP errors appear at warn level";
unlike $err, qr/real-token|wrong-token|guess-token|not-for-logs|\/health/,
   "HTTP warning log omits credentials, URL token guesses, query parameters and successful routes";

{
   local $ENV{PERL_ANYEVENT_LOG} = "filter=trace";
   ($status, $out, $err) = command ($http_probe);
}
is $status, 0, "trace HTTP rejection log probe exits cleanly";
like $err, qr/MCP HTTP remote=192\.0\.2\.1:1234: GET 404 uri="\/<token>\/mcp\/"\n/,
   "unrecognized URL token is redacted while endpoint path remains visible";
like $err, qr/: GET 404 uri="\/robots\.txt"\n/,
   "unrelated request path remains visible without its query parameters";
like $err, qr/: GET 404 uri="\/<token>\/not-mcp\/"\n/,
   "configured token is redacted even on the wrong endpoint";
like $err, qr/: GET 404 uri="\[non-path URI\]"\n/,
   "absolute-form HTTP target is not logged as a potentially credential-bearing URL";
like $err, qr/: GET 404 uri="\/"\n/,
   "GET / is logged at trace like other missing paths";
is scalar (() = $err =~ /MCP HTTP remote=/g), 9, "trace includes all failed requests but not successful responses";
is scalar (() = $err =~ /: GET 404 uri="\/"\n/g), 2,
   "GET / is quiet even when / is the actual MCP POST endpoint";
unlike $err, qr/real-token|wrong-token|guess-token|not-for-logs|\/health/,
   "HTTP log omits credentials, URL token guesses, query parameters and successful routes";

my $http_for_logs = AnyEvent::MCP::Server::HTTP->new (tokens => ["real-token"]);
is $http_for_logs->_log_uri ("/guess-token/mcp"), '"/<token>/mcp"',
   "missing final endpoint slash does not expose an unrecognized URL token";
my $root_auth = AnyEvent::MCP::Server::HTTP->new (path => "/", tokens => ["real-token"]);
is $root_auth->_log_uri ("/real-token"), '"/<token>"',
   "actual token-only endpoint hides configured URL credential";
is $root_auth->_log_uri ("/robots.txt"), '"/robots.txt"',
   "token-only endpoint still reports unrelated probe paths";
is $root_auth->_log_uri ("/guess-token"), '"/guess-token"',
   "unknown single path is not blindly classified as a token";
my $long_path = "/" . ("x" x 200);
is $http_for_logs->_log_uri ($long_path), '"' . substr ($long_path, 0, 160) . '..."',
   "HTTP warning path is bounded before logging";

($status, $out, $err) = command ($log_probe, "--quiet");
is $status, 0, "--quiet exits normally";
unlike $err, qr/file-patch|path-op|ex target=/, "--quiet suppresses activity and tool errors";
like $err, qr/error main: diagnostic failure/, "--quiet leaves normal diagnostics alone";

t/c23_http_hook.t  view on Meta::CPAN

is_deeply [map [$_->[0], $_->[1]], @requests],
   [["POST", "/review"], ["POST", "/mcp/"]],
   "hook sees both request methods and paths in order";
is $requests[0][2], "A\0B", "hook receives the raw binary body";
is_deeply JSON::XS::decode_json ($requests[1][2]),
   { jsonrpc => "2.0", id => 41, method => "ping", params => {} },
   "hook receives complete MCP JSON before normal dispatch";
$server->close;
$client->destroy;

# Custom endpoints do not weaken authentication on normal MCP routes.
socketpair $a, $b, AF_UNIX, SOCK_STREAM, PF_UNSPEC or die $!;
$server->accept ($a);
$client = AnyEvent::Handle->new (fh => $b, on_error => sub { die $_[2] });
$cv = AE::cv;
$timeout = AE::timer 5, 0, sub { $cv->croak ("HTTP auth timeout") };
$client->push_write (post ("/mcp/", '{"jsonrpc":"2.0","id":42,"method":"ping","params":{}}',
   "Content-Type: application/json\r\n"));
read_response ($client, sub {
   like $_[0], qr/^HTTP\/1\.1 401 Unauthorized\r?$/m, "MCP still requires authentication";
   $cv->send;

t/c29_imap_oauth.t  view on Meta::CPAN

use lib "lib";
use AnyEvent::MCP::IMAP::OAuth2 ();

my %kv = (
   method => "oauth2",
   server => "imap.example.org", user => "alice\@example.org",
   tls => "connect", port => 993,
   "oauth-client-id" => "client-id",
   "oauth-client-secret" => "public-secret",
   "oauth-client-auth" => "client_secret_post",
   "oauth-authorization-endpoint" => "https://login.example.org/auth",
   "oauth-token-endpoint" => "https://login.example.org/token",
   "oauth-scope" => "mail.read offline_access",
   "oauth-redirect-uri" => "http://127.0.0.1:1",
   "oauth-pkce" => 1,
   "oauth-auth-access_type" => "offline",
);

my $oauth = "AnyEvent::MCP::IMAP::OAuth2";
my $latin1 = "\x{e4}";
my $upgraded = $latin1;
utf8::upgrade $upgraded;

t/c29_imap_oauth.t  view on Meta::CPAN

is $oauth->can ("encode")->($upgraded), "%C3%A4",
   "OAuth form encoding is independent of the scalar UTF8 flag";
is $oauth->can ("form")->(scope => "mail.$latin1"), "scope=mail.%C3%A4",
   "OAuth form values are UTF-8 encoded before percent escaping";
is $oauth->can ("decode")->("%C3%A4"), $latin1,
   "OAuth percent decoder returns Unicode text";
ok !eval { $oauth->can ("decode")->("%FF"); 1 },
   "OAuth percent decoder rejects invalid UTF-8 bytes";

my ($url, $state, $verifier) = $oauth->can ("authorize")->(\%kv);
like $url, qr{\Ahttps://login\.example\.org/auth\?}, "authorization URL uses configured endpoint";
like $url, qr/(?:\?|&)code_challenge_method=S256(?:&|\z)/, "uses PKCE S256";
like $url, qr/(?:\?|&)access_type=offline(?:&|\z)/, "sends generic authorization extras";
like $url, qr/redirect_uri=http%3A%2F%2F127\.0\.0\.1%3A1/, "form-encodes redirect URI";
is length $state, 43, "state has 256 random bits encoded as base64url";
is length $verifier, 43, "PKCE verifier has 256 random bits encoded as base64url";

my $redirect = "http://127.0.0.1:1/?code=abc%2F123&state=$state";
is $oauth->can ("callback_code")->(\%kv, $state, $redirect),
   "abc/123", "redirect extracts and URL-decodes authorization code";
is $oauth->can ("callback_code")->(\%kv, $state, "http://127.0.0.1:1/?code=%C3%A4&state=$state"),

t/c29_imap_oauth.t  view on Meta::CPAN

   "http://127.0.0.1:1/?code=abc&state=$state#fragment",
) {
   ok !eval { $oauth->can ("callback_code")->(\%kv, $state, $bad); 1 },
      "rejects invalid or altered OAuth redirect URL";
}

my @requests;
{
   no warnings "redefine";
   local *AnyEvent::HTTP::http_request = sub {
      my ($method, $endpoint, @args) = @_;
      my $cb = pop @args;
      my %args = @args;
      push @requests, [$method, $endpoint, \%args];
      my $body = $args{body};
      my $response = $body =~ /grant_type=authorization_code/
         ? '{"access_token":"first-access","refresh_token":"initial-refresh","token_type":"Bearer"}'
         : '{"access_token":"renewed-access","refresh_token":"rotated-refresh","token_type":"Bearer"}';
      $args{on_body}->($response, { Status => 200 });
      $cb->(undef, { Status => 200 });
      undef
   };

   my $granted = $oauth->can ("finish")->(\%kv, $state, $verifier, $redirect);
   is $granted->{access_token}, "first-access", "authorization code exchanged for access token";
   is $granted->{refresh_token}, "initial-refresh", "authorization code gets refresh token";
   is $requests[0][0], "POST", "token grant uses POST";
   is $requests[0][1], "https://login.example.org/token", "token grant uses configured endpoint";
   like $requests[0][2]{body}, qr/grant_type=authorization_code/, "authorization grant type";
   like $requests[0][2]{body}, qr/code_verifier=/, "PKCE verifier sent to token endpoint";
   like $requests[0][2]{body}, qr/client_secret=public-secret/, "client_secret_post configured";
   is $requests[0][2]{tls_ctx}, "high", "OAuth token HTTP uses verified TLS";
   is $requests[0][2]{recurse}, 0, "no redirect following for token endpoint";

   my $dir = tempdir (CLEANUP => 1);
   my $file = "$dir/account.ini";
   $kv{"oauth-refresh-token-base64"} = MIME::Base64::encode_base64 ("initial-refresh", "");
   my $lock = AnyEvent::MCP::file_lock $file;
   AnyEvent::MCP::file_replace $file, "[account]\n"
      . (join "", map "$_ = $kv{$_}\n", sort keys %kv);
   close $lock;

   is $oauth->can ("refresh")->($file, \%kv), "renewed-access", "refresh grant supplies access token";

t/c29_imap_oauth.t  view on Meta::CPAN

   like $saved, qr/oauth-refresh-token-base64 = /, "rotated refresh token persisted";
   unlike $saved, qr/initial-refresh|rotated-refresh|renewed-access/, "token values not persisted in cleartext";
   like $requests[1][2]{body}, qr/refresh_token=initial-refresh/, "refresh uses stored token";

   my $changed = { %kv, "oauth-client-id" => "other-client" };
   ok !eval { $oauth->can ("refresh")->($file, $changed); 1 },
      "reconnect refuses changed OAuth client registration";

   {
      local *AnyEvent::HTTP::http_request = sub {
         my ($method, $endpoint, @args) = @_;
         my $cb = pop @args;
         my %args = @args;
         push @requests, [$method, $endpoint, \%args];
         $args{on_body}->('{"access_token":"basic-access","token_type":"Bearer"}', { Status => 200 });
         $cb->(undef, { Status => 200 });
         undef
      };
      my %basic = (%kv, "oauth-client-auth" => "client_secret_basic");
      my $result = $oauth->can ("token")->(\%basic, grant_type => "refresh_token", refresh_token => "old");
      is $result->{access_token}, "basic-access", "client_secret_basic token response accepted";
      like $requests[-1][2]{headers}{Authorization}, qr/^Basic /, "basic client credentials sent in header";
      unlike $requests[-1][2]{body}, qr/client_secret/, "basic mode omits client secret from body";
   }

   {
      local *AnyEvent::HTTP::http_request = sub {
         my ($method, $endpoint, @args) = @_;
         my $cb = pop @args;
         my %args = @args;
         $args{on_body}->('{"error":"invalid_grant","error_description":"do not print secrets"}',
            { Status => 400 });
         $cb->(undef, { Status => 400 });
         undef
      };
      my $ok = eval { $oauth->can ("token")->(\%kv, grant_type => "refresh_token", refresh_token => "old"); 1 };
      ok !$ok, "failed token exchange rejects error response";
      like $@, qr/HTTP 400/, "token error identifies HTTP status";
      unlike $@, qr/do not print secrets/, "token error does not echo arbitrary provider error text";
   }

   {
      local *AnyEvent::HTTP::http_request = sub {
         my ($method, $endpoint, @args) = @_;
         my $cb = pop @args;
         my %args = @args;
         my $ok = $args{on_body}->("x" x 70000, { Status => 200 });
         $cb->(undef, { Status => $ok ? 200 : 598 });
         undef
      };
      my $ok = eval { $oauth->can ("token")->(\%kv, grant_type => "refresh_token", refresh_token => "old"); 1 };
      ok !$ok && $@ =~ /response too large/, "OAuth token response size is bounded";
   }
}

t/c29_imap_oauth.t  view on Meta::CPAN

   my $file = "$dir/unicode-account.ini";
   my $text = "[account]\n" . (join "", map "$_ = $unicode{$_}\n", sort keys %unicode);
   my $lock = AnyEvent::MCP::file_lock $file;
   AnyEvent::MCP::file_save $file, $text;
   close $lock;

   my $body;
   {
      no warnings "redefine";
      local *AnyEvent::HTTP::http_request = sub {
         my ($method, $endpoint, @args) = @_;
         my $cb = pop @args;
         my %args = @args;
         $body = $args{body};
         $args{on_body}->(JSON::XS::encode_json ({
            access_token => "unicode-access", refresh_token => $rotated, token_type => "Bearer",
         }), { Status => 200 });
         $cb->(undef, { Status => 200 });
         undef
      };
      is $oauth->can ("refresh")->($file, \%unicode), "unicode-access",

t/c29_imap_oauth.t  view on Meta::CPAN

   my $result = AnyEvent::MCP::Worker::IMAP::imap_connect ($settings);
   ok $result->{connected}, "OAuth2 IMAP worker authenticated";
   is $MockOAuthIMAP::sasl, "user=alice\@example.org\001auth=Bearer first-access\001\001",
      "worker uses XOAUTH2 token instead of password login";
}

{
   no warnings "redefine";
   local *Mail::IMAPTalk::new = sub { MockOAuthIMAP->new };
   local *AnyEvent::HTTP::http_request = sub {
      my ($method, $endpoint, @args) = @_;
      my $cb = pop @args;
      my %args = @args;
      $args{on_body}->('{"access_token":"worker-refreshed","refresh_token":"worker-rotated"}',
         { Status => 200 });
      $cb->(undef, { Status => 200 });
      undef
   };
   my $dir = tempdir (CLEANUP => 1);
   my $file = "$dir/account.ini";
   $kv{"oauth-refresh-token-base64"} = MIME::Base64::encode_base64 ("worker-original", "");

t/e23_sctl.t  view on Meta::CPAN

$list = tool ("list")-> {result}{structuredContent}{instances};
is @$list, 2, "reconnection preserves separate browser and ScriptCat peers";

my $logs = "";
while (IO::Select->new ($err)->can_read (.05)) {
   my $n = sysread $err, my $chunk, 8192;
   last unless $n;
   $logs .= $chunk;
}
like $logs, qr/pairing window opened \(120s, 3 attempts\)/, "pairing activity logged without code";
like $logs, qr/listening on 127\.0\.0\.1:\d+ \(MCP HTTP \+ sctl WebSocket\)/, "startup log identifies listening endpoint";
like $logs, qr/list: 2 connected instances/, "instance discovery logs result count";
like $logs, qr/search: 1 matching methods/, "method discovery logs result count";
like $logs, qr/"scriptcat-test"#11111111: paired and connected \(1 methods\)/,
   "connection log identifies the named extension with abbreviated instance ID";
like $logs, qr/call .*method="scripts.list"/, "generic MCP call log includes forwarded method";
like $logs, qr/"scriptcat-test"#11111111: scripts.list scripts=0 \([0-9.]+s\)/,
   "successful call logs script count and elapsed time";
like $logs, qr/call .*method="debugger.send"/, "CDP operation method appears in activity log";
unlike $logs, qr/2\+2/, "arbitrary CDP expression stays out of operator log";



( run in 5.291 seconds using v1.01-cache-2.11-cpan-1bcd28dbaf1 )