#!/opt/bin/perl

=head1 NAME

mcp-mqtt - survey, publish and subscribe to MQTT messages

=head1 SYNOPSIS

   mcp-mqtt --name home login server localhost user '' tls none
   mcp-mqtt --name home --stdio

=head1 DESCRIPTION

Connect to one configured MQTT broker. Configure the endpoint and credentials
with C<login> first. It tests authentication and saves the account privately
in C<mqtt-NAME.ini> alongside the other AnyEvent::MCP configuration files.
Passwords are read from the controlling terminal without echo, not from
command-line arguments or environment variables.

The ordinary tools are:

=over

=item get

Get retained state for one exact topic. Returns as soon as the retained
message arrives; default timeout 0.5 seconds after successful SUBSCRIBE.
A missing message means none was observed, not that the topic is absent.

=item collect

Subscribe temporarily to an MQTT filter. C<mode> selects retained, live or
all received messages; default retained. C<topics_only> returns distinct
topic names. Stop at C<count>, the byte limit, or C<timeout>. MQTT has no
topic-list operation or end-of-retained-data marker. Subscribe separately to
C<$SYS/#> to inspect broker statistics.

Optionally supply a C<publish> object: subscribe and await SUBACK, then
publish and collect live responses on the same connection. Default count is
one for such an exchange. C<json_match> matches exact typed values of fields
in a JSON object; C<payload_equals> matches a whole UTF-8 payload. For
example, publish a Zigbee2MQTT bridge request containing a unique transaction
ID and match the transaction field in the response. A timeout does not
imply that the request failed. The publication outcome is returned separately.

=item publish

Publish an exact topic and exactly one of C<payload> (UTF-8) and
C<payload_base64> (binary). QoS 0 or 1, default 1. Retain defaults to false.
An empty retained payload deletes retained state. QoS 1 acknowledgment is
from the broker, not the recipient application. An uncertain publication
is not automatically retried.

=item status

Show the configured endpoint and event-monitor connection state, without
passwords or webhook secrets.

=item subscription-list, subscription-revoke

List or revoke persistent MCP event subscriptions.

=back

Transient operations use independent clean MQTT sessions and bounded
collection time/output. The delivered retain flag distinguishes retained
replay from ordinary live arrivals, not necessarily whether the publisher
asked the broker to retain a live message.

=head2 Events

The C<message> event accepts a C<filter> argument
and optional C<payload_equals>, C<json_match>, C<policy> (immediate,
throttle, debounce), C<interval> in seconds and C<durable>. Different
arguments create independent subscriptions. Identical filters share an
MQTT connection. Initial retained replay is excluded. Notifications carry
ordered C<events>, C<epoch> and C<seq> as in C<mcp-events>; individual
messages carry C<source_epoch>, which changes on MQTT reconnect. No MQTT
history is replayed after a disconnect. Durable notification delivery
persists queued notifications, not the upstream MQTT session.

All filters are available unless restricted with one or more
C<--event-filter> options. These match the
requested filter exactly, not the topics it covers. Use only a trusted
MCP instance, especially via an unguarded multibroker (which does not
forward individual user identity). The MQTT account's broker ACLs
still apply. Ordinary tools have separate read, publish and
publish-retained permissions. Account identity is part of their scope.

Start the multibroker child eagerly when using events. The ordinary
stdio inactivity exit remains enabled without subscriptions; active
event leases prevent it. Leases survive restart, but clean MQTT
sessions cannot collect offline traffic.
Monitor status shows connection/subscription failures and reconnects.

=head1 OPTIONS

See L<AnyEvent::MCP::Server::Simple> for common options.

=over

=item --event-filter FILTER

Repeat to allow only these exact subscription filters.

=item --allow-http

Allow loopback HTTP webhook callbacks for testing, as in mcp-events.

=item --event-profile auto|openai|beta

Select webhook wire profile, as in mcp-events.

=back

=head2 Login

C<login> accepts key/value pairs C<server HOST>, C<port PORT>,
C<user USER> and C<tls connect|none>. Omitted values reuse saved settings;
a new account prompts for server and user. Empty user selects anonymous
authentication. TLS with peer and hostname verification is the default
(port 8883); explicitly select C<tls none> for plain MQTT (port 1883).
Plain MQTT exposes passwords and messages to the network.
A failed login leaves the old account unchanged. Credentials are stored
as private, Base64-encoded password bytes, not encrypted. Restart the
server after changing the account.

=cut

use common::sense;
use Types::Serialiser ();

use Digest::SHA ();
use Encode ();
use MIME::Base64 ();
use File::Basename ();
use Time::HiRes ();

use AnyEvent ();
use AnyEvent::MCP ();
use AnyEvent::MCP::Config ();
BEGIN { delete $ENV{ANYEVENT_MQTT_DEBUG} } # would print MQTT credentials and packets to stdout
use AnyEvent::MCP::MQTT ();
use AnyEvent::MCP::Server::Permissions ();
use AnyEvent::MCP::Server::Simple;
use AnyEvent::MCP::Server::Events qw(
   $json $channels $subscriptions %verification
   events_init random_id timestamp save_state load_state live_subscriptions
   drop_subscription kick event_subscription accept_event
);

my $profile = "auto";
my $options = mcp_getoptions
   {
      usage => "Usage: mcp-mqtt [OPTION]... [login [KEY VALUE]...]\n",
      description => "Survey retained MQTT state, collect traffic, publish and deliver webhook events.",
      options => [
         ["--event-filter FILTER", "Allow exact event filter (repeatable)"],
         ["--allow-http", "Allow loopback HTTP callbacks"],
         ["--event-profile PROFILE", "auto, openai or beta"],

         "Commands:",
         ["login [KEY VALUE]...", "Configure or update an account; password read interactively"],

         "Login keys (KEY VALUE, not --options):",
         ["server HOST", "MQTT hostname (prompts if missing)"],
         ["user USER", "MQTT username (prompts if missing); empty string for anonymous"],
         ["tls connect|none", "Verified TLS (default) or explicitly no encryption"],
         ["port PORT", "Defaults: 8883 for connect; 1883 for none"],
      ],
      examples => "  mcp-mqtt --name home login server localhost user '' tls none\n"
         . "  mcp-mqtt --name home login tls none\n"
         . "  mcp-mqtt --name home --stdio",
   },
   "event-filter=s@" => \my @event_filters,
   "allow-http"      => \my $allow_http,
   "event-profile=s" => \$profile,
;
$profile =~ /\A(?:auto|openai|beta)\z/ or die "Invalid event profile\n";

my $name = $options->{name};
my $directory = File::Basename::dirname (AnyEvent::MCP::Config::_file ());
my $file = "$directory/mqtt-$name.ini";
my $account;
my $endpoint;
my $scalar_json = AnyEvent::MCP::json->canonical->allow_nonref;

sub load_account {
   return {} unless -e $file;
   open my $fh, "<:raw", $file or die "$file: $!\n";
   my @stat = stat $fh;
   -f _ && $stat[4] == $> && !($stat[2] & 0077)
      or die "$file: account file must be private and owned by current user\n";
   my $sections = AnyEvent::MCP::Config::parse_ini (AnyEvent::MCP::file_load ($file, $fh), $file);
   for (@$sections) {
      $_->[0] eq "" || $_->[0] eq "account" or die "$file: unexpected section $_->[0]\n";
   }
   AnyEvent::MCP::Config::merge_sections ($sections, "account")->{account} || {}
}

sub utf8_bytes {
   my ($s) = @_;
   defined $s && !ref $s or die "Expected string\n";
   Encode::encode ("UTF-8", $s, Encode::FB_CROAK () | Encode::LEAVE_SRC ())
}

sub base64_bytes {
   my ($s) = @_;
   defined $s && !ref $s && $s =~ /\A[A-Za-z0-9+\/]*={0,2}\z/
      or die "Invalid base64\n";
   my $b = MIME::Base64::decode_base64 $s;
   MIME::Base64::encode_base64 ($b, "") eq $s or die "Invalid base64\n";
   $b
}

sub settings {
   my ($kv) = @_;

   $kv->{server} =~ /\A[^\s\x00-\x1f]{1,255}\z/ or die "Missing or invalid server; run mcp-mqtt login\n";
   $kv->{tls} =~ /\A(?:connect|none)\z/ or die "Expected tls connect or none\n";
   $kv->{port} =~ /\A[0-9]+\z/ && $kv->{port} >= 1 && $kv->{port} <= 65535 or die "Invalid port\n";
   defined $kv->{user} && $kv->{user} !~ /[\x00\r\n]/ or die "Invalid user\n";

   my %connection = (
      host => $kv->{server}, port => $kv->{port} * 1, tls => $kv->{tls} eq "connect",
   );
   if (length $kv->{user}) {
      $connection{user_name} = utf8_bytes $kv->{user};
      $connection{password} = base64_bytes $kv->{"password-base64"};
      length $connection{user_name} <= 65535 && length $connection{password} <= 65535
         or die "MQTT credentials too long\n";
   }

   \%connection
}

sub mqtt_client {
   my ($on_message, $on_error) = @_;

   AnyEvent::MCP::MQTT->new (
      %$account,
      client_id        => "aemcp" . unpack ("H*", AnyEvent::MCP::random_bytes (8)),
      clean_session    => 1,
      keep_alive_timer => 60,
      timeout          => 10,
      handle_args      => [
         rbuf_max => 2 * 1024 * 1024,
         ($account->{tls} ? (tls_ctx => { verify => 1, verify_peername => "https" }) : ()),
      ],
      on_message => $on_message,
      on_error   => $on_error,
   )
}

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(?:server|port|user|tls)\z/ or die "Unknown login key '$key'; passwords cannot be passed on argv\n";
      $input{$key} = AnyEvent::MCP::utf8dec $value;
   }

   my $old = load_account;
   my %kv = (%$old, %input);
   delete $kv{port} if exists $input{tls} && !exists $input{port} && $old->{tls} ne $input{tls};
   for my $key (qw(server user)) {
      next if exists $kv{$key};
      print STDERR "$key: ";
      defined (my $value = <STDIN>) or die "No $key supplied\n";
      $value =~ s/\r?\n\z//;
      $kv{$key} = AnyEvent::MCP::utf8dec $value;
   }
   $kv{tls} ||= "connect";
   $kv{port} ||= $kv{tls} eq "connect" ? 8883 : 1883;
   delete $kv{"password-base64"};

   if (length $kv{user}) {
      require Term::ReadKey;
      open my $tty, "+<", "/dev/tty" or die "Password requires a controlling terminal: $!\n";
      $tty->autoflush (1);
      my $password = eval {
         local $SIG{INT} = local $SIG{TERM} = sub { die "Login interrupted\n" };
         Term::ReadKey::ReadMode ("noecho", $tty);
         print {$tty} "MQTT password for $kv{user}\@$kv{server}: ";
         scalar <$tty>
      };
      my $error = $@;
      Term::ReadKey::ReadMode ("restore", $tty);
      print {$tty} "\n";
      close $tty;
      die $error if length $error;
      defined $password or die "No password supplied\n";
      $password =~ s/\r?\n\z//;
      $kv{"password-base64"} = MIME::Base64::encode_base64 ($password, "");
   }

   $account = settings \%kv;
   my $cv = AE::cv;
   my $client = mqtt_client undef, sub { $cv->send ($_[1]) unless $cv->ready };
   my $timer = AE::timer 10, 0, sub { $cv->send ("MQTT connection timed out") unless $cv->ready };
   $client->connect->cb (sub { $cv->send (undef) unless $cv->ready });
   my $error = $cv->recv;
   $client->cleanup;
   die "$error\n" if defined $error;

   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 MQTT account '$name' in $file\n";
}

if (@ARGV && $ARGV[0] eq "login") {
   shift @ARGV;
   login;
   exit;
}
@ARGV and die "Unexpected arguments (try 'login')\n";

sub schema {
   my ($required, %properties) = @_;
   { type => "object", required => $required, properties => \%properties, additionalProperties => \0 }
}

sub args_only {
   my ($args, @allowed) = @_;
   ref $args eq "HASH" or die "Expected object\n";
   my %allowed = map { $_ => 1 } @allowed;
   !grep !$allowed{$_}, keys %$args or die "Unknown argument\n";
}

sub number {
   my ($v, $min, $max, $integer) = @_;
   defined $v && !ref $v && $v =~ /\A[0-9]+(?:\.[0-9]+)?\z/
      && $v >= $min && $v <= $max && (!$integer || $v == int $v) or die "Invalid number (expected $min..$max)\n";
   $v * 1
}

sub boolean {
   Types::Serialiser::is_bool ($_[0]) or die "Expected boolean\n";
   $_[0] ? 1 : 0
}

sub topic {
   my ($s, $filter) = @_;

   my $bytes = utf8_bytes $s;
   length $bytes && length $bytes <= 65535 && $s !~ /\x00/
      or die "Invalid MQTT topic\n";
   if ($filter) {
      my @level = split m{/}, $s, -1;
      for my $i (0..$#level) {
         $level[$i] !~ /[+#]/ || $level[$i] eq "+" || $level[$i] eq "#" && $i == $#level
            or die "Invalid MQTT topic filter\n";
      }
      $s !~ m{\A\$share/} or die "Shared subscriptions not supported\n";
   } else {
      $s !~ /[+#]/ or die "Expected exact MQTT topic\n";
   }

   $bytes
}

sub topic_matches {
   my ($filter, $topic) = @_;

   return if $topic =~ /^\$/ && $filter =~ /^[+#]/;
   my @topic = split m{/}, $topic, -1;
   for my $level (split m{/}, $filter, -1) {
      return 1 if $level eq "#";
      return unless @topic;
      my $part = shift @topic;
      return unless $level eq "+" || $level eq $part;
   }
   !@topic
}

sub match_settings {
   my ($args) = @_;

   my %match;
   if (exists $args->{payload_equals}) {
      length (utf8_bytes $args->{payload_equals}) <= 65536 or die "Payload match too long\n";
      $match{payload_equals} = $args->{payload_equals};
   }
   if (exists $args->{json_match}) {
      my $m = $args->{json_match};
      ref $m eq "HASH" && keys %$m <= 16 or die "Expected JSON field match object (up to 16 fields)\n";
      for my $v (values %$m) {
         !ref $v || Types::Serialiser::is_bool ($v) or die "JSON match values must be scalars\n";
      }
      length $json->encode ($m) <= 8192 or die "JSON match too large\n";
      $match{json_match} = $m;
   }
   \%match
}

sub payload_matches {
   my ($match, $bytes) = @_;

   return if exists $match->{payload_equals} && utf8_bytes ($match->{payload_equals}) ne $bytes;
   if (my $m = $match->{json_match}) {
      my $object = eval { AnyEvent::MCP::decode_json $bytes };
      return unless ref $object eq "HASH";
      for my $key (keys %$m) {
         return unless exists $object->{$key} && $scalar_json->encode ($object->{$key}) eq $scalar_json->encode ($m->{$key});
      }
   }
   1
}

sub message_record {
   my ($msg, $topic) = @_;

   my $bytes = $msg->message;
   my $text = eval { Encode::decode ("UTF-8", $bytes, Encode::FB_CROAK () | Encode::LEAVE_SRC ()) };
   {
      topic => $topic,
      received_at => Time::HiRes::time,
      qos    => $msg->qos,
      retain => $msg->retain ? \1 : \0,
      dup    => $msg->dup ? \1 : \0,
      (!defined $text ? (payload_base64 => MIME::Base64::encode_base64 ($bytes, "")) : (payload => $text)),
   }
}

sub publication {
   my ($args) = @_;

   args_only $args, qw(topic payload payload_base64 qos retain);
   (exists $args->{payload}) != (exists $args->{payload_base64})
      or die "Supply exactly one of payload or payload_base64\n";
   my $bytes = exists $args->{payload} ? utf8_bytes ($args->{payload}) : base64_bytes ($args->{payload_base64});
   length $bytes <= 1024 * 1024 or die "Payload too large\n";
   {
      topic   => (topic $args->{topic}, 0),
      message => $bytes,
      qos     => (number ($args->{qos} // 1, 0, 1, 1)),
      retain  => exists $args->{retain} ? boolean ($args->{retain}) : 0,
   }
}

sub permission {
   my ($req, $action, $topic, $context) = @_;

   $req->require_permission ({
      tool => $req->{tool},
      action => $action,
      dimensions => {
         endpoint => {
            label => "MQTT account", value => $endpoint,
            choices => [{ id => "account", label => $endpoint, match => $endpoint }],
         },
         topic => {
            label => "Topic or filter", value => $scalar_json->encode ($topic),
            choices => [
               { id => "exact", label => "This topic/filter: $topic", match => $scalar_json->encode ($topic) },
               { id => "all", label => "Any topic/filter", match => "^" },
            ],
         },
      },
      sandbox_grants => [],
      reason => "$action MQTT $topic",
      context => $context,
   });
}

sub publish_permission {
   my ($req, $args, $pub) = @_;

   my $key = exists $args->{payload} ? "payload" : "payload_base64";
   permission $req, ($pub->{retain} ? "publish-retained" : "publish"), $args->{topic}, {
      retain => $pub->{retain} ? \1 : \0, qos => $pub->{qos},
      bytes => length $pub->{message},
      $key => substr ($args->{$key}, 0, 2048),
      truncated => length ($args->{$key}) > 2048 ? \1 : \0,
   };
}

my $active;
# one transient session. Completion is deferred out of MQTT's receive
# callback, which may still have to send a PUBACK for the received packet.
sub operation {
   my ($req, $filter, $collect, $pub, $done) = @_;

   $active < 8 or die "Too many active MQTT operations\n";
   ++$active;
   my ($client, $timer, $completion, $finished, $subscribed, $receiving, $end);
   my $result = {};
   my @messages;
   my %seen;
   my $bytes = 0;
   $receiving = !$pub;
   $result->{publication} = "not-sent" if $pub;

   my $cleanup = sub {
      undef $timer;
      undef $completion;
      if ($client) {
         $client->cleanup;
         undef $client;
      }
      --$active;
   };
   my $finish = sub {
      my ($why, $error) = @_;
      return if $finished++;
      undef $timer;
      $result->{end} = $why;
      $result->{error} = $error if defined $error;
      $result->{$collect->{topics_only} ? "topics" : "messages"} = \@messages if defined $filter;
      $completion = AE::timer 0, 0, sub {
         $cleanup->();
         delete $req->{on_cancel};
         $done->($result) unless $req->{finished};
      };
   };
   $req->{on_cancel} = sub {
      $finished = 1;
      $cleanup->();
   };

   my $maybe_finish = sub {
      return if $finished || !$subscribed || !$end;
      return if $pub && $result->{publication} eq "unknown";
      $finish->($end);
   };
   my $timeout = sub {
      $finish->($end || "timeout", $pub && $result->{publication} eq "unknown" ? "Publication acknowledgment timed out" : undef);
   };
   my $send = sub {
      $receiving = 1;
      $result->{publication} = "unknown";
      my $cv = $client->publish (%$pub);
      $cv->cb (sub {
         return if $finished;
         $result->{publication} = $pub->{qos} ? "acknowledged" : "sent";
         $end = "published" unless defined $filter;
         $maybe_finish->();
      });
   };

   $timer = AE::timer 10, 0, sub { $finish->("error", "MQTT connection or subscription timed out") };
   my $ok = eval {
      $client = mqtt_client sub {
         my ($msg) = @_;
         return if $finished || !$receiving || $end || !defined $filter || $collect->{probe};
         my $t = eval { Encode::decode ("UTF-8", $msg->topic, Encode::FB_CROAK () | Encode::LEAVE_SRC ()) };
         return if $@ || !topic_matches ($filter, $t);
         return if $collect->{mode} eq "retained" && !$msg->retain || $collect->{mode} eq "live" && $msg->retain;
         return unless payload_matches $collect->{match}, $msg->message;
         return if $collect->{topics_only} && $seen{$t}++;

         my $item = $collect->{topics_only} ? $t : message_record ($msg, $t);
         my $size = 1 + length utf8_bytes ($scalar_json->encode ($item));
         if ($bytes + $size > $collect->{max_bytes}) {
            $end = "limit";
         } else {
            push @messages, $item;
            $bytes += $size;
            $end = "count" if @messages >= $collect->{count};
         }
         $maybe_finish->();
      }, sub {
         $finish->("error", $_[1]);
      };
      $client->connect->cb (sub {
         return if $finished;
         if (defined $filter) {
            $client->subscribe (topic => (topic $filter, 1), qos => 1, callback => sub { })->cb (sub {
               return if $finished;
               my $qos = $_[0]->recv;
               return $finish->("error", "MQTT subscription refused") unless defined $qos && $qos <= 1;
               $subscribed = 1;
               return $finish->("subscribed") if $collect->{probe};
               $timer = AE::timer $collect->{timeout}, 0, $timeout;
               $send->() if $pub;
               $maybe_finish->();
            });
         } else {
            $subscribed = 1;
            $timer = AE::timer 10, 0, $timeout;
            $send->();
         }
      });
      1
   };
   $finish->("error", "$@") unless $ok;
}

sub tool_result {
   my ($req, $result) = @_;

   $req->reply ({
      structuredContent => $result,
      content => [{ type => "text", text => AnyEvent::MCP::json->encode ($result) }],
      ($result->{error} ? (isError => \1) : ()),
   });
}

my $topic_schema = { type => "string", minLength => 1 };
my $timeout_schema = { type => "number", minimum => 0.05, maximum => 20 };
my %match_schema = (
   payload_equals => { type => "string" },
   json_match => { type => "object", description => "Match exact typed top-level JSON field values." },
);
my $publish_schema = schema (["topic"],
   topic => $topic_schema, payload => { type => "string" }, payload_base64 => { type => "string" },
   qos => { enum => [0, 1], default => 1 }, retain => { type => "boolean", default => \0 },
);

mcp_tool get => "Get retained message on one exact topic. Returns immediately when received, otherwise short timeout (default 0.5s).",
   (schema (["topic"], topic => $topic_schema, timeout => $timeout_schema)),
   readonly => 1,
   sub {
      my ($req, $args) = @_;
      args_only $args, qw(topic timeout);
      topic $args->{topic}, 0;
      my $timeout = number ($args->{timeout} // .5, .05, 20, 0);
      permission $req, "read", $args->{topic};
      operation $req, $args->{topic}, {
         mode => "retained", match => {}, count => 1, timeout => $timeout, max_bytes => 1024 * 1024,
      }, undef, sub {
         my ($result) = @_;
         $result->{message} = (delete $result->{messages})->[0];
         tool_result $req, $result;
      };
   },
;

mcp_tool publish => "Publish UTF-8 payload or payload_base64 bytes to exact topic. QoS 0 or 1 (default 1); retain false by default.",
   $publish_schema,
   sub {
      my ($req, $args) = @_;
      my $pub = publication $args;
      publish_permission $req, $args, $pub;
      operation $req, undef, undef, $pub, sub { tool_result $req, $_[0] };
   },
;

mcp_tool collect => "Collect matching MQTT messages. Retained survey by default; live/all modes. Optional publish: subscribe first, publish, collect live RPC responses. No topic enumeration/completeness guarantee.",
   (schema (["filter"],
      filter => $topic_schema,
      mode => { enum => [qw(retained live all)] },
      timeout => $timeout_schema,
      count => { type => "integer", minimum => 1, maximum => 1000 },
      max_bytes => { type => "integer", minimum => 256, maximum => 1048576 },
      topics_only => { type => "boolean" },
      publish => $publish_schema,
      %match_schema,
   )),
   sub {
      my ($req, $args) = @_;
      args_only $args, qw(filter mode timeout count max_bytes topics_only publish), keys %match_schema;
      topic $args->{filter}, 1;
      my $pub = exists $args->{publish} ? publication ($args->{publish}) : undef;
      my $mode = $args->{mode} // ($pub ? "live" : "retained");
      $mode =~ /\A(?:retained|live|all)\z/ && (!$pub || $mode eq "live") or die "Invalid mode (exchange requires live)\n";
      my $collect = {
         mode => $mode,
         timeout => (number ($args->{timeout} // ($pub ? 5 : 2), .05, 20, 0)),
         count => (number ($args->{count} // ($pub ? 1 : 1000), 1, 1000, 1)),
         max_bytes => (number ($args->{max_bytes} // 65536, 256, 1048576, 1)),
         topics_only => exists $args->{topics_only} ? boolean ($args->{topics_only}) : 0,
         match => (match_settings $args),
      };
      permission $req, "read", $args->{filter};
      publish_permission $req, $args->{publish}, $pub if $pub;
      operation $req, $args->{filter}, $collect, $pub, sub { tool_result $req, $_[0] };
   },
;

my %monitors;
my %allowed_filters = map { (AnyEvent::MCP::utf8dec $_) => 1 } @event_filters;
topic $_, 1 for keys %allowed_filters;
sub allowed_filter {
   !%allowed_filters || $allowed_filters{$_[0]}
}

sub monitor_start;
sub monitor_start {
   my ($filter, $mon) = @_;

   $mon->{client}->cleanup if $mon->{client};
   $mon->{status} = "connecting";
   $mon->{epoch} = random_id "";
   my $failed = sub {
      $mon->{status} = "offline";
      $mon->{error} = $_[0];
      my $delay = $mon->{delay} ||= 1;
      $mon->{delay} = $delay < 128 ? $delay * 2 : 300;
      $mon->{timer} = AE::timer $delay, 0, sub {
         undef $mon->{timer};
         monitor_start $filter, $mon;
      };
   };
   $mon->{client} = mqtt_client sub {
      my ($msg) = @_;
      return if $msg->retain || $mon->{status} eq "offline";
      my $topic = eval { Encode::decode ("UTF-8", $msg->topic, Encode::FB_CROAK () | Encode::LEAVE_SRC ()) };
      return if $@ || !topic_matches ($filter, $topic);
      my $record;
      for my $name (keys %$channels) {
         my $ch = $channels->{$name};
         next unless $ch && $ch->{filter} eq $filter && payload_matches ($ch->{match}, $msg->message);
         $record ||= { %{message_record ($msg, $topic)}, source_epoch => $mon->{epoch} };
         accept_event $name, $record;
      }
   }, sub { $failed->($_[1]) };
   $mon->{timer} = AE::timer 10, 0, sub {
      $mon->{client}->cleanup;
      $failed->("MQTT connection or subscription timed out");
   };
   $mon->{client}->connect->cb (sub {
      $mon->{client}->subscribe (topic => (topic $filter, 1), qos => 1, callback => sub { })->cb (sub {
         my $qos = $_[0]->recv;
         return $failed->("MQTT subscription refused") unless defined $qos && $qos <= 1;
         undef $mon->{timer};
         $mon->{status} = "online";
         delete @$mon{qw(error delay)};
      });
   });
}

my $sync_timer;
sub sync_monitors {
   undef $sync_timer;
   my %wanted = map { $channels->{$_}{filter} => 1 }
      grep { allowed_filter ($channels->{$_}{filter}) && live_subscriptions $_ } keys %$channels;

   for my $filter (keys %monitors) {
      next if $wanted{$filter};
      my $mon = delete $monitors{$filter};
      delete $mon->{timer};
      (delete $mon->{client})->cleanup;
   }
   for my $filter (keys %wanted) {
      next if $monitors{$filter};
      my $mon = $monitors{$filter} = {};
      monitor_start $filter, $mon;
   }
}

sub monitors_changed {
   $sync_timer = AE::timer 0, 0, \&sync_monitors;
}

sub event_arguments {
   my ($args) = @_;

   args_only $args, qw(filter policy interval durable), keys %match_schema;
   topic $args->{filter}, 1;
   my $policy = $args->{policy} // "immediate";
   $policy =~ /\A(?:immediate|throttle|debounce)\z/ or die "Invalid policy\n";
   my $durable = exists $args->{durable} ? boolean ($args->{durable}) : 0;
   my %normalized = (
      filter => $args->{filter}, policy => $policy, durable => $durable ? \1 : \0,
      %{match_settings $args},
   );
   if ($policy eq "immediate") {
      !exists $args->{interval} or die "Immediate policy takes no interval\n";
   } else {
      $normalized{interval} = number ($args->{interval}, .05, 2592000, 0);
   }
   \%normalized
}

sub mqtt_event {
   my ($req, $raw) = @_;
   my $args = eval { event_arguments $raw };
   return $req->rpc_error (-32602, "$@") if $@;
   my $filter = $args->{filter};
   my $channel = Digest::SHA::sha256_hex ($json->encode ($args));

   my $ch = {
      automatic => 1,
      filter => $filter, match => (match_settings $args),
      policy => $args->{policy}, interval => $args->{interval}, durable => $args->{durable} ? 1 : 0,
      description => "", producers => {},
      pending => [], batches => [], epoch => (random_id ""), next_seq => 0, dropped => 0,
   };

   if ($req->{method} eq "events/unsubscribe") {
      return event_subscription $req, $args, $channel, $ch;
   }
   allowed_filter $filter or return $req->rpc_error (-32602, "Event filter not authorized");
   return event_subscription $req, $args, $channel, $ch if $monitors{$filter} && $monitors{$filter}{status} eq "online";

   # confirm upstream subscription before creating a new webhook lease.
   # The durable monitor owns a separate session after verification.
   return $req->rpc_error (-32603, "Too many active MQTT operations") if $active >= 8;
   operation $req, $filter, { probe => 1, mode => "live", match => {}, count => 1, max_bytes => 0 },
      undef, sub {
         my ($result) = @_;
         return $req->rpc_error (-32603, $result->{error}) if $result->{error};
         event_subscription $req, $args, $channel, $ch;
      };
}

mcp_tool status => "Show MQTT endpoint, active operations and event filter connection state.",
   (schema ([])), readonly => 1,
   sub {
      my ($req, $args) = @_;
      args_only $args;
      $req->result ({
         endpoint => $endpoint, active => $active * 1, events => \1,
         monitors => [map {
            my $m = $monitors{$_};
            { filter => $_, status => $m->{status}, (exists $m->{error} ? (error => $m->{error}) : ()) }
         } sort keys %monitors],
      });
   },
;

mcp_event
   {
      name => "message",
      description => "Live MQTT messages matching a filter (retained replay excluded). Optional payload matching, immediate/throttle/debounce policy. Epoch/seq identify delivery gaps.",
      delivery => ["webhook"],
      inputSchema => (schema (["filter"], filter => $topic_schema, %match_schema,
         policy => { enum => [qw(immediate throttle debounce)] },
         interval => { type => "number", minimum => .05, maximum => 2592000 },
         durable => { type => "boolean" })),
      payloadSchema => {
         type => "object", required => [qw(filter epoch seq events)],
         properties => {
            filter => { type => "string" }, epoch => { type => "string" },
            seq => { type => "integer" }, events => { type => "array", items => { type => "object" } },
         },
      },
   },
   subscribe => \&mqtt_event,
   unsubscribe => \&mqtt_event,
;
mcp_tool subscription_list => "List active MQTT event subscriptions, filters, expiry and queued notifications.",
   (schema ([])), readonly => 1,
   sub {
      my ($req, $args) = @_;
      args_only $args;
      my @list;
      for my $id (sort keys %$subscriptions) {
         my $sub = $subscriptions->{$id};
         next if $sub->{expires} <= time;
         my $ch = $channels->{$sub->{channel}};
         push @list, {
            id => $id, filter => $ch->{filter}, policy => $ch->{policy},
            expires => (timestamp $sub->{expires}),
            queued => scalar grep exists $_->{targets}{$id}, @{$ch->{batches}},
         };
      }
      $req->result ({ subscriptions => \@list });
   },
;
mcp_tool subscription_revoke => "Revoke an MQTT event subscription by ID and discard its queued deliveries.",
   (schema (["id"], id => { type => "string" })),
   sub {
      my ($req, $args) = @_;
      args_only $args, "id";
      defined $args->{id} && !ref $args->{id} or die "Expected subscription ID\n";
      my $deleted = exists $subscriptions->{$args->{id}} || exists $verification{$args->{id}};
      save_state if drop_subscription $args->{id};
      monitors_changed;
      kick;
      $req->result ({ deleted => $deleted ? \1 : \0 });
   },
;

mcp_permissions +AnyEvent::MCP::Server::Permissions->new (name => "mqtt-$name");
mcp_config
   server_name => "mcp-mqtt",
   server_version => $AnyEvent::MCP::VERSION,
   idle_exit => 300,
   on_idle_shutdown => sub { !grep $_->{expires} > time, values %$subscriptions },
   short_instructions => "MQTT retained get, bounded topic/traffic collection, subscribe-publish-response exchange, publish and message events.",
   instructions => "get returns retained state for one topic. collect surveys filters (topics_only, mode retained/live/all), or subscribes then publishes and waits for matching live replies. publish sends text or base64. Native message events are available on subscription.",
   event_profile => $profile,
   capabilities => { tools => {}, extensions => { "io.modelcontextprotocol/events" => {} } },
;
mcp_start %$options if $options->{tool_help};

my $kv = load_account;
$account = settings $kv;
$endpoint = $scalar_json->encode ([@$kv{qw(server port tls user)}]);
# Do not silently restore subscriptions to a different MQTT account.
my $state_file = "$directory/mqtt-events-$name-" . Digest::SHA::sha256_hex (utf8_bytes $endpoint) . ".json";
events_init $state_file, $allow_http, "message", \&monitors_changed;
load_state;
for my $id (keys %$subscriptions) {
   my $ch = $channels->{$subscriptions->{$id}{channel}};
   drop_subscription $id unless $ch && allowed_filter ($ch->{filter}) && $subscriptions->{$id}{expires} > time;
}
save_state;
sync_monitors;
kick;

mcp_start %$options;
