#!/opt/bin/perl

=head1 NAME

mcp-fritz - TR-064 and FRITZ!Box management and diagnostics

=head1 SYNOPSIS

   mcp-fritz --name home login server fritz.box user myuser
   mcp-fritz --name home --stdio
   mcp-fritz --name home --call-monitor --stdio
   mcp-fritz --name home --support-dir /var/local/fritz support-data
   mcp-fritz --name other --tr064-only login server router port 5543

=head1 DESCRIPTION

Discover TR-064 services and their SOAP actions from the device and invoke
them without constructing XML. See L<https://fritz.com/en/pages/interfaces>
for the action semantics and individual FRITZ! service documentation.

Configure an account with C<login> first. Credentials are stored privately
in C<fritz-NAME.ini> alongside the other AnyEvent::MCP configuration files.
They are not encrypted. Restart the server after changing the account.

=over

=item tr064-list

List services, or the actions and argument descriptions of a selected
service. Identify a service by its service type, service ID or control URL;
use the control URL if ambiguous. Descriptions are cached; C<refresh>
clears the cache.

=item tr064-call

Invoke a discovered action using its exact input argument names. Pass
strings or numbers (use 0/1 for UPnP booleans); output values are strings.
Arguments omitted from the object are omitted from the SOAP request, since
some FRITZ! actions have optional arguments not identified in their SCPD.

Known read actions have read permissions, other actions require invoke
permission. There is no automatic retry after an uncertain action outcome.

=item http

Make a bounded authenticated request to the configured router.
C<interface> selects C<tr064> (HTTP authentication), C<web> (automatically
maintained FRITZ! web SID), or C<plain> (no authentication, web port).
Default web, or tr064 with C<--tr064-only>. In generic mode only tr064 is
available. Supply an origin-relative path or a URL on the selected origin.
A URL returned by TR-064 may already contain a temporary URL SID; use the
appropriate interface, without web SID authentication. If the device
returns a different hostname for the same device, use its path and query.

Supply query, form or raw body and content type as appropriate. For
FRITZ!OS UI requests, C<referer> can specify the originating page path.
The form action in the HTML is not necessarily the actual request URL:
FRITZ!OS 8.25 intercepts legacy forms and posts them to C</data.lua>,
with C<oldpage> set to the original form action and C<xhr=1>.
Inspect the browser's actual requests or the UI JavaScript.

Each HTTP method is a separate permission action (C<GET>, C<POST>, C<PUT>,
C<DELETE>, C<HEAD>), like mcp-http. Even GET can have side effects.
Existing rules with C<action=http> no longer match. Permission details
show query parameters, form fields or the raw body, and request headers, before automatic
authentication. These details do not become rule constraints.
All complete HTTP responses return their status, content type, body and
C<location> (resolved to an absolute URL) if present, including redirects
and HTTP error responses.
Transport failures and response limit errors remain tool errors.
No automatic redirects, proxy or requests to unrelated origins.
The web SID is managed internally, and redacted from returned bodies
and redirect locations.
TR-064 actions can return temporary URL credentials in their results.

=item support-data

Generate and download a local support dump (extended by default), using
the FRITZ!OS support download form. Save a private timestamped file in the
operator-configured support directory. Start without C<id>; the tool returns
immediately with a job ID, status and received byte count. Poll with C<id>
until status is C<done> (path and size) or C<error>. Only one download runs
at a time; a new request during a download returns the existing job.
The latest job remains queryable until another starts or the server exits.
HTTP inactivity timeout 300 seconds, overall timeout 600 seconds.
The dump contains private configuration. This does not send data to AVM.
The form is undocumented and may differ between firmware versions.

=back

=head2 Login

After C<login>, specify any of the following key/value pairs. Omitted
settings reuse an existing account. A new account prompts for missing host
and user. Passwords are read without echo from the controlling terminal,
never supplied on argv.

=over

=item server HOST

Router hostname or address (bracketed IPv6 is supported). Default
C<fritz.box> if the prompt is left empty.

=item port PORT

TR-064 HTTP port. Defaults to 49000 (HTTP) or 49443 (HTTPS).

=item scheme http|https

TR-064 transport. Default http.

=item description PATH

Device description path on the TR-064 origin, default /tr64desc.xml.

=item user USER

Account name. May be empty on devices that do not require a username.

=item password prompt|keep|none

Read a new password interactively, keep the saved password, or use an
empty password. Defaults to keep when the server and user are unchanged
and a password is saved, otherwise prompt.

=item auth auto|digest|basic|none

TR-064 HTTP authentication, default auto (Digest or HTTPS Basic).
Basic authentication is only supported over HTTPS.

=item web-port PORT

FRITZ! web interface port. Default 80 or 443 for HTTPS.

=item web-scheme http|https

FRITZ! web interface transport. Default http.

=item verify-tls yes|no

Verify HTTPS certificates and hostnames (default yes). Explicitly choose
no for a self-signed router certificate if necessary. Neither HTTP nor
unverified HTTPS protects credentials against an active network attacker.

=item call-port PORT

Call monitor TCP port, default 1012.

=back

Login checks service discovery and, if available, DeviceInfo:GetInfo.
FRITZ mode also tests SID authentication. In generic mode a public
description/action may not actually require authentication, so a successful
probe does not guarantee access to protected actions.

=head2 Events

With C<--call-monitor>, the native MCP event C<call> supports C<kind>:
C<ring>, C<call> (outgoing), C<connect>, C<disconnect> or C<all> (default).
The FRITZ! call monitor is a separate TCP service, not TR-064. Enable it
on the box by dialing #96*5* on a registered phone (disable with #96*4*).
Events carry the raw local time, call ID and relevant telephone numbers;
a source epoch changes whenever the connection is re-established.

Only connect while subscriptions are active; reconnect on failure.
There is no replay of missed calls or call state on reconnect. Use
TR-064 call-list actions for history. Optional C<durable> persists
queued webhook deliveries, not the TCP stream. These events expose
telephone metadata and are preauthorized by the operator's opt-in;
use only a trusted instance. Start the multibroker child eagerly when
using events.

=head1 OPTIONS

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

=over

=item --tr064-only

Disable FRITZ! web SID, support data, and call monitor. Use configured
TR-064 origin and description on other devices. This implements the
SOAP/SCPD interface, not every TR-064 revision or SSDP discovery.

=item --support-dir PATH

Local directory for support dumps. Default fritz-support-NAME alongside
the account file. Also used by the direct C<support-data [normal|extended]>
command, which needs no MCP connection.

=item --call-monitor

Enable preauthorized call monitor events. Off by default.

=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

=cut

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

use Digest::SHA ();
use Encode ();
use MIME::Base64 ();
use File::Basename ();
use File::Path ();
use File::Spec ();
use File::Temp ();
use POSIX ();
use URI ();

use AnyEvent ();
use AnyEvent::Handle ();
use AnyEvent::Socket ();
use AnyEvent::MCP ();
use AnyEvent::MCP::Config ();
use AnyEvent::MCP::Fritz ();
use AnyEvent::MCP::Server::Permissions ();
use AnyEvent::MCP::Server::Simple;
use AnyEvent::MCP::Server::Events qw(
   $json $channels $subscriptions 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-fritz [OPTION]... [login [KEY VALUE]... | support-data [normal|extended]]",
      description => "Discover and invoke TR-064 actions, FRITZ!OS HTTP, support dumps and call events.",
      options => [
         ["--tr064-only", "Disable FRITZ-specific interfaces"],
         ["--support-dir PATH", "Local support dump directory"],
         ["--call-monitor", "Enable preauthorized call events"],
         ["--allow-http", "Allow loopback HTTP callbacks"],
         ["--event-profile PROFILE", "auto, openai or beta"],

         "Commands:",
         ["login [KEY VALUE]...", "Configure or update account; omitted settings reuse saved values"],
         ["support-data [normal|extended]", "Download support data locally (default extended)"],

         "Login keys (KEY VALUE, not --options):",
         ["server HOST", "Router hostname or address (prompts if missing; default fritz.box)"],
         ["user USER", "Router username (prompts if missing)"],
         ["password prompt|keep|none", "Prompt without echo, reuse saved password, or use empty password; never pass password itself"],
         ["port PORT", "TR-064 port (default 49000 for HTTP, 49443 for HTTPS)"],
         ["scheme http|https", "TR-064 transport (default http)"],
         ["description PATH", "TR-064 device description path (default /tr64desc.xml)"],
         ["auth auto|digest|basic|none", "TR-064 authentication (default auto; Basic requires HTTPS)"],
         ["web-port PORT", "Web interface port (default 80 for HTTP, 443 for HTTPS)"],
         ["web-scheme http|https", "Web interface transport (default http)"],
         ["verify-tls yes|no", "Verify HTTPS certificates and hostnames (default yes)"],
         ["call-port PORT", "Call monitor TCP port (default 1012)"],
      ],
      examples => "  mcp-fritz --name home login server fritz.box user myuser\n"
         . "  mcp-fritz --name home login password prompt\n"
         . "  mcp-fritz --name home --call-monitor --stdio\n"
         . "  mcp-fritz --name home --support-dir /tmp/fritz support-data\n"
         . "  mcp-fritz --name other --tr064-only login server router port 5543",
   },
   "tr064-only"      => \my $tr064_only,
   "support-dir=s"   => \my $support_dir,
   "call-monitor"    => \my $call_monitor,
   "allow-http"      => \my $allow_http,
   "event-profile=s" => \$profile,
;
$tr064_only && $call_monitor and die "--call-monitor requires FRITZ extensions\n";
$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/fritz-$name.ini";
$support_dir = File::Spec->rel2abs ($support_dir || "$directory/fritz-support-$name");

my ($client, $endpoint);
my $docs = "https://fritz.com/en/pages/interfaces";
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 port {
   $_[0] =~ /\A[0-9]+\z/ && $_[0] >= 1 && $_[0] <= 65535 or die "Invalid port\n";
   $_[0] * 1
}

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

   $kv->{server} =~ /\A(?:[a-zA-Z0-9._-]+|\[[a-fA-F0-9:.]+\])\z/ or die "Missing or invalid server; run mcp-fritz login\n";
   $kv->{scheme} =~ /\Ahttps?\z/ && $kv->{"web-scheme"} =~ /\Ahttps?\z/ or die "Invalid HTTP scheme\n";
   $kv->{auth} =~ /\A(?:auto|digest|basic|none)\z/ or die "Invalid authentication mode\n";
   $kv->{"verify-tls"} =~ /\A(?:yes|no)\z/ or die "Expected verify-tls yes or no\n";
   defined $kv->{user} && $kv->{user} !~ /[\x00-\x1f\x7f]/ or die "Invalid user\n";
   $kv->{description} =~ m{\A/[^/\x00-\x20#][^\x00-\x20#]*\z} or die "Expected description path\n";

   my $tr064 = "$kv->{scheme}://$kv->{server}:" . port ($kv->{port});
   my $web = "$kv->{'web-scheme'}://$kv->{server}:" . port ($kv->{"web-port"});
   my $password = MIME::Base64::decode_base64 $kv->{"password-base64"};
   MIME::Base64::encode_base64 ($password, "") eq $kv->{"password-base64"} or die "Invalid saved password\n";

   AnyEvent::MCP::Fritz->new (
      server => $kv->{server}, call_port => (port $kv->{"call-port"}),
      tr064 => $tr064, web => $web, description => "$tr064$kv->{description}",
      user => $kv->{user}, password => AnyEvent::MCP::utf8dec ($password),
      auth => $kv->{auth}, verify_tls => $kv->{"verify-tls"} eq "yes",
   )
}

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

   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} "FRITZ 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//;
   MIME::Base64::encode_base64 ($password, "")
}

# The CLI waits only outside the server's event loop.
sub wait_operation {
   my ($timeout, $start) = @_;

   my $cv = AE::cv;
   my $op = {};
   my $timer = AE::timer $timeout, 0, sub {
      delete $op->{http};
      $cv->send (undef, "Operation timed out") unless $cv->ready;
   };
   $start->($op, sub { $cv->send (@_) unless $cv->ready });
   my ($r, $err) = $cv->recv;
   die "$err\n" if defined $err;
   $r
}

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|scheme|description|user|password|auth|web-port|web-scheme|verify-tls|call-port)\z/
         or die "Unknown login key '$key'\n";
      $input{$key} = AnyEvent::MCP::utf8dec $value;
   }

   my $old = load_account;
   my %kv = (%$old, %input);
   for my $key (qw(server user)) {
      next if exists $kv{$key};
      print STDERR $key eq "server" ? "server [fritz.box]: " : "user: ";
      defined (my $value = <STDIN>) or die "No $key supplied\n";
      $value =~ s/\r?\n\z//;
      $kv{$key} = AnyEvent::MCP::utf8dec $value;
   }
   $kv{server} ||= "fritz.box";
   for my $pair ([scheme => "port"], ["web-scheme" => "web-port"]) {
      my ($scheme, $port) = @$pair;
      delete $kv{$port} if exists $input{$scheme} && !exists $input{$port} && $old->{$scheme} ne $input{$scheme};
      $kv{$scheme} ||= "http";
   }
   $kv{port}          ||= $kv{scheme} eq "https" ? 49443 : 49000;
   $kv{"web-port"}    ||= $kv{"web-scheme"} eq "https" ? 443 : 80;
   $kv{description}   ||= "/tr64desc.xml";
   $kv{auth}          ||= "auto";
   $kv{"verify-tls"}  ||= "yes";
   $kv{"call-port"}   ||= 1012;

   my $mode = delete $kv{password};
   $mode ||= exists $old->{"password-base64"} && $old->{server} eq $kv{server} && $old->{user} eq $kv{user} ? "keep"
          : $tr064_only && $kv{auth} eq "none" ? "none" : "prompt";
   $mode =~ /\A(?:prompt|keep|none)\z/ or die "password expects prompt, keep or none (never the password itself)\n";
   $kv{"password-base64"} = password_prompt \%kv if $mode eq "prompt";
   $kv{"password-base64"} = "" if $mode eq "none";
   exists $kv{"password-base64"} or die "No saved password\n";

   $client = settings \%kv;
   my $services = wait_operation 30, sub { $client->services (@_) };
   my ($info) = grep $_->{service_type} eq "urn:dslforum-org:service:DeviceInfo:1", @$services;
   if ($info) {
      my $actions = wait_operation 30, sub {
         my ($op, $cb) = @_;
         $client->actions ($op, $info, $cb);
      };
      if (my ($get) = grep $_->{name} eq "GetInfo", @$actions) {
         wait_operation 30, sub {
            my ($op, $cb) = @_;
            $client->invoke ($op, $info, $get, {}, $cb);
         };
      }
   }
   wait_operation 30, sub { $client->sid (@_) } unless $tr064_only;

   my $lock = AnyEvent::MCP::file_lock $file;
   AnyEvent::MCP::file_save $file, AnyEvent::MCP::Config::serialize_ini [["account", \%kv]];
   close $lock;
   print STDERR "Saved FRITZ account '$name' in $file (" . scalar (@$services) . " services)\n";
   print STDERR "Generic mode: public TR-064 probes do not prove credentials for protected actions.\n" if $tr064_only;
}

if (@ARGV && $ARGV[0] eq "login") {
   shift @ARGV;
   login;
   exit;
}

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 string {
   defined $_[0] && !ref $_[0] && length $_[0] <= 65536 or die "Expected string\n";
   $_[0]
}

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

sub fields {
   my ($arg) = @_;

   return {} unless defined $arg;
   ref $arg eq "HASH" or die "Expected parameter object\n";
   +{ map { $_ => (string $arg->{$_}) } keys %$arg }
}

sub permission {
   my ($req, $action, $operation, $details) = @_;

   $req->require_permission ({
      tool => $req->{tool},
      action => $action,
      dimensions => {
         endpoint => {
            label => "Router account", value => $endpoint,
            choices => [{ id => "account", label => $endpoint, match => $endpoint }],
         },
         operation => {
            label => "Router operation", value => $operation,
            choices => [
               { id => "exact", label => $operation, match => $operation },
               { id => "all", label => "Any operation of this kind", match => "^" },
            ],
         },
      },
      sandbox_grants => [],
      reason => "$action $operation",
      (defined $details ? (details => $details) : ()),
   });
}

sub tool_operation {
   my ($req, $timeout, $start) = @_;

   my $op = {};
   my $done = sub {
      my ($result, $error) = @_;
      delete @$op{qw(http timer)};
      delete $req->{on_cancel};
      return if $req->{finished};
      $result ||= {};
      $result->{error} = $error if defined $error;
      $req->reply ({
         structuredContent => $result,
         content => [{ type => "text", text => AnyEvent::MCP::json->encode ($result) }],
         (defined $error ? (isError => \1) : ()),
      });
   };
   $op->{timer} = AE::timer $timeout, 0, sub { $done->(undef, "Operation timed out; outcome may be unknown") };
   $req->{on_cancel} = sub { delete @$op{qw(http timer)} };
   eval { $start->($op, $done); 1 } or $done->(undef, "$@");
}

# Exact service/action pairs, not a heuristic on the action name.
my %readonly;
for my $s (
   [DeviceInfo => qw(GetInfo GetDeviceLog)],
   [WANIPConnection => qw(GetStatusInfo GetExternalIPAddress GetConnectionTypeInfo GetNATRSIPStatus GetGenericPortMappingEntry GetSpecificPortMappingEntry)],
   [WANPPPConnection => qw(GetStatusInfo GetExternalIPAddress GetConnectionTypeInfo)],
   [WANCommonInterfaceConfig => qw(GetCommonLinkProperties GetTotalBytesSent GetTotalBytesReceived GetTotalPacketsSent GetTotalPacketsReceived)],
   [WANDSLInterfaceConfig => qw(GetInfo GetStatisticsTotal)],
   [Hosts => qw(GetHostNumberOfEntries GetGenericHostEntry GetSpecificHostEntry)],
   ["X_AVM-DE_OnTel" => qw(GetCallList GetPhonebook GetPhonebookList)],
) {
   my ($type, @actions) = @$s;
   $readonly{"urn:dslforum-org:service:$type:1#$_"} = 1 for @actions;
}

my ($monitor_status, $monitor_error) = ("idle", undef);

mcp_tool tr064_list => "Discover TR-064 services or list a service's SOAP actions and ordered input/output argument types. Documentation: $docs",
   (schema ([], service => { type => "string" }, refresh => { type => "boolean" })), readonly => 1,
   sub {
      my ($req, $args) = @_;
      args_only $args, qw(service refresh);
      string $args->{service} if exists $args->{service};
      my $refresh = exists $args->{refresh} && boolean $args->{refresh};
      permission $req, "read", "TR-064 descriptions";
      delete @$client{qw(services actions)} if $refresh;
      tool_operation $req, 30, sub {
         my ($op, $done) = @_;
         $client->services ($op, sub {
            my ($list, $err) = @_;
            return $done->(undef, $err) if $err;
            unless (exists $args->{service}) {
               return $done->({
                  services => $list, documentation => $docs,
                  ($call_monitor ? (call_monitor => { status => $monitor_status, error => $monitor_error }) : ()),
               });
            }
            my $service = eval { AnyEvent::MCP::Fritz::find_service ($list, $args->{service}) };
            return $done->(undef, "$@") if $@;
            $client->actions ($op, $service, sub {
               my ($actions, $err) = @_;
               return $done->(undef, $err) if $err;
               $done->({ service => $service, actions => $actions, documentation => $docs });
            });
         });
      };
   },
;

mcp_tool tr064_call => "Invoke a discovered TR-064 action. Use exact service type/ID/control URL and input argument names from tr064-list. Outputs are strings. Unknown actions require invoke permission. No retry after uncertain outcome.",
   (schema ([qw(service action)], service => { type => "string" }, action => { type => "string" }, arguments => { type => "object" })),
   sub {
      my ($req, $args) = @_;
      args_only $args, qw(service action arguments);
      my $service_name = string $args->{service};
      my $action_name = string $args->{action};
      my $arguments = fields $args->{arguments};
      my $scope = "$service_name#$action_name";
      permission $req, ($readonly{$scope} ? "read" : "invoke"), $scope;
      tool_operation $req, 40, sub {
         my ($op, $done) = @_;
         $client->services ($op, sub {
            my ($list, $err) = @_;
            return $done->(undef, $err) if $err;
            my $service = eval { AnyEvent::MCP::Fritz::find_service ($list, $service_name) };
            return $done->(undef, "$@") if $@;
            $client->actions ($op, $service, sub {
               my ($actions, $err) = @_;
               return $done->(undef, $err) if $err;
               my ($action) = grep $_->{name} eq $action_name, @$actions;
               return $done->(undef, "Unknown action") unless $action;
               $client->invoke ($op, $service, $action, $arguments, sub {
                  my ($result, $err) = @_;
                  return $done->(undef, $err) if $err;
                  $done->({ outputs => $result });
               });
            });
         });
      };
   },
;

mcp_tool http => "Bounded HTTP request to configured router. Returns HTTP status and Location even for non-2xx; transport errors fail. No redirects. interface tr064 uses Digest/Basic, web maintains FRITZ SID, plain uses web origin without auth. Supply query/form or raw body, optional referer path.",
   (schema ([qw(method path)],
      method => { enum => [qw(GET POST PUT DELETE HEAD)] }, path => { type => "string" },
      interface => { enum => $tr064_only ? ["tr064"] : [qw(tr064 web plain)] },
      query => { type => "object" }, form => { type => "object" }, body => { type => "string" },
      content_type => { type => "string" }, referer => { type => "string" },
   )),
   sub {
      my ($req, $args) = @_;
      args_only $args, qw(method path interface query form body content_type referer);
      my $method = string $args->{method};
      $method =~ /\A(?:GET|POST|PUT|DELETE|HEAD)\z/ or die "Invalid method\n";
      my $interface = $args->{interface} // ($tr064_only ? "tr064" : "web");
      $interface =~ /\A(?:tr064|web|plain)\z/ && (!$tr064_only || $interface eq "tr064") or die "Invalid interface\n";
      !exists $args->{form} || !exists $args->{body} or die "Supply form or body, not both\n";
      my $base = $interface eq "tr064" ? $client->{tr064} : $client->{web};
      my $uri = URI->new (AnyEvent::MCP::Fritz::resolve_url ("$base/", (string $args->{path})));
      my $query = { $uri->query_form, %{fields $args->{query}} };
      my $form = exists $args->{form} ? fields ($args->{form}) : undef;
      my $body = exists $args->{body} ? AnyEvent::MCP::Fritz::bytes (string $args->{body}) : undef;
      my $referer = exists $args->{referer} ? AnyEvent::MCP::Fritz::resolve_url ("$base/", (string $args->{referer})) : undef;
      my $type = exists $args->{content_type} ? string ($args->{content_type}) : $form ? "application/x-www-form-urlencoded" : "text/plain; charset=utf-8";
      $type !~ /[\x00-\x1f\x7f]/ or die "Invalid content type\n";
      $uri->query (undef);
      # Do not put session credentials or argument values in permission rules.
      my $json = AnyEvent::MCP::json->canonical->pretty;
      my %headers = (
         (defined $form || defined $body ? ("content-type" => $type) : ()),
         (defined $referer ? (referer => $referer) : ()),
      );
      permission $req, $method, "$interface $method " . $uri->path, {
         (keys %$query ? ("View query parameters" => $json->encode ($query)) : ()),
         ($form ? ("View $method form" => $json->encode ($form))
                : defined $body ? ("View $method body" => $args->{body}) : ()),
         (keys %headers ? ("View request headers" => $json->encode (\%headers)) : ()),
      };
      tool_operation $req, 40, sub {
         my ($op, $done) = @_;
         my $send = sub {
            my ($sid, $err) = @_;
            return $done->(undef, $err) if $err;
            if ($sid) {
               delete $query->{sid};
               if ($form) {
                  $form->{sid} = $sid;
               } else {
                  $query->{sid} = $sid;
               }
               if ($referer) {
                  my $ref = URI->new ($referer);
                  my %q = ($ref->query_form, sid => $sid);
                  $ref->query_form (%q);
                  $referer = $ref->as_string;
               }
            }
            $uri->query_form (%$query) if keys %$query;
            $client->request ($op, $method, $uri->as_string, {
               auth => $interface eq "tr064",
               accept_status => 1,
               body => $form ? (AnyEvent::MCP::Fritz::form_data $form) : $body,
               headers => {
                  ($sid ? (authorization => "AVM-SID $sid") : ()),
                  (defined $form || defined $body ? ("content-type" => $type) : ()),
                  ($referer ? (referer => $referer) : ()),
               },
            }, sub {
               my ($r, $err) = @_;
               return $done->(undef, $err) unless $r;
               my $data = $r->{body};
               my $location = $r->{headers}{location};
               $data =~ s/\Q$sid\E/[SID]/g if $sid;
               $location =~ s/\Q$sid\E/[SID]/g if $sid && defined $location;
               my $text = eval { Encode::decode ("UTF-8", $data, Encode::FB_CROAK () | Encode::LEAVE_SRC ()) };
               $done->({
                  status => $r->{headers}{Status} * 1,
                  content_type => $r->{headers}{"content-type"},
                  (defined $location ? (location => $location) : ()),
                  (defined $text ? (body => $text) : (body_base64 => MIME::Base64::encode_base64 ($data, ""))),
               }, $err);
            });
         };
         $interface eq "web" ? $client->sid ($op, $send) : $send->(undef, undef);
      };
   },
;

sub download_support {
   my ($op, $extended, $done, $progress) = @_;

   $client->sid ($op, sub {
      my ($sid, $err) = @_;
      return $done->(undef, $err) if $err;
      my $boundary = "aemcp" . unpack ("H*", AnyEvent::MCP::random_bytes (16));
      my $body = "--$boundary\r\nContent-Disposition: form-data; name=\"sid\"\r\n\r\n$sid\r\n"
               . "--$boundary\r\nContent-Disposition: form-data; name=\"" . ($extended ? "SupportDataEnhanced" : "SupportData")
               . "\"\r\n\r\n\r\n--$boundary--\r\n";
      $client->request ($op, "POST", "$client->{web}/cgi-bin/firmwarecfg", {
         body => $body, timeout => 300, limit => 64 * 1024 * 1024,
         on_progress => $progress,
         headers => {
            "content-type" => "multipart/form-data; boundary=$boundary",
            referer => "$client->{web}/support.lua?sid=$sid",
         },
      }, sub {
         my ($r, $err) = @_;
         return $done->(undef, $err) if $err;
         $r->{body} =~ /\A(?:##### TITLE |Support Data\r?\n)/ or return $done->(undef, "Response is not a FRITZ support dump");
         my $result = eval {
            File::Path::mkpath ($support_dir, 0, 0700);
            my $stamp = POSIX::strftime "%Y%m%d-%H%M%S", localtime;
            my ($fh, $path) = File::Temp::tempfile ("fritz-support-$stamp-XXXXXX", DIR => $support_dir, SUFFIX => ".txt", UNLINK => 0);
            binmode $fh, ":raw";
            unless (print {$fh} $r->{body} and close $fh) {
               my $error = "$!";
               unlink $path;
               die "Writing support dump: $error\n";
            }
            { path => $path, bytes => length ($r->{body}), extended => $extended ? \1 : \0 }
         };
         $done->($result, $@ || undef);
      });
   });
}

my $support_job;

sub start_support {
   my ($extended) = @_;

   my $job = $support_job = {
      id => random_id ("support_"), status => "running", extended => $extended ? \1 : \0, bytes => 0,
   };
   my $started = AE::now;
   my $op = {};
   my $id = $job->{id};
   mcp_log "support-data $id started (" . ($extended ? "extended" : "normal") . ")";

   my $done = sub {
      my ($result, $error) = @_;
      delete @$op{qw(http timer progress)};
      $job->{elapsed} = int (AE::now - $started);
      if (defined $error) {
         $job->{status} = "error";
         $job->{error} = $error;
         mcp_log "support-data $id failed: $error";
      } else {
         %$job = (%$job, %$result, status => "done");
         mcp_log "support-data $id saved $job->{bytes} bytes in $job->{elapsed}s: $job->{path}";
      }
   };
   $op->{timer} = AE::timer 600, 0, sub { $done->(undef, "Support download timed out") };
   $op->{progress} = AE::timer 15, 15, sub {
      $job->{elapsed} = int (AE::now - $started);
      mcp_log "support-data $id: $job->{bytes} bytes after $job->{elapsed}s";
   };
   eval {
      download_support $op, $extended, $done, sub { $job->{bytes} = $_[0] };
      1
   } or $done->(undef, "$@");
}

unless ($tr064_only) {
   mcp_tool support_data => "Start a local FRITZ support dump (extended by default); returns job ID and status immediately. Poll with id for received bytes, status, and completed file path. One download at a time; no upload to vendor.",
      (schema ([], extended => { type => "boolean" }, id => { type => "string" })),
      sub {
         my ($req, $args) = @_;
         args_only $args, qw(extended id);
         my $extended = exists $args->{extended} ? boolean ($args->{extended}) : 1;
         permission $req, "diagnostic", "Download support data";
         if (exists $args->{id}) {
            !exists $args->{extended} or die "Poll with id only\n";
            $support_job && (string $args->{id}) eq $support_job->{id} or die "Unknown or expired support job ID\n";
         } elsif (!$support_job || $support_job->{status} ne "running") {
            start_support $extended;
         }
         $req->result ({ %$support_job });
      },
   ;
}

my ($monitor_connect, $monitor_handle, $monitor_retry, $monitor_sync, $monitor_epoch, $monitor_delay);

sub monitor_wanted {
   scalar grep { live_subscriptions $_ } keys %$channels
}

sub monitor_start;
sub monitor_failed {
   my ($error) = @_;

   undef $monitor_connect;
   if ($monitor_handle) {
      $monitor_handle->destroy;
      undef $monitor_handle;
   }
   $monitor_status = "offline";
   $monitor_error = $error;
   return unless monitor_wanted;
   my $delay = $monitor_delay ||= 1;
   $monitor_delay = $delay < 128 ? $delay * 2 : 300;
   $monitor_retry = AE::timer $delay, 0, sub {
      undef $monitor_retry;
      monitor_start if monitor_wanted;
   };
}

sub monitor_start {
   $monitor_status = "connecting";
   $monitor_connect = AnyEvent::Socket::tcp_connect $client->{server}, $client->{call_port}, sub {
      my ($fh) = @_;
      undef $monitor_connect;
      return monitor_failed ("Call monitor connection failed: $!") unless $fh;
      $monitor_status = "online";
      undef $monitor_error;
      undef $monitor_delay;
      $monitor_epoch = random_id "";
      $monitor_handle = AnyEvent::Handle->new (
         fh => $fh, rbuf_max => 16384,
         on_error => sub { monitor_failed $_[2] },
         on_eof => sub { monitor_failed "Call monitor disconnected" },
         on_read => sub {
            my ($hdl) = @_;
            while ($hdl->{rbuf} =~ s/\A([^\n]*)\n//) {
               my $record = AnyEvent::MCP::Fritz::call_record $1 or next;
               $record->{source_epoch} = $monitor_epoch;
               $record->{received_at} = timestamp time;
               for my $name (keys %$channels) {
                  my $ch = $channels->{$name};
                  next unless $ch && ($ch->{kind} eq "all" || $ch->{kind} eq $record->{kind});
                  accept_event $name, $record;
               }
            }
         },
      );
   }, sub { 10 };
}

sub sync_monitor {
   undef $monitor_sync;
   if (monitor_wanted) {
      monitor_start unless $monitor_connect || $monitor_handle || $monitor_retry;
   } else {
      undef $monitor_connect;
      undef $monitor_retry;
      if ($monitor_handle) {
         $monitor_handle->destroy;
         undef $monitor_handle;
      }
      $monitor_status = "idle";
      undef $monitor_error;
      undef $monitor_delay;
   }
}

sub monitor_changed {
   $monitor_sync = AE::timer 0, 0, \&sync_monitor;
}

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

   my ($kind, $durable);
   eval {
      args_only $args, qw(kind durable);
      $kind = $args->{kind} // "all";
      $kind =~ /\A(?:all|ring|call|connect|disconnect)\z/ or die "Invalid call kind\n";
      $durable = exists $args->{durable} ? boolean ($args->{durable}) : 0;
      1
   } or return $req->rpc_error (-32602, "$@");

   my $channel = "call-$kind-$durable";
   my $normalized = { kind => $kind, durable => $durable ? \1 : \0 };
   event_subscription $req, $normalized, $channel, {
      automatic => 1, filter => $kind, kind => $kind, policy => "immediate", durable => $durable,
      description => "", producers => {},
      pending => [], batches => [], epoch => (random_id ""), next_seq => 0, dropped => 0,
   };
}

if ($call_monitor) {
   mcp_event
      {
         name => "call",
         description => "Real-time telephone call monitor: ring, call (outgoing), connect, disconnect, or all. Phone metadata; no replay after TCP reconnect.",
         delivery => ["webhook"],
         inputSchema => (schema ([], kind => { enum => [qw(all ring call connect disconnect)] }, 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 => \&call_event,
      unsubscribe => \&call_event,
   ;
}

mcp_permissions +AnyEvent::MCP::Server::Permissions->new (name => "fritz-$name");
mcp_config
   server_name => "mcp-fritz",
   server_version => $AnyEvent::MCP::VERSION,
   idle_exit => $call_monitor ? 0 : $tr064_only ? 300 : 900,
   short_instructions => "Discover and invoke TR-064 SOAP actions, authenticated router HTTP, optional FRITZ support data and real-time call events.",
   instructions => "Use tr064-list for services/action schemas, tr064-call for invocation. See $docs for semantics. http is restricted to configured router origins; FRITZ web SID is automatic. Support dumps stay local. Call events are opt-in.",
   event_profile => $profile,
   ($call_monitor ? (capabilities => { tools => {}, extensions => { "io.modelcontextprotocol/events" => {} } }) : ()),
;
mcp_start %$options if $options->{tool_help};

my $kv = load_account;
$client = settings $kv;
$endpoint = $scalar_json->encode ([@$kv{qw(server scheme port description web-scheme web-port user auth verify-tls call-port)}]);

if (@ARGV && $ARGV[0] eq "support-data") {
   shift @ARGV;
   !$tr064_only && @ARGV <= 1 && (!@ARGV || $ARGV[0] =~ /\A(?:normal|extended)\z/) or die "Invalid support-data command\n";
   my $result = wait_operation 600, sub {
      my ($op, $cb) = @_;
      download_support $op, (!@ARGV || $ARGV[0] eq "extended"), $cb;
   };
   print "$result->{path}\n";
   exit;
}
@ARGV and die "Unexpected arguments (try 'login')\n";

if ($call_monitor) {
   my $state_file = "$directory/fritz-events-$name-" . Digest::SHA::sha256_hex (AnyEvent::MCP::Fritz::bytes $endpoint) . ".json";
   events_init $state_file, $allow_http, "call", \&monitor_changed;
   load_state;
   for my $id (keys %$subscriptions) {
      my $ch = $channels->{$subscriptions->{$id}{channel}};
      drop_subscription $id unless $ch && $ch->{kind} =~ /\A(?:all|ring|call|connect|disconnect)\z/ && $subscriptions->{$id}{expires} > time;
   }
   save_state;
   sync_monitor;
   kick;
}

mcp_start %$options;
