AnyEvent-MCP

 view release on metacpan or  search on metacpan

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

C<< $req->progress ($progress, $total, $message) >> reports progress when
the client supplied a progress token. Delivery is best effort and may be
dropped by the transport; it does not complete the request.

=head1 METHODS

=over

=item $toolset = AnyEvent::MCP::Server::Toolset->new

Creates an empty tool registry.

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

Registers a tool named C<$name>. Underscores are converted to hyphens and
duplicate names are rejected.

C<$description> is stripped of surrounding whitespace and common indentation.
C<$input_schema> is a JSON Schema hash reference describing the arguments.

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

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

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

Registered tools are callbacks, not methods of the Toolset.

=item $definitions = $toolset->list

Returns the array reference of MCP tool definitions in registration order.
C<$definitions> contains no callbacks.

=item $toolset->call ($req)

Invokes the tool named by C<< $req->{tool} >> with C<$req> and
C<< $req->{args} >>. Sets C<< $req->{toolset} >> to this Toolset.

Unknown names and exceptions from the callback are left for the server to
handle.

=back

=cut

package AnyEvent::MCP::Server::Toolset;

use common::sense;
use AnyEvent::MCP ();

our @ISA = qw(AnyEvent::MCP::Base);

sub new {
   my $class = shift;

   $class->SUPER::new (tool => {}, list => [], @_)
}

sub tool {
   my ($self, $name, $description, $input_schema, $callback) = @_;

   $name =~ y/_/-/;

   !exists $self->{tool}{$name}
      or die "duplicate MCP tool '$name'\n";

   my $definition = {
      name        => $name,
      description => AnyEvent::MCP::_clean_text $description,
      inputSchema => $input_schema,
   };

   $self->{tool}{$name} = {
      definition => $definition,
      callback   => $callback,
   };

   push @{$self->{list}}, $definition;
}

sub list {
   $_[0]{list}
}

sub call {
   my ($self, $req) = @_;

   my $name = $req->{tool};

   my $tool = $self->{tool}{$name}
      or die "unknown MCP tool '$name'\n";

   $req->{toolset} = $self;
   $tool->{callback}->($req, $req->{args})
}

1



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