#!/opt/bin/perl

=head1 NAME

mcp-events - persistent HTTP-triggered MCP events

=head1 SYNOPSIS

   mcp-events --name events

   mcp-multibroker events --- mcp-events --name events --- --eager

=head1 DESCRIPTION

Use this server to wake an agent when something happens elsewhere. For
example, ask the agent to create a channel C<mail> with a 900-second
throttle, subscribe to it, and give you a producer command. Install that
command in a mail arrival hook. The agent can then examine the mailbox
instead of polling it.

Channels are created and administered through MCP tools. They exist
independently of subscriptions. There is one MCP event, C<signal>, taking
an argument C<channel>. With a multibroker, wrap the argument object under
the corresponding broker name. Creating channels does not change the
event catalog.

Each channel can have several independently revocable producer credentials.
C<producer-create> returns the URL, bearer token and a curl example. A
producer credential only authorizes triggering its channel, not subscribing
or administering the server. Use HTTPS or a trusted local connection to
protect the credential. For example:

   curl --fail -H 'Authorization: Bearer TOKEN' \
        -H 'Content-Type: application/json' \
        -d '{"mailbox":"INBOX"}' http://127.0.0.1:PORT/emit/mail

The producer interface accepts POST with a JSON object, or an empty body
(equivalent to C<{}>). HTTP 202 means accepted, not delivered: older input
may be discarded to make room. Wrong credentials or nonexistent channels
return 401. If there are no live subscribers, the server returns 409.
Too-large input returns 413, invalid JSON 400 and unsupported media type
415. Every accepted object is a separate event, even when identical to
another. Retrying an uncertain POST can cause duplicates. When signalling
from a hook, log notification failures rather than letting them fail the
underlying operation (e.g. delivery of a mail).

The listener is active also with stdio and reverse MCP connections. Until
the multibroker starts all children by default, use C<--eager>. The shared
C<--print-url> option prints MCP connection URLs, not producer credentials.

=head2 Delivery policies

The notification payload is
C<< {channel: NAME, epoch: ID, seq: NUMBER, events: [OBJECT, ...]} >>.
The array preserves arrival order, even for a single event. C<seq> is the
zero-based sequence number of its first object; the next contiguous
batch starts at C<seq + number of events>. A gap indicates missing input,
so a subscriber can rescan the authoritative source. A changed C<epoch>
means a new sequence (e.g. after recreating a channel or restarting a
volatile one). The first batch after subscribing need not start at zero.
Rejected POSTs do not consume sequence numbers. The MCP event envelope
carries the notification ID and timestamp. Older queued notifications
may lack C<epoch> and C<seq>; their payloads are not changed on upgrade.

=over

=item immediate

Each event forms a notification immediately. No interval.

=item throttle

Deliver the first event immediately if idle (no notification formed in the
last interval). Collect other arrivals within that leading window until
the interval ends. After a collected notification, the first suppressed
arrival starts a new full-length collection window. Further arrivals do
not extend the deadline. With interval 15 and arrivals at 0, 3, 10 and 16,
notifications form at 0, 15 and 31. There are no empty notifications.

=item debounce

Collect arrivals, resetting the timer to a full interval on each arrival.
Continuous arrivals can defer notification indefinitely.

=back

These policies govern notification formation, not when the network or
subscriber actually processes notifications. A delivery failure may delay
several notifications. Each subscription has at most one outstanding
request; later notifications wait for earlier ones. Failed requests are
retried with exponential backoff, capped at five minutes, until delivery,
overflow, expiration or administrative removal. There is no replay of formed
notifications to new subscriptions. Subscribers active when a batch forms
receive the whole batch, including objects received before they subscribed.

To bound resource use, the server accepts at most 64 channels, 32 producer
credentials per channel, and 64 subscriptions (including pending
verifications). Each channel holds at most 256 undelivered input objects,
512 KiB of queued JSON arrays and 240 KiB of JSON per batch. If the
current collection exceeds its own limits, discard its oldest objects.
Then discard the oldest formed batches until the channel fits its limits.
This does not change the collection deadline or revoke subscriptions.
An in-flight delivery of a discarded batch may still complete, but is
not retried. The limits bound queued payloads, not the actual process
memory including in-flight requests and data structures.

=head2 State and lifetime

State is stored in C<events-NAME.json> alongside the normal global.ini
configuration, with a separate process-lifetime lock. Do not run multiple
servers of the same name. The state contains private signing secrets; keep
the file private. Producer tokens are stored only as hashes. Channel
definitions and subscriptions are saved atomically before acknowledging
changes. The server refuses invalid state at startup and exits on save
failure. Do not edit state while the server is running.

For durable channels pending objects, collection deadlines, throttle state,
sequence numbers and undelivered notifications survive a process restart.
Acceptance is persisted before the HTTP reply. Volatile channels retain
only configuration and subscriptions on disk, not pending delivery work,
sequence numbers or timers. Atomic file replacement protects against
partial updates on process failure; it is not a guarantee against sudden
power loss.

Retained deliveries have stable event and message IDs across retries and,
for durable channels, restarts. A successful webhook response acknowledges
one subscriber. A crash before saving that acknowledgment can repeat the
delivery. Delivery is best effort with retries, not lossless or exactly
once. Overflow can discard previously accepted events; a stalled
subscriber cannot prevent future input from being accepted.
Expiring, revoking or deleting subscriptions ends delivery obligations.
When the last subscriber disappears, pending input is discarded as well.
There is no historical event archive.

Subscriptions honor the requested lifetime up to 24 hours (also the default).
Refresh retains the ID; unchanged live credentials need not be verified
again. Administrative revocation does not prevent a client from subscribing
again. Delete the channel or remove the client's MCP access to prevent that.

All authenticated MCP clients of the instance are trusted administrators.
Do not expose the MCP endpoint to untrusted clients. Subscription authority
includes choice of HTTPS callback destination, including private addresses.
TLS is verified and redirects are disabled. This deliberately does not
implement the public-address restriction of the MCP Events guides.

=head1 TOOLS

=over

=item channel-list

List channels, policies, producer IDs/labels, pending object counts,
active subscription counts and C<dropped> (objects discarded on overflow
in the current epoch, counted once even if multiple recipients were
affected). Optional C<channel> filter.

=item channel-create

Create C<channel> with optional C<description>, C<policy> (default immediate),
C<interval> (positive seconds, up to 30 days, required for throttle or
debounce), and C<durable> (default false). Names start with an ASCII
alphanumeric or underscore, followed by at most 127 such characters,
dots or hyphens. Creation does not issue a producer token.

=item channel-update

Update any of the configuration fields of an existing channel. Policy,
interval and durability changes require an empty queue. Changing to
immediate removes the interval. Renaming is not supported.

=item channel-delete

Delete a channel, all its credentials, subscriptions and pending work.

=item producer-create

Create a new producer credential for C<channel> with an optional C<label>.
Returns C<id>, C<token>, C<url> and C<curl>. The token cannot be recovered
later; issue a new one if lost. Existing credentials remain valid.

=item producer-revoke

Revoke a producer credential by C<channel> and C<id>. Does not cancel
previously accepted events.

=item subscription-list

List active subscriptions, their channel, expiry and queued notification
count. Optional C<channel> filter. Does not return callback credentials
or URLs.

=item subscription-revoke

Remove a subscription by C<id>, cancelling outstanding and queued work
for that subscription. An already sent request cannot be recalled.

=back

=head1 OPTIONS

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

=over

=item --producer-origin ORIGIN

Advertise this HTTP(S) origin (scheme, host and optional port) in generated
producer URLs, for example when behind a reverse proxy. Defaults to the
configured listener URL without MCP authentication. With an ephemeral bind
port, specify an explicit origin.

=item --emit-socket PATH

Also accept authenticated producer HTTP requests at this absolute Unix
socket path in a private directory. The path must not exist.

=item --allow-http

Allow plain HTTP callbacks to literal loopback addresses for local testing.

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

Select webhook wire profile. Auto uses the old OpenAI profile for legacy MCP
and known OpenAI callbacks, except for explicitly advertised Beta support.
Other modern callers use Beta-style webhook IDs and errors. Experimental:
not a claim of complete Beta conformance.

=back

=cut

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

use Digest::SHA ();
use MIME::Base64 ();
use File::Basename ();
use File::Path ();
use Fcntl ();
use POSIX ();
use Time::HiRes ();

use AnyEvent ();
use AnyEvent::HTTP ();
use AnyEvent::Socket ();
use AnyEvent::MCP ();
use AnyEvent::MCP::Config ();
use AnyEvent::MCP::Server::HTTP ();
use AnyEvent::MCP::Server::Simple;
use AnyEvent::MCP::Server::Events qw(
   $json $channels $subscriptions %verification
   events_init random_id timestamp channel_valid equal_secret
   save_state load_state live_subscriptions drop_subscription kick
   event_subscription accept_event
);

my $profile = "auto";

my $options = mcp_getoptions
   {
      usage       => "Usage: mcp-events [OPTION]...\n",
      description => "Persistent HTTP-triggered events with MCP channel administration.",
      options     => [
         ["--producer-origin ORIGIN", "Advertise producer URL origin"],
         ["--emit-socket PATH", "Additional local HTTP producer socket"],
         ["--allow-http", "Allow loopback HTTP callbacks for testing"],
         ["--event-profile PROFILE", "auto, openai or beta"],
      ],
   },
   "producer-origin=s" => \my $origin,
   "emit-socket=s"     => \my $socket,
   "allow-http"       => \my $allow_http,
   "event-profile=s"  => \$profile,
;

@ARGV and die "Unexpected arguments\n";
$profile =~ /\A(?:auto|openai|beta)\z/ or die "Invalid event profile\n";
if (defined $origin) {
   $origin =~ s{/$}{};
   $origin =~ m{\Ahttps?://(?:[a-z0-9.-]+|\[[0-9a-f:.]+\])(?::[0-9]+)?\z}i
      or die "Expected HTTP(S) producer origin\n";
}

events_init
   File::Basename::dirname (AnyEvent::MCP::Config::_file ()) . "/events-$options->{name}.json",
   $allow_http, "signal";

my $channel_schema = { type => "string", pattern => '^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$' };
my $id_schema = { type => "string" };
my %configuration = (
   description => { type => "string", maxLength => 1024 },
   policy      => { type => "string", enum => [qw(immediate throttle debounce)] },
   interval    => { type => "number", exclusiveMinimum => 0, maximum => 2592000, description => "Seconds, for throttle/debounce" },
   durable     => { type => "boolean", description => "Persist pending events and unacknowledged deliveries" },
);

sub schema {
   my ($required, %properties) = @_;

   { type => "object", required => $required, properties => \%properties, additionalProperties => \0 }
}

mcp_event
   {
      name          => "signal",
      description   => "External signal on an existing named channel. Lossy on overflow; epoch and seq identify gaps. Use channel-list to discover channels; channel-create and producer-create to set up new ones.",
      delivery      => ["webhook"],
      inputSchema   => (schema (["channel"], channel => $channel_schema)),
      payloadSchema => {
         type       => "object",
         properties => {
            channel => { type => "string" },
            epoch   => { type => "string", description => "Changes when the sequence resets" },
            seq     => { type => "integer", minimum => 0, description => "Sequence number of the first input object" },
            events  => { type => "array", items => { type => "object" } },
         },
         required => ["channel", "events"],
      },
   },
   subscribe   => \&event_subscription,
   unsubscribe => \&event_subscription,
;

sub channel_name {
   channel_valid ($_[0]) or die "Invalid channel name\n";
   $_[0]
}

sub channel_get {
   $channels->{channel_name $_[0]} or die "Unknown channel\n"
}

sub args_only {
   my ($args, @allowed) = @_;

   my %allowed = map { $_ => 1 } @allowed;
   !grep !$allowed{$_}, keys %$args or die "Unknown argument\n";
}

sub configure_channel {
   my ($ch, $args) = @_;

   args_only $args, "channel", keys %configuration;
   my %new = (%$ch, map { exists $args->{$_} ? ($_ => $args->{$_}) : () } keys %configuration);
   defined $new{description} && !ref $new{description} && length $new{description} <= 1024
      or die "Invalid description\n";
   defined $new{policy} && !ref $new{policy} && $new{policy} =~ /\A(?:immediate|throttle|debounce)\z/
      or die "Invalid policy\n";

   if ($new{policy} eq "immediate") {
      !exists $args->{interval} or die "Immediate policy takes no interval\n";
      delete $new{interval};
   } else {
      defined $new{interval} && !ref $new{interval} && $new{interval} =~ /\A[0-9]+(?:\.[0-9]+)?\z/
         && $new{interval} > 0 && $new{interval} <= 2592000
         or die "Expected positive interval in seconds (maximum 30 days)\n";
      $new{interval} += 0;
   }

   if (exists $args->{durable}) {
      Types::Serialiser::is_bool ($args->{durable}) or die "Expected boolean durable\n";
      $new{durable} = $args->{durable} ? 1 : 0;
   }

   if ($ch->{policy} ne $new{policy} || $ch->{interval} != $new{interval} || $ch->{durable} != $new{durable}) {
      !@{$ch->{pending}} && !@{$ch->{batches}} or die "Channel has undelivered work\n";
      delete @new{qw(last leading)};
   }

   %$ch = %new;
}

sub channel_info {
   my ($name, $ch) = @_;

   {
      channel     => $name,
      description => $ch->{description},
      policy      => $ch->{policy},
      (defined $ch->{interval} ? (interval => $ch->{interval}) : ()),
      durable     => $ch->{durable} ? \1 : \0,
      pending     => scalar @{$ch->{pending}},
      queued      => scalar @{$ch->{batches}},
      dropped     => $ch->{dropped},
      subscriptions => scalar (live_subscriptions $name),
      producers   => [map { { id => $_, label => $ch->{producers}{$_}{label} } } sort keys %{$ch->{producers}}],
   }
}

mcp_tool channel_list => "List channels, policy, producers (IDs only), pending work, overflow drops and subscription counts. Optional channel filter.",
   (schema ([], channel => $channel_schema)),
   readonly => 1, idempotent => 1, closedworld => 1,
   sub {
      my ($req, $args) = @_;
      args_only $args, "channel";
      channel_get $args->{channel} if exists $args->{channel};
      $req->result ({ channels => [map channel_info ($_, $channels->{$_}),
         exists $args->{channel} ? ($args->{channel}) : sort keys %$channels] });
   },
;

mcp_tool channel_create => "Create channel definition. Policy immediate (default), throttle or debounce. Throttle/debounce require interval in seconds. Durable=false by default. Use producer-create to get a trigger credential.",
   (schema (["channel"], channel => $channel_schema, %configuration)),
   nondestructive => 1, closedworld => 1,
   sub {
      my ($req, $args) = @_;
      my $name = channel_name $args->{channel};
      !exists $channels->{$name} or die "Channel already exists\n";
      keys %$channels < 64 or die "Too many channels\n";
      my $ch = {
         description => "", policy => "immediate", durable => 0, producers => {},
         pending => [], batches => [], epoch => (random_id ""), next_seq => 0, dropped => 0,
      };
      configure_channel $ch, $args;
      $channels->{$name} = $ch;
      save_state;
      $req->result (channel_info $name, $ch);
   },
;

mcp_tool channel_update => "Change channel description, policy, interval or durability. Policy/interval/durability changes require no undelivered work.",
   (schema (["channel"], channel => $channel_schema, %configuration)),
   idempotent => 1, closedworld => 1,
   sub {
      my ($req, $args) = @_;
      my $ch = channel_get $args->{channel};
      configure_channel $ch, $args;
      save_state;
      $req->result (channel_info $args->{channel}, $ch);
   },
;

mcp_tool channel_delete => "Delete channel, all producer credentials, subscriptions and undelivered work.",
   (schema (["channel"], channel => $channel_schema)),
   idempotent => 1, closedworld => 1,
   sub {
      my ($req, $args) = @_;
      args_only $args, "channel";
      my $name = channel_name $args->{channel};
      drop_subscription $_ for grep $subscriptions->{$_}{channel} eq $name, keys %$subscriptions;
      drop_subscription $_ for grep $verification{$_}{channel} eq $name, keys %verification;
      my $deleted = delete $channels->{$name};
      save_state if $deleted;
      kick;
      $req->result ({ deleted => $deleted ? \1 : \0 });
   },
;

sub shell_quote {
   my ($text) = @_;

   $text =~ s/'/'"'"'/g;
   "'$text'"
}

mcp_tool producer_create => "Issue a new credential scoped to one channel. Returns token, URL and curl example. Store token securely; not recoverable. Other credentials stay valid.",
   (schema (["channel"], channel => $channel_schema, label => { type => "string", maxLength => 128 })),
   nondestructive => 1, closedworld => 1,
   sub {
      my ($req, $args) = @_;
      args_only $args, "channel", "label";
      my $ch = channel_get $args->{channel};
      my $label = $args->{label} // "";
      !ref $label && length $label <= 128 or die "Invalid label\n";
      keys %{$ch->{producers}} < 32 or die "Too many producer credentials\n";

      my $id = random_id "producer_";
      my $token = unpack "H*", AnyEvent::MCP::random_bytes (32);
      my $url = "$origin/emit/$args->{channel}";
      $ch->{producers}{$id} = { hash => (Digest::SHA::sha256_hex $token), label => $label };
      save_state;
      $req->result ({
         id    => $id,
         token => $token,
         url   => $url,
         curl  => "curl --fail -H 'Authorization: Bearer $token' -H 'Content-Type: application/json' -d '{}' " . shell_quote ($url),
      });
   },
;

mcp_tool producer_revoke => "Revoke producer credential by channel and ID. Already accepted events remain queued.",
   (schema (["channel", "id"], channel => $channel_schema, id => $id_schema)),
   idempotent => 1, closedworld => 1,
   sub {
      my ($req, $args) = @_;
      args_only $args, "channel", "id";
      my $ch = channel_get $args->{channel};
      defined $args->{id} && !ref $args->{id} or die "Expected producer ID\n";
      my $deleted = delete $ch->{producers}{$args->{id}};
      save_state if $deleted;
      $req->result ({ deleted => $deleted ? \1 : \0 });
   },
;

mcp_tool subscription_list => "List active subscription IDs, channels, expiration and queued notifications. Optional channel filter. No callback secrets or URLs.",
   (schema ([], channel => $channel_schema)),
   readonly => 1, idempotent => 1, closedworld => 1,
   sub {
      my ($req, $args) = @_;
      args_only $args, "channel";
      channel_get $args->{channel} if exists $args->{channel};
      my @list;
      for my $id (sort keys %$subscriptions) {
         my $sub = $subscriptions->{$id};
         next if $sub->{expires} <= time || exists $args->{channel} && $sub->{channel} ne $args->{channel};
         push @list, {
            id      => $id,
            channel => $sub->{channel},
            expires => (timestamp $sub->{expires}),
            queued  => scalar grep exists $_->{targets}{$id}, @{$channels->{$sub->{channel}}{batches}},
         };
      }
      $req->result ({ subscriptions => \@list });
   },
;

mcp_tool subscription_revoke => "Remove subscription by ID, cancel pending verification and discard its queued deliveries. Does not prevent later subscribe.",
   (schema (["id"], id => $id_schema)),
   idempotent => 1, closedworld => 1,
   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};
      kick;
      $req->result ({ deleted => $deleted ? \1 : \0 });
   },
;

sub producer_request {
   my ($server, $req, $reply) = @_;

   return 0 unless $req->{uri} =~ m{\A/emit/};
   if ($req->{method} ne "POST") {
      $reply->(405, "Method Not Allowed", {}, "");
      return 1;
   }

   my ($name) = $req->{uri} =~ m{\A/emit/([A-Za-z0-9_][A-Za-z0-9_.-]{0,127})\z};
   my ($token) = $req->{authorization} =~ /\ABearer ([0-9a-f]{64})\z/i;
   my $ch = defined $name ? $channels->{$name} : undef;
   unless ($ch && defined $token && grep equal_secret ($_->{hash}, Digest::SHA::sha256_hex ($token)), values %{$ch->{producers}}) {
      $reply->(401, "Unauthorized", {}, "");
      return 1;
   }

   if (length $req->{body} > 240 * 1024) {
      $reply->(413, "Payload Too Large", {}, "");
      return 1;
   }
   if (length $req->{body} && $req->{"content-type"} !~ m{\Aapplication/json(?:\s*;|\z)}i) {
      $reply->(415, "Unsupported Media Type", {}, "");
      return 1;
   }

   my $data = length $req->{body} ? eval { AnyEvent::MCP::decode_json $req->{body} } : {};
   unless (ref $data eq "HASH") {
      $reply->(400, "Expected JSON Object", {}, "");
      return 1;
   }
   if (length $json->encode ([$data]) > 240 * 1024) {
      $reply->(413, "Payload Too Large", {}, "");
      return 1;
   }

   unless (accept_event $name, $data) {
      $reply->(409, "No Active Subscribers", {}, "");
      return 1;
   }

   mcp_log "Accepted producer POST channel=$name";
   $reply->(202, "Accepted", {}, "{}");
   1
}

mcp_permissions undef;
mcp_config
   server_name        => "mcp-events",
   short_instructions => "Create/list persistent event channels, issue HTTP producer tokens, subscribe to signal(channel). Supports immediate, throttle and debounce delivery.",
   instructions       => "Create a channel and use producer-create to get a trigger URL and token. Subscribe to signal with channel argument. POST JSON objects using the producer bearer token. Queue overflow discards old events; use epoch and seq to detect gaps. Durable channels persist pending delivery work. Revoke subscriptions or producer tokens individually; channel-delete removes everything.",
   event_profile      => $profile,
   capabilities       => { tools => {}, extensions => { "io.modelcontextprotocol/events" => {} } },
   on_http_request    => \&producer_request,
;

# tool-help exits before opening state or starting listeners.
mcp_start %$options if $options->{tool_help};

unless (defined $origin) {
   my %http = AnyEvent::MCP::Config::global_config->http_settings ($options->{name}, $options->{bind});
   $origin = AnyEvent::MCP::Server::HTTP->new (%http, %$options, path => "/")->url (0);
   $origin =~ s{/$}{};
}

load_state;
kick;

my ($ingress, $listener);
if (defined $socket) {
   $socket =~ m{\A/} && !-e $socket && !-l $socket
      or die "Expected unused absolute Unix socket path\n";
   my ($dir) = $socket =~ m{\A(.*)/[^/]+\z};
   my @stat = stat $dir;
   @stat && -d _ && $stat[4] == $> && !($stat[2] & 0077)
      or die "Producer socket directory must be private and owned by the current user\n";

   $ingress = AnyEvent::MCP::Server::HTTP->new (
      auth => "none",
      on_http_request => sub {
         return 1 if producer_request @_;
         $_[2]->(404, "Not Found", {}, "");
         1
      },
   );

   my $umask = umask 0077;
   $listener = AnyEvent::Socket::tcp_server "unix/", $socket, sub { $ingress->accept ($_[0]) };
   umask $umask;
}

mcp_start %$options, listen => 1;
