AnyEvent-MCP

 view release on metacpan or  search on metacpan

lib/AnyEvent/MCP/Server/Simple.pm  view on Meta::CPAN

      instructions => "Use echo to return the supplied text.";

   mcp_tool echo =>
      "Return the supplied text.",
      {
         type       => "object",
         properties => {
            text => {
               type      => "string",
               maxLength => 4096,
            },
         },
         required => ["text"],
      },
      sub {
         my ($req, $args) = @_;

         my $text = $args->{text};
         defined $text and !ref $text and length $text <= 4096
            or die "text must be a string of at most 4096 characters\n";

         $req->reply ({
            content => [{ type => "text", text => $text }],
         });
      };

   mcp_start %$options;

Use your installed Perl's explicit path in the shebang, or invoke the file
with C<perl> as in the commands below.

C<mcp_getoptions> parses the common server options and returns startup
settings. C<mcp_config> declares protocol metadata and instructions.
C<mcp_tool> registers a description, input schema and callback.
C<mcp_start> constructs the transport and runs AnyEvent until shutdown.
Register everything before starting: code after C<mcp_start> runs only
when the server stops.

The input schema tells the client what to supply. The server does B<not>
validate arguments against JSON Schema, so the callback checks the value it
actually uses. A missing text, array or object fails as a tool error.
The example allows an empty string.

C<$req> is an L<AnyEvent::MCP::Server::Request>; C<$args> is its argument
hash reference. Replying finishes the request. Merely returning from the
callback does not. You supply the MCP result, and the server supplies the
JSON-RPC envelope.

=head2 Start and call the server

Inspect the common options with:

   perl echo-mcp --help

For a client launching a local subprocess, configure:

   perl /absolute/path/to/echo-mcp --stdio

The client must launch the process itself. Stdin and stdout carry MCP,
so starting the program in a terminal and typing text at it is not a test
of the echo tool. Print diagnostics to stderr, not stdout.

You can make a first call without an AI client. Save this as C<try-echo>
in the same directory as C<echo-mcp>:

   use common::sense;
   use AnyEvent;
   use AnyEvent::MCP::Client::JSONL;

   my $client = AnyEvent::MCP::Client::JSONL->new (
      command => [$^X, "./echo-mcp", "--stdio"],
   );

   my $cv = AE::cv;

   $client->call (echo => { text => "hello" }, sub {
      $cv->send (@_);
   });

   my ($success, $result) = $cv->recv;
   $success
      or die "$result->{message}\n";
   !$result->{isError}
      or die "$result->{content}[0]{text}\n";

   print $result->{content}[0]{text}, "\n";

Run C<perl try-echo>. It prints:

   hello

The JSONL client starts the server, connects and negotiates the protocol on
first use. C<$^X> chooses the same Perl interpreter as the test client.
The condition variable keeps the event loop running until the reply arrives.
Keep C<$client> alive while its operations are outstanding.

There are two success checks. C<$success> means the JSON-RPC operation
completed successfully; a tool can still return C<isError> in that result.
This client expects our echo tool's text result. A general client must handle
other MCP content representations too.

To use HTTP, start the server in one terminal:

   perl echo-mcp --bind :31742

and retrieve its URL in another:

   perl echo-mcp --bind :31742 --print-url

Configure that URL in your MCP client and ask it to call echo with text
C<hello>. Both commands use instance C<echo-demo>, unless you override it
with C<--name>. Repeat the same listener overrides when printing the URL.
C<--print-url> prints the address and exits; it does not start a server.

For the small Perl client above, replace the JSONL import and constructor
with:

   use AnyEvent::MCP::Client::HTTP;

   my $client = AnyEvent::MCP::Client::HTTP->new (
      url => $ARGV[0],

lib/AnyEvent/MCP/Server/Simple.pm  view on Meta::CPAN

values. C<instructions> is treated as human-readable text and normalized.

Server and transport options are passed to the underlying objects.
Common options include:

=over

=item name => $instance

Local instance name used to select configuration and credentials. Independent
of the name reported to MCP clients.

=item server_name => $name

Advertised MCP server implementation name. Defaults to C<AnyEvent::MCP>.

=item server_version => $version

Advertised application version, not the MCP protocol revision. Accepts
an ordinary Perl version number; Simple stringifies it for MCP.
Defaults to the AnyEvent::MCP library version.

=item server_info => { name => $name, version => $version }

Raw MCP server identity, passed through unchanged to the underlying
server. Cannot be combined with C<server_name> or C<server_version>.

=item instructions => $text

Human-readable guidance for the client, normalized when configured.

=item short_instructions => $text

Optional condensed guidance for finding this server's tools. Used as the
advertised MCP instructions when C<auto_instructions> is enabled.

=item auto_instructions => $boolean

Enabled by default. Exposes full instructions through the generated
C<meta-instructions> tool while advertising the short instructions if set.
When short or custom instructions are provided, append a brief hint pointing
to the full tool description; otherwise advertise full instructions as before.
Disable to advertise full instructions and omit the generated tool.

=item custom_instructions => $text

Instance-specific purpose prepended to advertised instructions. Can also be
set through C<--custom-instructions> or C<custom_instructions> in the program
or instance section of the global INI configuration.

=item on_request => $callback->($server, $req)

Synchronous hook before each dispatch attempt. For example, refresh
database state here. This does not replace dispatch or receive a
completion callback, and permission retries can invoke it again.

=item on_start => $callback->($server)

Called after the transport is ready, before entering the event loop.
Use it for startup information or installing watchers. Stdout carries
protocol messages in stdio mode; print diagnostics to stderr.
The callback must not block.

=item idle_exit => $seconds

Optional positive idle time for spawned stdio servers. With a multibroker
advertising C<anyevent-mcp/multibroker> version 1, Simple requests shutdown
once no MCP requests have been active for that long. The broker can ignore
the request. An application may veto shutdown with C<on_idle_shutdown>;
Simple retries after the configured interval if it is declined. HTTP servers,
ordinary clients and servers without this option are unaffected.

=back

See L<AnyEvent::MCP::Server> for further protocol options and events.

=item mcp_permissions $object

Select the L<AnyEvent::MCP::Server::Permissions> object used by the Simple
starters. If never called (and no explicit C<permissions> option is supplied),
Simple creates one automatically, named from the program and selected instance.
C<mcp_permissions undef> explicitly disables the permission system:
tool callbacks calling C<require_permission> then fail instead of prompting.
Applications can still pass C<permissions> through C<mcp_config> or startup
arguments when needed.

The common C<--ask> option overrides the object's prompting mode, and CLI
automatic permission rules precede configured rules and rules originally
supplied with the object. Those rules are applied when starting the server,
not when C<mcp_permissions> is called. No permission object is created when
it is explicitly disabled.

=item mcp_tool $name, $description, $input_schema, $callback->($req, $args)

Registers a tool named C<$name> with C<$description> and the JSON Schema
hash reference C<$input_schema>. C<$description> is normalized like
C<instructions>.

C<$callback> receives an L<AnyEvent::MCP::Server::Request> object C<$req>
and its C<< $req->{args} >> hash reference as C<$args>, for convenience.

Tools complete the request with C<< $req->reply ($result) >>, or use
C<< $req->result ($data) >> and C<< $req->error ($message) >> for convenience.
Request context is available directly in
the hash, for example C<< $req->{tool} >> and C<< $req->{server} >>.

=item $server_options = mcp_getoptions ({ %settings }, @getopt_options)

Parse the switches documented in L</COMMON COMMAND-LINE OPTIONS> alongside
application-specific L<Getopt::Long> option specifications:

   my $verbose;
   my $options = mcp_getoptions (
      {
         usage => "Usage: $0 [OPTION]... WORKDIR\n",
         description => "Provide example tools through MCP.",
         option_heading => "Example options:",
         options => [
            ["--verbose", "Show additional diagnostics"],
         ],
         examples => "  $0 --stdio ./project",



( run in 0.655 second using v1.01-cache-2.11-cpan-60884a8df76 )