AnyEvent-MCP
view release on metacpan or search on metacpan
bin/mcp-imap view on Meta::CPAN
#!/opt/bin/perl
=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
access parameters may be necessary. Authorization is human-initiated only,
never exposed through an MCP tool. After authorization, the browser will
normally show an error page because no server is listening on the loopback
redirect URI. B<This is expected; copy the full redirect URL from the address
bar anyway.> Port 1 works with Chromium's error-page behavior, but provider
redirect registrations and other browsers may differ.
IMAP runs in a separate persistent synchronous worker, so an IMAP command
does not block the MCP event loop. One request at a time is processed by the
worker. While it is blocked, the frontend can send 30-second elapsed-time
progress notifications to clients that supply a progress token. These report
frontend liveness, not progress within Dovecot. A dropped connection during
a write can leave an unknown outcome; do not blindly retry such writes.
bin/mcp-imap view on Meta::CPAN
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);
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;
print STDERR "Authenticated and saved account '$name' in $file\n";
}
if (@ARGV && $ARGV[0] eq "login") {
shift @ARGV;
login ();
exit;
}
@ARGV and die "Unexpected arguments (try 'login')\n";
mcp_permissions +AnyEvent::MCP::Server::Permissions->new (
name => "imap-$name",
actions => {
read => "Read mailboxes and messages",
modify => "Change message flags, copy, move or append mail",
manage => "Create, rename, delete or subscribe mailboxes",
expunge => "Permanently remove messages marked Deleted",
},
);
sub imap_log_request {
my ($server, $req) = @_;
return unless $req->{method} eq "tools/call";
my $args = $req->{args};
my $json = JSON::XS->new->ascii->canonical;
my %details;
for my $key (qw(mailbox destination operation limit offset max_bytes uid_range part)) {
$details{$key} = $json->encode (substr $args->{$key}, 0, 96)
if defined $args->{$key} && !ref $args->{$key};
}
$details{count} = @{$args->{uids}} if ref $args->{uids} eq "ARRAY";
( run in 1.548 second using v1.01-cache-2.11-cpan-1bcd28dbaf1 )