AnyEvent-MCP
view release on metacpan or search on metacpan
bin/mcp-webbrowser view on Meta::CPAN
#!/opt/bin/perl
=encoding utf8
=head1 NAME
mcp-webbrowser - expose opted-in browser tabs to MCP
=head1 SYNOPSIS
mcp-webbrowser --stdio
mcp-webbrowser --print-url
mcp-webbrowser --stdio --bind 127.0.0.1:31741
mcp-webbrowser --connect http://host:port/TOKEN/browser
=head1 DESCRIPTION
The companion userscript lets you explicitly grant an MCP client access to
individual browser tabs. Only opted-in tabs connect to this broker over
WebSocket; MCP clients can then discover those tabs, execute JavaScript in
their page context and add DOM elements. Code can inspect or change the
page, including logged-in content and forms, and cause side effects. Treat
allowing a tab as giving the MCP client access to that page, not merely its
URL or title. The broker still applies its own MCP permission rules.
This executable is the broker, not a browser extension. The userscript
handles per-tab authorization and page execution. The broker cannot see
unapproved tabs merely because the userscript is installed.
The HTTP/WebSocket listener stays active alongside MCP stdio or an outgoing
C<--connect>. Listener configuration, token derivation and URL discovery follow
C<mcp-vim>. All enabled users authenticate ordinary MCP requests, but only
C<connect_user> (default C<default>) may attach browser WebSockets. Explicit
static tokens may still authenticate both connection types.
Keep the broker URL private. The userscript accepts the C<http://> URL printed
by C<mcp-webbrowser --print-url>, converts it to WebSocket internally and
appends its own opaque per-tab target ID.
=head1 USERSCRIPT INSTALLATION AND USE
The self-contained userscript is C<webbrowser/mcp-webbrowser.user.js> in the
AnyEvent::MCP source distribution. Installing the Perl distribution does
not install it in a browser. Install a userscript manager first; see the
L<ScriptCat installation guide|https://docs.scriptcat.org/en/docs/use/use/>.
B<ScriptCat on Chromium and Firefox has been tested> (Firefox 153 on Linux,
including page execution, DOM insertion and navigation). ScriptCat is available
for Chrome, Edge and Firefox. Tampermonkey
provides the required C<GM_getTab>/C<GM_saveTab> APIs and may work, but
has not been tested with this userscript. Other managers are unverified.
Install the source-distribution file through your userscript manager, or
open the published userscript URL in the browser and install it there:
https://dist.schmorp.de/mcp-webbrowser/1/mcp-webbrowser.user.js
The C</1/> is the major version of the private browser/broker protocol, not
the MCP protocol or Perl distribution version. The published script declares
that URL for installation and automatic updates; updates depend on the
userscript manager. The source file contains the entire userscript and
needs no external JavaScript import.
Start the broker (directly or through your MCP client/multibroker) and obtain
its listener URL with:
bin/mcp-webbrowser view on Meta::CPAN
For C<list_tab_operations>, a successful reply is an array of operation
descriptions; an empty array means no additional operations. The broker
wraps it as C<{operations: [...]}>. C<call_tab_operation> uses the usual
C<{value: ...}> reply. The distributed userscript currently offers no
additional operations and returns an empty list or an operation error.
Late replies after cancellation are ignored. State updates replace cached
metadata. Malformed messages close the connection with status 1002.
The initial hello has a 15-second deadline; a silent connection is closed.
The distributed userscript evaluates in the page's JavaScript world via an
injected script and returns serialized results through DOM events. Its
Navigation API listener is installed in that same world. The broker cannot
authenticate page-reported values or infer application-rendering readiness
from navigation success. The userscript retries disconnected WebSockets;
it has no event subscriptions or separate SPA revision counter.
=cut
use common::sense;
use JSON::XS ();
use Socket ();
use Scalar::Util qw(weaken);
use AnyEvent ();
use AnyEvent::Socket ();
use AnyEvent::Handle ();
use AnyEvent::WebSocket::Server ();
use AnyEvent::WebSocket::Message ();
use AnyEvent::MCP ();
use AnyEvent::MCP::Config ();
use AnyEvent::MCP::Server::HTTP ();
use AnyEvent::MCP::Server::JSONL ();
use AnyEvent::MCP::Server::Permissions ();
use AnyEvent::MCP::Server::Toolset ();
use AnyEvent::MCP::Server::Simple qw(mcp_getoptions mcp_tool_help mcp_log mcp_log_request);
my $options = mcp_getoptions
{
usage => "Usage: mcp-webbrowser [OPTION]...\n",
path => "/",
description => "Expose connected browser tabs to MCP; HTTP/WebSocket stays active with stdio or --connect.",
examples => " mcp-webbrowser --auto-allow '*,*' # all actions in opted-in tabs",
}
;
@ARGV and die "Unexpected arguments\n";
my $ask = delete $options->{ask};
my $name = $options->{name};
my $connect = $options->{connect};
my $stdio = $options->{stdio} || !defined $connect && $ENV{PERL_ANYEVENT_MCP_MULTIBROKER_PROTOCOL} eq "stdio";
!($stdio && defined $connect) or die "Cannot combine --stdio and --connect\n";
my $config = AnyEvent::MCP::Config::global_config ();
my %http = $config->http_settings ($name, $options->{bind});
$http{tokens} = $options->{tokens} if $options->{tokens};
$http{connect_tokens} = $options->{tokens} if $options->{tokens};
my %token = map { $_ => 1 } @{$http{connect_tokens}};
my $json = JSON::XS->new->utf8->max_depth (64);
my (%connections, %pages, %tabs);
my ($last_allowed, $marked);
my $done = AE::cv;
my $permissions = AnyEvent::MCP::Server::Permissions->new (
name => "webbrowser-$name",
actions => {
read => "List connected browser tabs and their reported metadata",
exec => "Execute JavaScript or tab operations in a connected browser page",
},
(defined $ask ? (ask => $ask) : ()),
auto_rules => [@{$options->{auto_rules} || []},
$config->auto_rules ($name)],
);
sub page_label {
my ($state) = @_;
my ($title, $url) = @{$state}{qw(title url)};
s/[\x00-\x1f\x7f]/ /g for $title, $url;
(length $title ? (substr $title, 0, 80) . " - " : "")
. (substr $url, 0, 160)
}
sub code_preview {
my ($code, $limit) = @_;
$limit //= 160;
my $short = substr $code, 0, $limit;
$short .= "..." if length $code > $limit;
$json->encode ($short)
}
sub url_preview {
my $url = shift;
$url =~ s/[?#].*//s;
$url =~ s{(://)[^/]*@}{$1};
$url =~ s/[\x00-\x1f\x7f]/ /g;
my $short = substr $url, 0, 64;
$short .= "..." if length $url > 64;
$json->encode ($short)
}
sub browser_origin {
my ($scheme, $authority) = $_[0] =~ m{\A(https?://)([^/?#]+)};
return "null" unless defined $authority;
$authority =~ s/.*@//;
$scheme . $authority
}
sub browser_state {
my ($state) = @_;
+{ %$state, origin => browser_origin ($state->{url}) }
}
sub permission {
my ($req, $action, $target, $code, $kind) = @_;
bin/mcp-webbrowser view on Meta::CPAN
}
} elsif ($type eq "navigated") {
@$packet == 3 && defined $packet->[1] && !ref $packet->[1]
&& $packet->[1] =~ /\A[1-9][0-9]*\z/ && valid_state ($packet->[2])
or die "Invalid navigation result\n";
my $entry = $page->{tab}{navigation};
if ($entry && $entry->{page} == $page && $entry->{id} == $packet->[1]
&& $entry->{phase} eq "proceed") {
$page->{state} = browser_state ($packet->[2]);
finish_navigation $page->{tab}, "same-document";
}
} elsif ($type eq "state") {
@$packet == 2 && valid_state ($packet->[1]) or die "Invalid browser state\n";
$page->{state} = browser_state ($packet->[1]);
} elsif ($type eq "allowed") {
@$packet == 1 or die "Invalid browser allowed event\n";
$last_allowed = $page->{target};
} elsif ($type eq "mark") {
@$packet == 2 && ($packet->[1] eq "0" || $packet->[1] eq "1")
or die "Invalid browser mark event\n";
if ($packet->[1]) {
$marked = $page->{target};
} elsif (defined $marked && $marked eq $page->{target}) {
undef $marked;
}
for my $other (values %pages) {
next if $other->{minor} < 2;
send_message $other, ["marked", defined $marked && $marked eq $other->{target}
? JSON::XS::true : JSON::XS::false];
}
} elsif ($type eq "quit") {
@$packet == 1 or die "Invalid browser quit\n";
close_page $page, 1000, "Page disconnected";
finish_tab $page->{tab}, "disabled"
if $page->{tab} && !$page->{tab}{navigation};
} else {
die "Unknown browser message\n";
}
}
sub accept_browser {
my ($fh) = @_;
my ($requested, $rejection);
my $reject = sub {
$rejection = shift;
die "Browser WebSocket handshake rejected\n";
};
my $ws = AnyEvent::WebSocket::Server->new (
max_payload_size => 16 * 1024 * 1024,
handshake => sub {
my ($req, $res) = @_;
my ($cookie, $target) = $req->{resource_name} =~ m{\A/([^/]+)/([^/?#]+)\z};
defined $cookie or $reject->("invalid path");
$token{$cookie} or $reject->("invalid token");
$target =~ /%(?![0-9a-fA-F]{2})/ and $reject->("invalid target");
$target =~ s/%([0-9a-fA-F]{2})/chr hex $1/ge;
utf8::decode $target or $reject->("invalid target");
length $target && $target !~ /\0/ or $reject->("invalid target");
$requested = $target;
$res
},
);
$ws->establish ($fh)->cb (sub {
my $conn = eval { $_[0]->recv };
unless ($conn) {
AE::log warn => $rejection
? "Browser WebSocket rejected: $rejection"
: "Browser WebSocket establishment failed: " . ($@ || "no connection");
return;
}
my $page = { conn => $conn, requested => $requested, pending => {}, rpcid => 0 };
$connections{$page+0} = $page;
weaken (my $weak = $page);
$conn->on (finish => sub { close_page $weak, 1000, "Page disconnected" if $weak });
$conn->on (each_message => sub {
return unless $weak && exists $connections{$weak+0};
my $ok = eval {
$_[1]->opcode == 1 or die "Browser messages must be text\n";
receive_message $weak, $json->decode ($_[1]->body);
1
};
unless ($ok) {
my $reason = $@;
AE::log warn => "Browser protocol error: $reason";
$reason =~ s/\n.*//s;
$reason =~ s/[^\x20-\x7e]/?/g;
close_page $weak, 1002, substr $reason, 0, 123;
}
});
$page->{hello_timer} = AE::timer 15, 0, sub {
close_page $weak, 1002, "Browser hello timed out" if $weak;
};
});
}
my $toolset = AnyEvent::MCP::Server::Toolset->new;
$toolset->tool (tabs => "List connected tabs; last_allowed identifies the last explicit Allow action, "
. "marked identifies the tab selected with Mark. Neither changes execution permissions.",
{ type => "object", properties => {}, additionalProperties => JSON::XS::false },
sub {
my ($req) = @_;
permission $req, "read";
AE::log debug => "webbrowser tabs";
$req->result ({ tabs => [map {
my $page = $pages{$_};
+{ %{$page->{state}}, target => $_, instance_id => $page->{instance_id},
revision => $page->{tab}{revision}*1,
last_allowed => defined $last_allowed && $last_allowed eq $_ ? JSON::XS::true : JSON::XS::false,
marked => defined $marked && $marked eq $_ ? JSON::XS::true : JSON::XS::false }
} sort keys %pages] });
},
);
$toolset->tool (execute => "Page JS: CODE becomes body of async () => CODE; supply CODE, not arrow-function wrapper. "
. "Example: ({title: document.title}); NOT async () => ({title: document.title}) (returns function, rejected). "
. "Single expression returns implicitly; { ... } body needs explicit return; await works. "
( run in 0.829 second using v1.01-cache-2.11-cpan-234fa220139 )