Skip to content

Writing Clarive API modules

The REST API (/api/v2), the MCP server (/mcp) and the clarive CLI all publish the operations declared in lib/Clarive/API/*.pm. A module declares what each operation takes and calls the existing models. Validation, permissions, read-only tokens, error handling and serialization happen once, in Clarive::API::Registry. An operation you add appears in all three.

A module

package Clarive::API::Widget;
use Moose;
use Clarive::API::Module;    # makes this a module and exports `api`

sub summary { 'Widgets: list them and polish them' }

api list => {
    summary => 'List widgets',
    params  => [
        query => { type => 'string', description => 'Words in the widget name' },
        __PACKAGE__->paging_params,
    ],
};

sub list {
    my ( $self, $ctx, $p ) = @_;
    my @rows = Baseliner::Model::Widgets->new->search( $p->{query} );
    return $self->paged( \@rows, skip => $p->{skip}, limit => $p->{limit} );
}

api polish => {
    summary     => 'Polish a widget',
    description => 'Takes a widget mid, as returned by widget.list.',
    kind        => 'write',
    permission  => 'action.widgets.polish',
    params      => [ mid => { type => 'string', required => 1 } ],
    positional  => ['mid'],
};

sub polish {
    my ( $self, $ctx, $p ) = @_;
    my $widget = $self->load_ci( $p->{mid}, 'Widget' );
    $widget->polish( username => $ctx->username );
    return { mid => $widget->mid, polished => \1 };
}

__PACKAGE__->meta->make_immutable;

1;

The namespace comes from the package name (Widget is widget; UserGroup would be user_group), or from api_namespace 'name'. Operations are widget.list and widget.polish, MCP tools widget_list and widget_polish, and CLI commands clarive widget list and clarive widget polish <mid>.

The spec

Key Meaning
summary One line, required
description What an agent needs to use it well: formats, where ids come from, side effects
kind read (default), write or destructive. Read tokens only call read operations
permission An action, a list of actions (any of them), 'root', or sub { my ($ctx, $p) = @_; ... }
params Ordered name => {...} pairs: type (string, integer, number, boolean, array, object, file, any), required, default, enum, minimum, maximum, items (for arrays), description
positional Params the CLI takes without a flag
returns_file The handler returns $self->file(...)
public Callable without a token (only auth.login is)
handler Another method name, when the op name clashes with a helper (file, paged...)
additional_params Accept params not listed
allow_read_only A read token may call it although it is not read (it only takes power away, like auth.logout)
no_oauth OAuth tokens (Copilot and other OAuth MCP clients) may not call it: for operations that make credentials, which would outlive the app's connection

The registry turns strings into numbers, booleans, arrays and objects (query strings and CLI flags are strings), applies defaults, refuses unknown params and lists every problem in one invalid_params error.

Handlers

A handler gets ($self, $ctx, $p) and runs as the caller: Baseliner->username is $ctx->username while it runs, so events and audit fields name the right user.

  • Call the models. Do not reimplement them.
  • No Catalyst $c. For models that take ($c, $user_ctx), pass $ctx->shim(%params) and $ctx->user_ctx.
  • Check per-object permissions with $ctx->check_action( $action, bounds => {...} ).
  • Throw with $self->not_found($what, $id), invalid, forbidden, conflict or failed. A model's _fail becomes a failed error, and a Perl crash an internal one.
  • Return plain data. Objects, MongoDB ids and dates are converted, and CI objects are masked (passwords, keys, password variables) with the hide string that updates ignore. Use $self->redact for other secret-bearing data.
  • A file param reaches the handler as { path, filename, size } and is never a path chosen by the client. Return files with $self->file( path => ... ) or $self->file( body => ..., filename => ... ).
  • Long tasks start and return an id. Give callers an operation they can poll.

Tests

Each module has a test in t/clarive/api/, named after the module (lib/Clarive/API/UserGroup.pm is t/clarive/api/user_group.t). Call operations through the registry so validation and permissions run:

my $ret = Clarive::API::Registry->call( 'widget.polish', { mid => $mid },
    Clarive::API::Context->new( username => 'foo', transport => 'test' ) );

Test the happy path, a user without the permission, and the not-found and invalid cases. t/clarive/api/registry.t checks that every module compiles and every operation is well formed.