AnyEvent-MCP

 view release on metacpan or  search on metacpan

Changes  view on Meta::CPAN

	- make mcp-imap messages.more indicate any remaining search work,
	  including sparse UID ranges; document next_cursor as authoritative
	  and recommend threads for targeted whole-mailbox lookups.
	- eliminate the last utf8::is_utf8-based encoding decision in OAuth2:
	  form values are Unicode text encoded to UTF-8 before percent escaping;
	  decode redirect and persisted refresh-token bytes explicitly.
	- centralize UTF-8 configuration file I/O in file_load/file_save:
	  files contain UTF-8 bytes, parse_ini handles Unicode text, and all
	  config, rules and IMAP callers share the same conversion boundary.
	  Keep the atomic byte-oriented file_replace for JSON and raw streams;
	  preserve raw passwords and Base64/hex-encoded binary secrets.
	- load Encode::MIME::Header explicitly in the mcp-imap worker; only
	  mcp-imap requires it, not other AnyEvent::MCP components.
	- decode RFC 2047 encoded subject and address display fields in
	  mcp-imap ENVELOPE summaries; include attachment names, MIME types,
	  sizes and part numbers in read-only previews without extra FETCHes.
	- make mcp-fs remote subprocess framing byte-only: explicitly UTF-8
	  encode MCP argv and Unicode paths at their source, preserve raw OS
	  executable/env paths and binary stdin, reject non-octet frame fields;
	  add remote and VCS Unicode path/argv regressions.
	- log idle IMAP keepalive failure details at trace and suppress only

Changes  view on Meta::CPAN

	  hyphen, dot, @ and +), with separate strict managed-user names.
	- fold small state-file locking and atomic replacement helper into
	  MCP.pm instead of a separate AnyEvent::MCP::File module.
	- make --ask a shared common option, with per-option exclusion;
	  add --ask none to deny unresolved permissions and decline
	  downstream elicitation without prompting.
	- document mcp-imap login keys individually in --help and manpage;
	  support tls connect/starttls/none (including explicit unencrypted IMAP)
	  and reset default ports on TLS mode changes.
	- report LOGINDISABLED with no supported SASL mechanism cleanly on
	  IMAP password login, without obscure Authen::SASL warnings.
	- add mcp_permissions to Simple: default permission engine, explicit
	  object or explicit undef; apply --ask and automatic rule overrides
	  centrally without dropping application-supplied automatic rules.
	- give mcp-fs writable private /tmp and /var/tmp (mode 1777) even
	  with world-read; only shared-tmp or world-write exposes host
	  temporary directories. Make world-write formally imply shared-tmp
	  for permission checks; document the private/host lifetime distinction.
	- add read-only mcp-imap previews for 25 UIDs, with bounded partial
	  MIME decoding, HTML link preservation and grouped IMAP FETCH calls.
	- allow mcp-imap messages to fetch selected UIDs without SEARCH.

Changes  view on Meta::CPAN

          silently retrying; send credentials only after verified TLS succeeds.
        - omit pointless mailbox permission dimension for mcp-imap mailboxes.
        - clarify expected OAuth redirect error page and account selection.
        - implement mcp-imap OAuth2 authorization-code login with PKCE,
          human-pasted headless browser redirect, HTTPS token exchange,
          refresh-token persistence/rotation and IMAP SASL XOAUTH2.
          Keep interactive credentials outside MCP tools and argv.
        - omit unnecessary shell quotes in mcp-imap providers commands.
        - expand mcp-imap providers with Thunderbird ISPDB domain search,
          provider-hosted HTTPS autoconfig lookup and ISPDB fallback,
          password-based IMAP alternatives and provider setup instructions;
          continue printing optional OAuth configuration without saving it.
	- add per-downstream --hidden to mcp-multibroker, omitting a
	  server's tools from normal discovery while retaining explicit
	  list-tools, discover-brokers and call-tool access.
	- number the user management test consecutively as t/27_users.t.
	- tidy Perl import grouping, internal comments and source layout
	  in the command-line tools and library modules.
	- stop imposing an IMAP account file mode check; access is governed
	  by ordinary filesystem permissions.
	- use the permission engine's literal matching convention for exact

Changes  view on Meta::CPAN

	  reasons; show abnormal disconnects in the userscript console and toast.
	- document browser wire-protocol minor-version compatibility: accept
	  compatible older and newer clients without breaking base functionality.
	- remove the obsolete private stdio permission-result bridge from
	  mcp-multibroker; use ordinary form elicitation.
	- add per-tab operation discovery and calls to mcp-webbrowser, with
	  per-tab routing, ordinary MCP permissions and browser protocol 1.1;
	  the userscript initially advertises no extra operations.
	- make the unsandboxed-warning test tolerate diagnostic output from
	  non-GNU utility probes (FreeBSD and BusyBox).
	- add mcp-imap with one named password-authenticated account per instance,
	  bounded UID search, MIME reads, explicit mailbox/message mutations,
	  UIDPLUS-only targeted expunge, forked worker and MCP permissions.
	- propagate XPCSE save response ETags back to Vim session metadata;
	  make stale upload HTTP status an editor error.
	- require GNU sed in worker tool discovery; report missing-Perl diagnostics in tests.
	- xpcse: forward Vim's :write! flag through mcp-vim to browser
	  uploads, without changing upload behavior yet.
	- recommend rather than require WebSocket modules: only mcp-vim and
	  mcp-webbrowser use them; mcp-vim loads them only for browser clients,
	  and tests skip optional WebSocket coverage when unavailable.

README  view on Meta::CPAN

    for question arguments and result fields.

MAIL AND HTTP TOOLS
  Read and organize mail
    Configure an IMAP account interactively before starting its MCP server.
    Look up provider setup instructions and candidate login commands:

       mcp-imap --name personal providers alice@example.net

    Replace the example address. Provider OAuth client registrations may not
    be usable by unrelated applications. For ordinary password or
    app-password authentication, a manual login looks like:

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

    The password is requested on the terminal, never as a command argument.
    For OAuth2, use a provider-approved registration and the suggested
    "login method oauth2" parameters. Authorize the intended mail account in
    a browser, then paste the entire final redirect URL in the terminal. An
    error page at the unserved loopback redirect is expected. See mcp-imap
    for OAuth options, refresh tokens and other restrictions.

    After login, configure your MCP client to launch:

       mcp-imap --stdio --name personal

bin/mcp-fs  view on Meta::CPAN

C<--exec-prefix 'doas -n'> can read protected files on a machine using doas
instead of sudo. Remote execution uses the existing SSH command shell and
places the prefix before the remote Perl launcher. A failed prefix never
falls back to the original credentials.

=item --sudo[=USER]

Shortcut for C<--exec-prefix 'sudo -n'>, optionally adding C<-u USER>.
Overrides C<--exec-prefix>. For example, C<--sudo> with
C<--host user@host> works when SSH must log in as an unprivileged account
but passwordless sudo is permitted. C<--sudo=mail> runs as the mail user.
Sudo must work noninteractively; no password or terminal is supplied.

=item --host-dac

Keep the host user namespace and retain C<CAP_DAC_OVERRIDE> inside
bubblewrap. For example, a root worker can inspect a 0700 directory owned
by another user within a granted workdir. Other capabilities are dropped;
the existing mount and MCP permission restrictions still apply. Requires
root when bubblewrap is in use; ignored when running unsandboxed, where
the worker already has its host privileges.

bin/mcp-imap  view on Meta::CPAN


=encoding utf8

=head1 NAME

mcp-imap - inspect and manage one IMAP account through MCP

=head1 SYNOPSIS

   mcp-imap [OPTION]...
   mcp-imap [OPTION]... login [method password|oauth2] [server HOST]
       [user USER] [tls connect|starttls|none] [port PORT] [oauth-KEY VALUE]...
   mcp-imap [OPTION]... providers [SEARCH]

=head1 DESCRIPTION

Each C<--name> selects one IMAP account and an independent MCP permission
profile. Configure the account with C<login>, then run the MCP server with
C<--stdio>, C<--connect>, or an HTTP listener. Login takes passwords from
the controlling terminal without echo, never from command-line arguments
or MCP tools.

The account is stored as C<imap-NAME.ini> under
C<$XDG_CONFIG_HOME/anyevent-mcp> or C<~/.config/anyevent-mcp>, mode 0600.
Password data is Base64 in that private file, not encrypted. Protect the
file like a password. Repeating C<login> replaces the saved password after
a successful connection. For C<login method oauth2>, it prints a browser
authorization URL and accepts the resulting redirect URL from the terminal,
without listening on a callback port. The private file stores the refresh
token; later IMAP sessions refresh access tokens automatically. Neither
passwords nor OAuth tokens are accepted as command-line values.
Unencrypted IMAP authentication is available only when explicitly selected
with C<login tls none>. This exposes credentials and message contents on the connection.

C<providers> searches Thunderbird's ISPDB domain index and OAuth provider
definitions. With no argument it lists known domains. A domain, substring,
or full email address selects a provider and looks up provider-hosted HTTPS
autoconfig (preferred) or Thunderbird's ISPDB as a fallback. It prints
shell-quoted password login commands for supported IMAP/TLS alternatives,
provider setup instructions, and OAuth commands if a matching public OAuth
registration is known. An email address fills in the username.
The commands are NOT executed. Thunderbird's client registrations may not
be usable by unrelated applications. OAuth authorization requests need
registered redirect URIs and may require provider-specific optional
C<oauth-auth-NAME VALUE> arguments (e.g. C<oauth-auth-access_type offline>).

See L</LOGIN KEYS> for an individually documented list of accepted
connection and OAuth2 settings, including their defaults.
Successful OAuth2 login requires a refresh token; provider-specific offline

bin/mcp-imap  view on Meta::CPAN


C<login> accepts C<KEY VALUE> pairs (without leading dashes).
Values not supplied are inherited from the saved account when available.
Changing authentication methods retains only the connection settings.
Passwords and OAuth tokens are never accepted on the command line.

=head2 Connection and authentication

=over

=item C<method password|oauth2>

Login method. Defaults to the saved method, or C<password> for a new account.

=item C<server HOST>

IMAP hostname. Read from standard input if unset.

=item C<user USER>

IMAP username, often a complete email address. Read from standard input
if unset.

=item C<tls connect|starttls|none>

C<connect> (default) negotiates TLS immediately, typically on port 993.
C<starttls> upgrades an initially cleartext connection before authenticating,
typically on port 143. C<none> skips TLS entirely, typically on port 143:
the username, password or OAuth token, and mail contents travel unencrypted.
Use C<none> only when the connection is otherwise protected, such as by a
trusted local transport. Some IMAP servers advertise C<LOGINDISABLED>
before TLS negotiation; if they also offer no supported SASL authentication
mechanism, C<tls none> cannot authenticate until the server's policy
permits cleartext authentication.

=item C<port PORT>

IMAP TCP port, default 993 for C<connect>, and 143 for
C<starttls> or C<none>. Changing C<tls> without specifying C<port>

bin/mcp-imap  view on Meta::CPAN


=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

bin/mcp-imap  view on Meta::CPAN

=back

=head1 FIRST USE

Discover your provider's settings before logging in:

   mcp-imap --name personal providers alice@example.net

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 \

bin/mcp-imap  view on Meta::CPAN

use AnyEvent::Fork::RPC ();
use AnyEvent::MCP ();
use AnyEvent::MCP::Config ();
use AnyEvent::MCP::Server::Permissions ();

use AnyEvent::MCP::Server::Simple;

my $options = mcp_getoptions
   {
      usage       => "Usage: mcp-imap [OPTION]... [login [key value ...] | providers [SEARCH]]\n",
      description => "Serve one named IMAP account; 'login' configures password or OAuth2; 'providers' discovers mail setup.",
      options     => [
         ["--allow-mbox-from", "Allow potentially unsafe unescaped mbox From_ lines in APPEND"],
         ["--keepalive SECONDS", "Idle IMAP NOOP interval (default 250; 0 disables)"],
         ["--provider-file FILE", "Use local Thunderbird OAuth source with providers"],
         ["--ispdb-file FILE", "Use local autoconfig XML with providers"],

         "Commands:",
         ["login [KEY VALUE]...", "Configure or update an account; credentials entered interactively"],
         ["providers [SEARCH]", "Discover providers and suggested login commands"],

         "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"],

bin/mcp-imap  view on Meta::CPAN

   }
   $kv->{tls} =~ /\A(?:connect|starttls|none)\z/
      or die "$file: invalid tls mode (expected connect, starttls, or none)\n";
   $kv->{port} =~ /\A[0-9]+\z/ && $kv->{port} >= 1 && $kv->{port} <= 65535
      or die "$file: invalid port\n";
   $kv->{server} !~ /[\s\x00-\x1f]/ && length $kv->{server} <= 255
      or die "$file: invalid server\n";
   $kv->{user} !~ /[\r\n\x00]/ or die "$file: invalid user\n";

   my %connection = map +($_ => $kv->{$_}), qw(server user port tls);
   my $method = $kv->{method} || "password";
   if ($method eq "oauth2") {
      require AnyEvent::MCP::IMAP::OAuth2;
      AnyEvent::MCP::IMAP::OAuth2::validate ($kv);
      defined $kv->{"oauth-refresh-token-base64"}
         && $kv->{"oauth-refresh-token-base64"} =~ /\A[A-Za-z0-9+\/]*={0,2}\z/
         && length $kv->{"oauth-refresh-token-base64"}
         or die "$file: missing or invalid OAuth refresh token; run mcp-imap login\n";
      return {
         %connection, method => "oauth2", account_file => $file, oauth => { %$kv },
      };
   }

   $method eq "password" or die "$file: invalid login method\n";
   defined $kv->{"password-base64"}
      && $kv->{"password-base64"} =~ /\A[A-Za-z0-9+\/]*={0,2}\z/
      && length $kv->{"password-base64"}
      or die "$file: missing or invalid password encoding\n";
   +{
      %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;
   %kv = map +(exists $old->{$_} ? ($_ => $old->{$_}) : ()), qw(server user tls port)
      if ($old->{method} || "password") ne $method;
   %kv = (%kv, %input);
   delete $kv{port} if exists $input{tls} && !exists $input{port} && ($old->{tls} // "") ne $input{tls};
   $kv{method} = $method;
   delete $kv{"password-base64"} if $method eq "oauth2";
   delete @kv{grep /^oauth-/, keys %kv} if $method eq "password";

   for my $key (qw(server user)) {
      next if defined $kv{$key} && length $kv{$key};
      print STDERR "$key: ";
      chomp ($kv{$key} = <STDIN> // "");
      $kv{$key} = AnyEvent::MCP::utf8dec $kv{$key};
   }
   $kv{tls} ||= "connect";
   $kv{port} ||= $kv{tls} eq "connect" ? 993 : 143;

bin/mcp-imap  view on Meta::CPAN

      $redirect =~ s/\r?\n\z//;
      my $tokens = AnyEvent::MCP::IMAP::OAuth2::finish (\%kv, $state, $verifier, $redirect);
      my $refresh = $tokens->{refresh_token}
         or die "OAuth provider returned no refresh token; configure offline access and try again\n";
      $kv{"oauth-refresh-token-base64"} = MIME::Base64::encode_base64 (AnyEvent::MCP::utf8enc $refresh, "");
      $account = settings (\%kv);
      $account->{access_token} = $tokens->{access_token};
   } else {
      open my $tty, "+<", "/dev/tty"
         or die "Password requires a controlling terminal: $!\n";
      print {$tty} "IMAP password for $kv{user}\@$kv{server}: ";
      Term::ReadKey::ReadMode ("noecho", $tty);
      my $password = <$tty>;
      Term::ReadKey::ReadMode ("restore", $tty);
      print {$tty} "\n";
      close $tty;
      defined $password or die "No password supplied\n";
      $password =~ s/\r?\n\z//;
      length $password or die "Empty password\n";
      $kv{"password-base64"} = MIME::Base64::encode_base64 ($password, "");
      $account = settings (\%kv);
   }

   require AnyEvent::MCP::Worker::IMAP;
   AnyEvent::MCP::Worker::IMAP::imap_connect ($account);

   my $lock = AnyEvent::MCP::file_lock $file;
   AnyEvent::MCP::file_save $file,
      AnyEvent::MCP::Config::serialize_ini [["account", \%kv]];
   close $lock;

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

      my $settings = (AnyEvent::MCP::Config::global_config)->{section}{"client $kv{name}"} || {};
      %kv = (
         (map { exists $settings->{$_} ? ($_ => $settings->{$_}) : () }
            qw(url bearer timeout)),
         %kv,
      );
   }

   defined $kv{url}
      or die "HTTP client requires a URL\n";
   !exists $kv{username} && !exists $kv{password}
      or die "HTTP Basic authentication is unsupported\n";
   die "Invalid bearer token\n" if defined $kv{bearer} && $kv{bearer} !~ /\A[^\s]+\z/;

   $class->SUPER::new (timeout => 300, %kv)
}

sub _send {
   my ($self, $message, $done) = @_;

   my $key = exists $message->{id} && !exists $message->{result} && !exists $message->{error}

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


   use AnyEvent::MCP::Config;

   my $config = AnyEvent::MCP::Config::global_config;
   my $token = $config->user_credentials ("agni")->[0][2];
   my $url = $config->http_url ("agni", undef, path => "/");

=head1 DESCRIPTION

An MCP server and its clients often need matching credentials. Rather than
maintaining a separate password for each server and user, this module can
derive them from one private master secret. Users are defined by
C<user.NAME = GENERATION> in C<[global]>, C<[program PROGRAM]> or
C<[instance NAME]>, in that order of precedence. An absent global
C<user.default> is implicitly enabled at generation 1.

The shared file format is described in L<AnyEvent::MCP/GLOBAL CONFIGURATION>.
Loading this module does not read any files. C<global_config> loads the
configuration, ensures a persistent master secret exists and caches the
initialized object for the process.

A missing secret is generated using C<AnyEvent::MCP::random_bytes> and
appended under a file lock. Failure to save the secret is fatal, rather
than using a temporary secret that other processes cannot reproduce.
A supplied invalid secret is an error. Changing or losing the master
secret invalidates all credentials derived from it.

Derivation uses C<derive_secret> with the random master key.
The application namespace, purpose, program, instance name and username are
separately length-prefixed, so distinct contexts derive different credentials.
Deriving a password does not create an account or configure the server to
accept it: authentication still belongs to the server.

=head1 METHODS

=over

=item $config = AnyEvent::MCP::Config::global_config (file => $file)

Return the process-global configuration object, loaded and initialized.
The first call accepts the same arguments as C<new>, and ensures that the

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

   for my $server ($doc->findnodes ("/clientConfig/emailProvider/incomingServer[\@type='imap']")) {
      my %info = (
         server => $server->findvalue ("./hostname"),
         port => $server->findvalue ("./port"),
         tls => $server->findvalue ("./socketType"),
         user => $server->findvalue ("./username"),
      );
      my @auth = map $_->textContent, $server->findnodes ("./authentication");
      my @methods;
      push @methods, "oauth2" if grep $_ eq "OAuth2", @auth;
      push @methods, "password" if grep $_ eq "password-cleartext", @auth;
      next unless @methods;
      $info{tls} = $info{tls} eq "SSL" ? "connect" : $info{tls} eq "STARTTLS" ? "starttls" : next;
      $info{port} =~ /^\d+$/ && $info{port} >= 1 && $info{port} <= 65535 or next;
      if (defined $email) {
         my ($local, $domain) = split /\@/, $email, 2;
         for my $key (qw(server user)) {
            $info{$key} =~ s/%EMAILADDRESS%/$email/g;
            $info{$key} =~ s/%EMAILLOCALPART%/$local/g;
            $info{$key} =~ s/%EMAILDOMAIN%/$domain/g;
         }

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

=head1 MAIL AND HTTP TOOLS

=head2 Read and organize mail

Configure an IMAP account interactively before starting its MCP server.
Look up provider setup instructions and candidate login commands:

   mcp-imap --name personal providers alice@example.net

Replace the example address. Provider OAuth client registrations may not
be usable by unrelated applications. For ordinary password or app-password
authentication, a manual login looks like:

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

The password is requested on the terminal, never as a command argument.
For OAuth2, use a provider-approved registration and the suggested
C<login method oauth2> parameters. Authorize the intended mail account in
a browser, then paste the entire final redirect URL in the terminal.
An error page at the unserved loopback redirect is expected. See
L<mcp-imap> for OAuth options, refresh tokens and other restrictions.

After login, configure your MCP client to launch:

   mcp-imap --stdio --name personal

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

         $imap->_imap_cmd ("starttls", 0, "")
            or die "IMAP STARTTLS rejected: " . $imap->get_last_error . "\n";
         IO::Socket::SSL->start_SSL ($imap->{Socket}, %tls)
            or die "IMAP TLS handshake failed: " . IO::Socket::SSL::errstr () . "\n";
         delete $imap->{Cache}{capability}; # TLS changes advertised mechanisms
      }
      $imap->{UseBlocking} = 1;
   }

   $imap or die "IMAP connection failed: $@\n";
   if (($config->{method} || "password") eq "oauth2") {
      require AnyEvent::MCP::IMAP::OAuth2;
      require Authen::SASL;
      my $mechanism = uc ($config->{oauth}{"oauth-sasl"} || "xoauth2");
      $imap->capability->{"auth=" . lc $mechanism}
         or die "IMAP server does not advertise AUTH=$mechanism\n";
      my $token = $config->{access_token}
         || AnyEvent::MCP::IMAP::OAuth2::refresh ($config->{account_file}, $config->{oauth});
      my $sasl = Authen::SASL->new (
         mechanism => $mechanism,
         callback => { user => $config->{user}, pass => $token },
      );
      $imap->authenticate ($sasl)
         or die "IMAP OAuth authentication failed: " . $imap->get_last_error . "\n";
   } else {
      my $caps = $imap->capability;
      my $sasl = grep /^auth=(?:plain|login|digest-md5)\z/, keys %$caps;
      if (!$sasl && $caps->{logindisabled}) {
         die "IMAP server advertises LOGINDISABLED and no supported AUTH mechanism. "
           . "Use tls connect/starttls, or allow cleartext authentication on the IMAP server.\n";
      }
      if (!$sasl && $config->{password} =~ /[^\x00-\x7f]/) {
         die "IMAP server offers no supported AUTH mechanism for a non-ASCII password.\n";
      }
      $imap->login ($config->{user}, $config->{password})
         or die "IMAP authentication failed: " .
            ($imap->get_last_error || $@ || "server supplied no error details") . "\n";
   }

   $imap->uid (1);
   $imap->parse_mode (DecodeUTF8 => 1);

   +{ connected => JSON::XS::true, capabilities => [sort keys %{$imap->capability}] }
}

t/c02_config.t  view on Meta::CPAN

      $^X, "-Ilib", "bin/anyevent-mcp", "--config", $file, @args);
   close $in;
   local $/;
   my $stdout = <$out>;
   my $stderr = <$err>;
   waitpid $pid, 0;

   ($? >> 8, $stdout, $stderr)
}

my ($status, $output) = command ("password", "agni", "alice");
ok $status, "Basic password command is removed";
($status, $output) = command ("token", "agni");
ok $status && !$output, "token command removed";
($status, $output) = command ("url", "agni");
ok $status && !$output, "URL command removed";
($status, $output) = command ("--help");
ok !$status && $output =~ /Usage: anyevent-mcp/, "help command";
($status, $output) = command ("unknown");
ok $status, "invalid command";
($status, $output) = command ("init");
ok !$status, "init command idempotently ensures existing configuration";

t/c04_client.t  view on Meta::CPAN

$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;
eval { AnyEvent::MCP::Client::HTTP->new (url => "http://localhost/", bearer => "token", username => "alice", password => "pw") };
ok $@ =~ /Basic authentication is unsupported/, "Basic credentials rejected even with bearer";
eval { AnyEvent::MCP::Client::HTTP->new (url => "http://localhost/", username => "alice") };
ok $@ =~ /Basic authentication is unsupported/, "Basic client credentials rejected";

$server = AnyEvent::MCP::Server::HTTP->new (auth => "none", toolsets => [$toolset], versions => ["2025-06-18"]);
$server->listen;
$client = AnyEvent::MCP::Client::HTTP->new (url => $server->url);
($success, $result) = wait_for (sub { $client->call (echo => { value => 42 }, $_[0]) });
ok $success && $result->{structuredContent}{value} == 42, "legacy fallback tool call";
ok $client->{protocol_version} eq "2025-06-18", "negotiated legacy version";

t/c15_getoptions.t  view on Meta::CPAN

         return 0 unless $req->{uri} eq "/health";
         $reply->(200, "OK", {}, "ok");
         1
      },
   );
   my $timeout = AE::timer 5, 0, sub { die "HTTP probe timed out\n" };

   for my $request (
      "GET / HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "GET /guess-token/mcp/ HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "GET /robots.txt?password=not-for-logs HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "GET /real-token/not-mcp/ HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "GET http://example.org/mcp/ HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "POST /mcp/ HTTP/1.1\r\nContent-Length: 0\r\nAuthorization: Bearer wrong-token\r\n\r\n",
      "POST /real-token/mcp/ HTTP/1.1\r\nContent-Type: application/json\r\nContent-Length: 1\r\n\r\n!",
      "GET /health HTTP/1.1\r\nContent-Length: 0\r\n\r\n",
      "malformed\r\n\r\n",
   ) {
      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";

t/c29_imap_oauth.t  view on Meta::CPAN

   no warnings "redefine";
   local *Mail::IMAPTalk::new = sub { MockOAuthIMAP->new };
   my $settings = {
      server => "imap.example.org", port => 993, tls => "connect",
      user => "alice\@example.org", method => "oauth2",
      oauth => \%kv, access_token => "first-access",
   };
   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"}',

t/e24_imap.t  view on Meta::CPAN

   sub delete { $seen{delete} = [@_]; 1 }
   sub logout { 1 }
}

{
   no warnings "redefine";
   local *Mail::IMAPTalk::new = sub { IMAPMock->new };
   local %IMAPMock::cap = (move => 1, uidplus => 1);

   my ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("connect", {
      server => "example.org", port => 993, tls => "connect", user => "a", password => "secret",
   });
   ok $ok, "connected with mock Mail::IMAPTalk";
   is $result->{connected}, 1, "authenticated";

   ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("mailboxes", {});
   ok $ok, "list";
   is scalar @{$result->{mailboxes}}, 2, "two mailboxes";

   ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("lsub", {});
   ok $ok, "lsub";

t/e24_imap.t  view on Meta::CPAN

         mailbox => "INBOX", data_base64 => MIME::Base64::encode_base64 ($head . $body, ""),
      });
      is !!$ok, !!$allowed, "APPEND $label " . ($allowed ? "allowed" : "blocked");
      is !!$IMAPMock::seen{append}, !!$allowed, "APPEND $label: no unexpected server write";
      if (!$allowed) {
         like $result, qr/raw message line $line\b/, "APPEND $label: exact raw line number";
         like $result, qr/mboxo From_ separator.*new message boundary/s, "APPEND $label: explains mboxo corruption risk";
      }
   }

   my %login = (server => "example.org", port => 993, tls => "connect", user => "a", password => "secret");
   ($ok) = AnyEvent::MCP::Worker::IMAP::run ("connect", { %login, allow_mbox_from => 1 });
   ok $ok, "override enabled by connection settings";
   ($ok) = AnyEvent::MCP::Worker::IMAP::run ("append", {
      mailbox => "INBOX", data_base64 => MIME::Base64::encode_base64 ($head . "From sender Sat Oct 24 20:05:09 2026\r\n", ""),
   });
   ok $ok, "operator override permits otherwise rejected message";

   ($ok) = AnyEvent::MCP::Worker::IMAP::run ("connect", \%login);
   ok $ok, "default safety restored on reconnect";
   ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("append", {

t/e24_imap.t  view on Meta::CPAN

{
   no warnings "redefine";
   my (%args, $upgrades, $handshakes, $mock);
   local *Mail::IMAPTalk::new = sub {
      my ($class, %options) = @_;
      %args = %options;
      $mock = IMAPMock->new;
   };
   local *IMAPMock::_imap_cmd = sub { ++$upgrades; 1 };
   local *IO::Socket::SSL::start_SSL = sub { ++$handshakes; 1 };
   my %login = (server => "localhost", user => "alice", password => "secret");

   my ($ok) = AnyEvent::MCP::Worker::IMAP::run ("connect",
      { %login, port => 143, tls => "none" });
   ok $ok && !$args{UseSSL} && !$upgrades && !$handshakes,
      "tls none authenticates over cleartext without STARTTLS or TLS";
   ok $mock->{UseBlocking}, "cleartext IMAP worker uses blocking socket operations";

   ($ok) = AnyEvent::MCP::Worker::IMAP::run ("connect",
      { %login, port => 993, tls => "connect" });
   ok $ok && $args{UseSSL} && !$upgrades && !$handshakes,

t/e24_imap.t  view on Meta::CPAN

   ok $ok && !$args{UseSSL} && $upgrades == 1 && $handshakes == 1,
      "tls starttls performs explicit upgrade before authentication";
}

{
   no warnings "redefine";
   my $logins;
   local *Mail::IMAPTalk::new = sub { IMAPMock->new };
   local *IMAPMock::login = sub { ++$logins; 1 };
   local %IMAPMock::cap = (logindisabled => 1);
   my %login = (server => "localhost", user => "root", password => "secret",
                port => 143, tls => "none");

   my ($ok, $error) = AnyEvent::MCP::Worker::IMAP::run ("connect", \%login);
   ok !$ok && $error =~ /LOGINDISABLED.*no supported AUTH mechanism/,
      "cleartext server that refuses LOGIN and offers no usable SASL reports the cause";
   is $logins || 0, 0, "no attempt to authenticate with an empty SASL mechanism list";

   $IMAPMock::cap{"auth=plain"} = 1;
   ($ok) = AnyEvent::MCP::Worker::IMAP::run ("connect", \%login);
   ok $ok && $logins == 1, "server-advertised AUTH PLAIN is not rejected";

   delete $IMAPMock::cap{"auth=plain"};
   delete $IMAPMock::cap{logindisabled};
   ($ok, $error) = AnyEvent::MCP::Worker::IMAP::run ("connect",
      { %login, password => "p\x{e4}ssword" });
   ok !$ok && $error =~ /non-ASCII password/,
      "non-ASCII password requiring SASL reports absent AUTH mechanisms";
}

{
   no warnings "redefine";
   my ($connections, $noops) = (0, 0);
   my $open = 1;
   local *Mail::IMAPTalk::new = sub { ++$connections; IMAPMock->new };
   local *IMAPMock::is_open = sub { $open };
   local *IMAPMock::noop = sub { ++$noops; 1 };
   local %IMAPMock::cap;
   my %login = (server => "localhost", port => 143, tls => "none", user => "root", password => "secret");

   my ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("connect", \%login);
   ok $ok && $connections == 1, "initial worker IMAP connection";
   ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("ping", {});
   ok $ok && $noops == 1, "keepalive sends NOOP on live session";
   is $connections, 1, "successful keepalive does not reconnect";

   $open = 0;
   ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("ping", {});
   ok !$ok && $result =~ /closed during keepalive/, "dead keepalive reports failure";

t/e24_imap.t  view on Meta::CPAN

{
   no warnings "redefine";
   my (@thread_args, $thread_calls);
   local *Mail::IMAPTalk::new = sub { IMAPMock->new };
   local %IMAPMock::cap = ("thread=orderedsubject" => 1);
   local *IMAPMock::thread = sub {
      @thread_args = @_;
      ++$thread_calls;
      [[100, 102, 111], [101], [104, 106]];
   };
   my %login = (server => "localhost", port => 143, tls => "none", user => "root", password => "secret");
   my ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("connect", \%login);
   ok $ok, "threading mock connected";

   ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("threads", {
      mailbox => "INBOX", uid_range => "100:200", uidvalidity => 123,
      filter => { not => { deleted => 1 }, subject => "x(quoted)" },
   });
   ok $ok, "UID THREAD ORDEREDSUBJECT succeeds";
   is_deeply $result->{threads}, [[100, 102, 111], [101], [104, 106]],
      "nested UID threads retained in server order";

t/e24_imap.t  view on Meta::CPAN

   my ($sort_calls, @sort_args, $fail_sort) = (0);
   my $sort_size = 205;
   local *Mail::IMAPTalk::new = sub { IMAPMock->new };
   local %IMAPMock::cap = (sort => 1);
   local *IMAPMock::sort = sub {
      @sort_args = @_;
      ++$sort_calls;
      return if $fail_sort;
      [1001 .. 1000 + $sort_size];
   };
   my %login = (server => "localhost", port => 143, tls => "none", user => "root", password => "secret");
   my ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("connect", \%login);
   ok $ok, "SORT snapshot mock connected";

   ($ok, $result) = AnyEvent::MCP::Worker::IMAP::run ("sort_create", {
      mailbox => "INBOX", filter => { before => "1-Feb-2021", undeleted => 1 },
   });
   ok $ok, "create SORT snapshot with SEARCH filter";
   is_deeply [@sort_args[1 .. $#sort_args]],
      ["(SUBJECT DATE)", "UTF-8", "BEFORE", "1-Feb-2021", "UNDELETED"],
      "SORT uses subject/date and selected search criteria";

t/e28_imap_providers.t  view on Meta::CPAN


my $xml = <<'XML';
<clientConfig version="1.1">
  <emailProvider id="example.com">
    <incomingServer type="pop3"><hostname>pop.example.com</hostname></incomingServer>
    <incomingServer type="imap">
      <hostname>imap.%EMAILDOMAIN%</hostname>
      <port>993</port><socketType>SSL</socketType>
      <username>%EMAILADDRESS%</username>
      <authentication>OAuth2</authentication>
      <authentication>password-cleartext</authentication>
    </incomingServer>
  </emailProvider>
</clientConfig>
XML

my $parsed = AnyEvent::MCP::IMAP::Providers::parse_oauth ($source);
is $parsed->{"example.com"}{issuer}, "login.example.com", "issuer lookup";
is $parsed->{"example.com"}{scope}, "mail.read offline_access", "IMAP + extra scope";
is $parsed->{"imap.example.net"}{scope}, "simple-scope", "literal scope";
is $parsed->{"example.com"}{clientId}, "client'123", "client id parsed";
like eval { AnyEvent::MCP::IMAP::Providers::parse_oauth ("// changed"); 1 } ? "" : $@,
   qr/kHostnames/, "changed JavaScript layout rejected";

my $server = AnyEvent::MCP::IMAP::Providers::parse_ispdb ($xml, "somebody\@example.com");
is_deeply $server->{servers}[0], {
   server => "imap.example.com", port => 993, tls => "connect", user => "somebody\@example.com",
   methods => [qw(oauth2 password)],
}, "ISPDB XML placeholders and connection data";

$server = AnyEvent::MCP::IMAP::Providers::parse_ispdb ($xml);
is scalar @{$server->{servers}}, 0, "unresolved hostname placeholder is not invented";

is_deeply AnyEvent::MCP::IMAP::Providers::parse_index ('["a.com","b.de","invalid/x"]'),
   [qw(a.com b.de)], "ISPDB directory index parsed and validated";

SKIP: {
   skip "mcp-imap CLI dependencies unavailable", 24

t/e28_imap_providers.t  view on Meta::CPAN

         1
      };

   open my $help_fh, "-|", $^X, "-Ilib", "bin/mcp-imap", "--help"
      or die "mcp-imap --help: $!";
   my $help = do { local $/; <$help_fh> };
   close $help_fh;
   is $? >> 8, 0, "mcp-imap --help works";
   like $help, qr/\nCommands:\n\s+login \[KEY VALUE\]/,
      "help documents login and providers commands separately";
   like $help, qr/\nLogin keys \(KEY VALUE, not --options\):\n\s+method password\|oauth2/,
      "help lists login keys separately from command-line switches";
   like $help, qr/\nOAuth2 login keys \(method oauth2\):\n\s+oauth-client-id ID/,
      "OAuth2 login keys have their own help section";
   like $help, qr/\btls connect\|starttls\|none\b/,
      "help explains all three TLS modes, including explicit no encryption";
   like $help, qr/oauth-auth-NAME VALUE/,
      "help lists provider-specific OAuth authorization parameters";

   my ($jsfh, $jsfile) = tempfile ();
   my ($xmlfh, $xmlfile) = tempfile ();

t/e28_imap_providers.t  view on Meta::CPAN

   ($out, $status) = run_cli ("alice\@example.com");
   is $status, 0, "provider command succeeded";
   like $out, qr/^\s+method oauth2/m, "suggests method oauth2";
   like $out, qr/^\s+server imap\.example\.com/m, "uses ISPDB hostname";
   like $out, qr/^\s+user alice\@example\.com/m, "substitutes email address";
   like $out, qr/^\s+oauth-scope 'mail\.read offline_access'/m, "uses IMAP scope plus extra";
   like $out, qr/^\s+oauth-client-id 'client'\\''123'/m, "shell-quotes client id";
   like $out, qr/^mcp-imap --name sample login/m, "unquotes safe account name";
   like $out, qr/^\s+oauth-redirect-uri http:\/\/127\.0\.0\.1:1/m, "defaults to blocked loopback port";
   like $out, qr/# OAuth2:/, "OAuth command identified";
   like $out, qr/# Password:\nmcp-imap --name sample login/, "password fallback has runnable syntax";
   like $out, qr/# Password:\nmcp-imap --name sample login \\\n  method password/m,
      "password fallback explicitly selects method";
   unlike $out, qr/# Password:\nmcp-imap.*?method oauth2/s, "password fallback avoids OAuth keys";
   
   ($out, $status) = run_cli ("example");
   is $status, 0, "ambiguous search lists candidates";
   like $out, qr/Specify a domain or email/, "ambiguous search does not invent a choice";
}

is AnyEvent::MCP::IMAP::Providers::quote ("'"), q(''\'''), "POSIX shell quoting";
is AnyEvent::MCP::IMAP::Providers::quote ("http://127.0.0.1:1"), "http://127.0.0.1:1",
   "safe URL needs no quotes";
is AnyEvent::MCP::IMAP::Providers::quote ("a b"), "'a b'", "space still requires shell quoting";

my $password_only = <<'XML';
<clientConfig version="1.1"><emailProvider id="gmx.test">
  <displayName>Test ISP</displayName>
  <incomingServer type="imap"><hostname>imap.mail.example</hostname><port>993</port>
    <socketType>SSL</socketType><username>%EMAILADDRESS%</username>
    <authentication>password-cleartext</authentication></incomingServer>
  <incomingServer type="imap"><hostname>imap.mail.example</hostname><port>143</port>
    <socketType>STARTTLS</socketType><username>%EMAILADDRESS%</username>
    <authentication>password-cleartext</authentication></incomingServer>
  <enable visiturl="https://mail.example/enable"><instruction>Enable IMAP in settings</instruction></enable>
</emailProvider></clientConfig>
XML
my $ordinary = AnyEvent::MCP::IMAP::Providers::parse_ispdb ($password_only, "test\@gmx.de");
is scalar @{$ordinary->{servers}}, 2, "password-only provider retains both IMAP alternatives";
is_deeply [map $_->{tls}, @{$ordinary->{servers}}], [qw(connect starttls)], "TLS alternatives retained";
is_deeply $ordinary->{servers}[0]{methods}, ["password"], "password-only provider supported";
is_deeply $ordinary->{notes}, ["Enable IMAP in settings"], "provider enable instructions retained";
is_deeply $ordinary->{links}, ["https://mail.example/enable"], "provider setup URL retained";

done_testing;



( run in 1.451 second using v1.01-cache-2.11-cpan-f5f21f1076c )