AnyEvent-MCP
view release on metacpan or search on metacpan
bin/mcp-imap view on Meta::CPAN
partial/empty page with a continuation cursor when matches are sparse.
MCP mail processing requires C<Encode::MIME::Header> for RFC 2047
subject and address display-name decoding.
Additional character encodings are supported when optional Encode extensions
(C<Encode::HanExtra>, C<Encode::JIS2K>, C<Encode::EUCJPASCII>) are installed;
the IMAP worker loads available extensions without requiring them. An
unsupported charset yields a decoding error, not a silent empty message.
=head1 LOGIN KEYS
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>
selects that TLS mode's default port.
=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>
IMAP SASL mechanism for OAuth, default C<xoauth2>.
=item C<oauth-auth-NAME VALUE>
Add a provider-specific authorization query parameter, for example
C<oauth-auth-access_type offline> to request a refresh token.
NAME consists of ASCII letters, digits or underscores. Protocol-defined
parameters such as C<client_id>, C<redirect_uri> and C<state> cannot
be overridden.
=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 \
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.
Then configure your MCP client to start:
mcp-imap --name personal --stdio
Or expose it through a multibroker:
mcp-multibroker --stdio mail --- mcp-imap --name personal --stdio ---
Ask the assistant:
List my subscribed mailboxes, then show the ten newest subjects
and senders in INBOX. Do not modify flags or move messages.
For example, to subscribe a folder called C<Receipts>, invoke C<mailbox>
with C<{"operation":"subscribe","mailbox":"Receipts"}>, then call C<lsub>
to see subscribed folders. Read operations request C<read> permission;
changing subscriptions requires C<manage>. A mailbox-specific permission
prompt can allow just that mailbox or all mailboxes.
To let a separately started server join an existing multibroker with
an HTTP/extension listener, run:
mcp-imap --name personal --connect http://127.0.0.1:31740/TOKEN/mail
Replace C<TOKEN> with the token obtained using the multibroker's
C<--print-url>. Use C<https://> with a trusted, matching certificate.
The C<lsub> tool lists subscribed mailboxes; C<mailboxes> lists all
visible mailboxes. Subscriptions affect folder selection in clients,
not message delivery or permissions. See
L<AnyEvent::MCP::Intro/Read and organize mail> for search and safety
examples.
=head1 TOOLS
=over
=item mailboxes
List visible mailboxes. The C<mailboxes> result contains triples of
C<[attributes, hierarchy_separator, name]>. One entry might be
C<[["\\HasNoChildren"], "/", "INBOX"]>. Mailboxes marked C<\\Noselect>
are containers, not selectable message folders.
=item lsub
List subscribed mailboxes (IMAP LSUB). Uses the same result format as C<mailboxes>.
=item messages
bin/mcp-imap view on Meta::CPAN
Allow APPEND messages with unescaped mbox From_ separator-like lines.
Unsafe with mboxo servers which fail to escape these lines. Off by default;
can only be enabled by the server operator, not through an MCP tool.
=item --provider-file FILE
Use FILE as a local Thunderbird OAuth JavaScript source with the
C<providers> command. Invalid for normal server startup or C<login>.
=item --ispdb-file FILE
Use FILE as a local Thunderbird autoconfiguration XML source with the
C<providers> command. Invalid for normal server startup or C<login>.
=back
=cut
use common::sense;
use MIME::Base64 ();
use AnyEvent ();
use AnyEvent::Fork::Early;
use Term::ReadKey ();
use JSON::XS ();
use AnyEvent::Fork ();
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"],
["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"
. " mcp-imap --name local login server localhost user alice tls none\n"
. " mcp-imap --name personal --stdio",
},
"allow-mbox-from!" => \my $allow_mbox_from,
"keepalive=i" => \my $keepalive,
"provider-file=s" => \my $provider_file,
"ispdb-file=s" => \my $ispdb_file,
;
$keepalive //= 250;
$keepalive >= 0 or die "--keepalive must be nonnegative\n";
my $name = $options->{name};
if (@ARGV && $ARGV[0] eq "providers") {
shift @ARGV;
require AnyEvent::MCP::IMAP::Providers;
AnyEvent::MCP::IMAP::Providers::run ($name, $provider_file, $ispdb_file, @ARGV);
exit;
}
(defined $provider_file || defined $ispdb_file)
and die "--provider-file and --ispdb-file are only for providers\n";
my $directory = ($ENV{XDG_CONFIG_HOME} || ($ENV{HOME} || die "HOME is not set\n") . "/.config")
. "/anyevent-mcp";
my $file = "$directory/imap-$name.ini";
sub load_account {
return {} unless -e $file;
my $sections = AnyEvent::MCP::Config::parse_ini (AnyEvent::MCP::file_load ($file), $file);
for (@$sections) {
$_->[0] eq "" || $_->[0] eq "account"
or die "$file: unexpected section $_->[0]\n";
}
my %kv = %{AnyEvent::MCP::Config::merge_sections ($sections, "account")->{account}};
\%kv
}
sub settings {
my ($kv) = @_;
for (qw(server user tls port)) {
defined $kv->{$_} && length $kv->{$_} or die "$file: missing $_; run mcp-imap --name $name login\n";
}
$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;
my $account;
if ($method eq "oauth2") {
require AnyEvent::MCP::IMAP::OAuth2;
AnyEvent::MCP::IMAP::OAuth2::validate (\%kv);
my ($url, $state, $verifier) = AnyEvent::MCP::IMAP::OAuth2::authorize (\%kv);
print STDERR "Authorize the mail account '$kv{user}', not a different account already signed into the browser.\n";
print STDERR "Open this OAuth authorization URL in a browser:\n$url\n\n";
print STDERR "After authorization, the browser will display an error page because no server listens at the redirect URI.\n";
print STDERR "This is expected. Copy the FULL URL from the browser address bar and paste it here.\n";
open my $tty, "+<", "/dev/tty"
or die "OAuth callback requires a controlling terminal: $!\n";
print {$tty} "Paste redirected URL: ";
Term::ReadKey::ReadMode ("noecho", $tty);
my $redirect = <$tty>;
Term::ReadKey::ReadMode ("restore", $tty);
print {$tty} "\n";
close $tty;
defined $redirect or die "No OAuth redirect URL supplied\n";
$redirect = AnyEvent::MCP::utf8dec $redirect;
$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);
( run in 1.369 second using v1.01-cache-2.11-cpan-1bcd28dbaf1 )