PHP code example of packstub / agents

1. Go to this page and download the library: Download packstub/agents library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

packstub / agents example snippets


use Packstub\Agents\Facades\Agents;

public function boot(): void
{
    Agents::useAgent(\App\Ai\Agents\Assistant::class);
    Agents::useServer(\App\Mcp\Servers\AcmeServer::class);
    Agents::authorizeUsing(fn (string $ability) => auth()->user()->can($ability));
}

#[IsReadOnly]
#[Description('Find orders by number, customer, status and date.')]
class SearchOrders extends AgentTool
{
    protected ?string $ability = 'orders.view';

    protected function run(Request $request): array
    {
        $filters = AgentResources::normalizeFilters('orders', (array) $request->get('filters'));
        $query = AgentResources::apply('orders', Order::query(), $filters);

        return [
            'total' => $query->count(),
            'rows' => $query->limit($this->limit($request))->get()->map(fn (Order $o) => Orders::agentSummary($o))->all(),
        ];
    }

    public function schema(JsonSchema $schema): array
    {
        return [
            'filters' => $schema->object(AgentResources::filterSchema($schema, 'orders')),
            'limit' => $schema->integer(),
        ];
    }
}

class AcmeServer extends \Packstub\Agents\Mcp\AgentServer
{
    protected string $name = 'Acme';

    protected string $instructions = 'The back office of an online shop. Start with search-orders.';

    protected array $tools = [
        Tools\SearchOrders::class,
        \Packstub\Agents\Mcp\Tools\DrawChart::class,
        Tools\ConfirmOrder::class,
    ];
}

class Assistant extends Agent
{
    protected function persona(): string
    {
        return 'You are Ask Acme, the back-office assistant of an online shop.';
    }

    protected function domain(): string
    {
        return <<<'PROMPT'
        - Orders move from placed to paid to shipped; a cancelled order keeps its number.
        - Warehouse staff may confirm and ship; only managers may refund.
        PROMPT;
    }
}

$conversation = app(AgentConversationStore::class)->startConversation($user, $question);
$turn = app(AgentTurns::class)->enqueue($conversation, $user, ['prompt' => $question], null, 'auto', null); // model key, page context ("orders/12")

class Orders implements AgentResource
{
    public static function agentKey(): string { return 'orders'; }

    public static function agentSummary(Model $record, bool $full = false): array
    {
        return ['number' => $record->number, 'status' => $record->status, 'url' => route('orders.show', $record)];
    }

    public static function agentFilters(): array
    {
        return [
            Filter::text('query')->description('Order number or customer.')
                ->apply(fn (Builder $q, string $t) => $q->where('number', 'like', "%{$t}%")),
            Filter::enum('status', OrderStatus::class)->multiple()
                ->apply(fn (Builder $q, array $s) => $q->whereIn('status', $s)),
            Filter::date('placed_from')
                ->apply(fn (Builder $q, string $d) => $q->where('placed_at', '>=', $d)),
        ];
    }
}

$token = $user->createToken('laptop', ['read', 'tool:search-orders'], now()->addDays(30))->plainTextToken;

Agents::tenantModel(Team::class, slugAttribute: 'slug');
Agents::tenantUsing(fn () => auth()->user()?->currentTeam);
Agents::enteringTenant(function (Team $team) {
    tenancy()->initialize($team);

    return fn () => tenancy()->end();
});

Agents::useAgent(Assistant::class);                       // your Agent subclass
Agents::useServer(AcmeServer::class);                     // the MCP server class with the tool list
Agents::useTools([...]);                                  // or a plain tool list
Agents::addTools([...]);                                  // tools appended to the server's own list
Agents::useResources([Orders::class]);                    // the AgentResource classes
Agents::useMiddleware([AuditTurns::class]);               // your own agent middleware
Agents::authorizeUsing(fn (string $ability) => ...);      // how an ability is checked for the current person
Agents::roleLabelUsing(fn () => ...);                     // the person's role, for the prompt and refusals
Agents::credentialsUsing(fn () => new WorkspaceCredentials(...)); // a workspace's own provider key
Agents::limitsAuthorizeUsing(fn () => ...);               // who may edit the agent_limits rows
Agents::tenantUsing(fn () => ...);                        // the current workspace
bash
php artisan packstub-agents:tool SearchOrders --ability=orders.view
php artisan packstub-agents:tool ConfirmOrder --write --ability=orders.manage