> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Tools, permissions, commands, and UI

> Use SessionRpc in Laravel Copilot SDK to handle tools, permissions, commands, and UI requests.

## Tools, permissions, commands, and UI

Scope: SessionRpc (per-session operations tied to a Session)

For an overview of RPC and the list of all RPC pages, see [RPC](https://kawax.biz/en/packages/laravel-copilot-sdk/rpc.md).

```php theme={null}
// tools (protocol v3+: respond to external_tool.requested events)
// Initialize and validate the runtime tool set before sending (experimental, used for subagent sessions and similar)
$session->rpc()->tools()->initializeAndValidate();
// Returns an empty ToolsInitializeAndValidateResult

// Run a tool currently exposed to the session through the native call pipeline (experimental)
use Revolution\Copilot\Types\Rpc\ToolsExecuteRequest;

$result = $session->rpc()->tools()->execute(new ToolsExecuteRequest(
    name: 'search',
    arguments: ['query' => 'Laravel'],
    toolCallId: 'call-123', // Optional. Used to correlate with the call
));

if (is_string($result)) {
    // Simple text result
    echo $result;
} else {
    // ToolResultExpanded: textResultForLlm, resultType, newMessages,
    // mcpMeta, structuredContent, taskCompletionDecision, etc.
    echo $result->textResultForLlm;
    // resultType holds a ToolResultType or a string for unknown values
}

// Arrays also work. toolCallId can be omitted, and sessionId is overwritten with this session's value
$session->rpc()->tools()->execute([
    'name' => 'search',
    'arguments' => ['query' => 'Copilot'],
]);
// arguments: [] is sent as the JSON object {}, and scalars/null/non-empty arrays keep their JSON values

// execute() goes through the normal native tool call pipeline, so it doesn't bypass permission checks.
// If the tool requires approval, the onPermissionRequest handler in SessionConfig handles it as usual.
$session->rpc()->tools()->handlePendingToolCall(new HandlePendingToolCallRequest(
    requestId: '...',
    result: 'Tool execution result',
));
// Get the session's current tool metadata (experimental)
$session->rpc()->tools()->getCurrentMetadata();
// Fully replace the external tools provided by this connection (experimental)
$session->rpc()->tools()->set(['tools' => [
    ['name' => 'search', 'description' => 'Search documents', 'parameters' => ['type' => 'object']],
]]);
// Get the subagent settings applied to the current session (experimental)
$settings = $session->rpc()->tools()->getSubagentSettings();
// $settings->subagents is SubagentSettings, or null when there is no settings block
// Update subagent settings (experimental)
use Revolution\Copilot\Enums\SubagentSettingsEntryContextTier;
use Revolution\Copilot\Types\Rpc\SubagentSettings;
use Revolution\Copilot\Types\Rpc\SubagentSettingsEntry;
use Revolution\Copilot\Types\Rpc\UpdateSubagentSettingsRequest;

$result = $session->rpc()->tools()->updateSubagentSettings(new UpdateSubagentSettingsRequest(
    subagents: new SubagentSettings(agents: [
        'my-agent' => new SubagentSettingsEntry(
            contextTier: SubagentSettingsEntryContextTier::Default,
            model: 'gpt-5',
        ),
    ]),
));
// Applying the settings returns an empty ToolsUpdateSubagentSettingsResult

// permissions (protocol v3+: respond to permission.requested events)
use Revolution\Copilot\Types\Rpc\FolderTrustAddParams;
use Revolution\Copilot\Types\Rpc\PermissionLocationAddToolApprovalParams;
use Revolution\Copilot\Types\Rpc\PermissionLocationApplyParams;
use Revolution\Copilot\Types\Rpc\PermissionLocationResolveParams;
use Revolution\Copilot\Types\Rpc\PermissionsLocationsAddToolApprovalDetailsCommands;
use Revolution\Copilot\Types\Rpc\SessionPermissionsManagedReviewRequiredRequest;

$session->rpc()->permissions()->handlePendingPermissionRequest(new PermissionDecisionRequest(
    requestId: '...',
    result: PermissionDecision::approveOnce(),
));
// Automatically approve all permission requests in the session
$session->rpc()->permissions()->setApproveAll(new PermissionsSetApproveAllRequest(enabled: true));
// Set the permission mode (manual / assisted / allow-all)
$session->rpc()->permissions()->setMode(new PermissionsSetModeRequest(mode: PermissionMode::AllowAll));
// Get the current permission mode
$mode = $session->rpc()->permissions()->getMode();
// When you set permissionMode on session create or resume, get the applied result from the session
$result = $session->permissionModeResult();
// $result->success - Whether it was applied successfully
// $result->mode - The permission mode after it was applied
// Get the approval modes available under the current policy (experimental)
$capabilities = $session->rpc()->permissions()->getCapabilities();
// $capabilities->assistedApproval - Whether LLM-assisted approval is enabled
// $capabilities->bypassPermissions - Whether managed policy allows unconditional approval
// Get the active permission escalation and the startup baseline
$allowAll = $session->rpc()->permissions()->getAllowAll();
// $allowAll->active / $allowAll->baseline->tools
// Get whether permission request events are required
$required = $session->rpc()->permissions()->getRequired();
// Get whether managed policy requires review of the given permission request
$reviewRequired = $session->rpc()->permissions()->managedReviewRequired(
    new SessionPermissionsManagedReviewRequiredRequest(request: ['kind' => 'tool', 'toolName' => 'bash'])
);
// Get the additional directories included in the model context
$additionalDirectories = $session->rpc()->permissions()->additionalDirectories()->list();
// Reset session-scoped permission approvals
$session->rpc()->permissions()->resetSessionApprovals();
// Get the list of currently pending permission requests
$pending = $session->rpc()->permissions()->pendingRequests();
// Enable/disable the event bridge for permission requests
$session->rpc()->permissions()->setRequired(new PermissionsSetRequiredRequest(required: true));
// Add/remove permission rules
$session->rpc()->permissions()->modifyRules(new PermissionsModifyRulesParams(
    scope: PermissionsModifyRulesScope::SESSION,
    add: [['tool' => 'bash', 'decision' => 'allow']],
));
// Notify that a permission prompt was shown
$session->rpc()->permissions()->notifyPromptShown(new PermissionPromptShownNotification(message: 'tool permission prompt'));
// Clear, in memory, permission escalations restored from history on resume
$result = $session->rpc()->permissions()->clearResumeEscalation();
// $result->success
// Path permissions
$paths = $session->rpc()->permissions()->paths()->list();
$session->rpc()->permissions()->paths()->add(new PermissionPathsAddParams(path: '/path/to/allow'));
$session->rpc()->permissions()->paths()->updatePrimary(new PermissionPathsUpdatePrimaryParams(path: '/path/to/allow'));
$session->rpc()->permissions()->paths()->isPathWithinAllowedDirectories(new PermissionPathsAllowedCheckParams(path: '/path/to/allow/file.txt'));
$session->rpc()->permissions()->paths()->isPathWithinWorkspace(new PermissionPathsWorkspaceCheckParams(path: '/path/to/allow/file.txt'));
// URL permissions
$session->rpc()->permissions()->urls()->setUnrestrictedMode(
    new PermissionUrlsSetUnrestrictedModeParams(enabled: true)
);
// Resolve the permission location for the working directory and apply saved rules
$location = $session->rpc()->permissions()->locations()->resolve(
    new PermissionLocationResolveParams(workingDirectory: '/path/to/repo')
);
$session->rpc()->permissions()->locations()->apply(
    new PermissionLocationApplyParams(workingDirectory: '/path/to/repo')
);
// Persist a tool approval to the permission location
$session->rpc()->permissions()->locations()->addToolApproval(
    new PermissionLocationAddToolApprovalParams(
        approval: new PermissionsLocationsAddToolApprovalDetailsCommands(commandIdentifiers: ['bash']),
        locationKey: $location->locationKey,
    )
);
// Check and add folder trust
$trusted = $session->rpc()->permissions()->folderTrust()->isTrusted(['path' => '/path/to/repo']);
$session->rpc()->permissions()->folderTrust()->addTrusted(new FolderTrustAddParams(path: '/path/to/repo'));

// commands: get the list of slash commands available in the session
use Revolution\Copilot\Types\Rpc\CommandsListRequest;

$list = $session->rpc()->commands()->list();
// $list->commands - Array of SlashCommandInfo
// $list->commands[0]->name - Command name (without the slash)
// $list->commands[0]->description - Command description
// $list->commands[0]->kind - Command category (builtin, skill, client)
// $list->commands[0]->allowDuringAgentExecution - Whether it can be used while the agent is running

// Get the list with filters
$list = $session->rpc()->commands()->list(new CommandsListRequest(
    includeBuiltins: true,
    includeSkills: false,
));

// commands: invoke a slash command
use Revolution\Copilot\Types\Rpc\CommandsInvokeRequest;

$result = $session->rpc()->commands()->invoke(new CommandsInvokeRequest(
    name: 'help',
    input: 'optional input text',
));

// commands: respond to a command invocation event
$session->rpc()->commands()->handlePendingCommand(new CommandsHandlePendingCommandRequest(
    requestId: '...',
));

// commands: run a slash command synchronously
use Revolution\Copilot\Types\Rpc\ExecuteCommandParams;

$result = $session->rpc()->commands()->execute(new ExecuteCommandParams(
    commandName: 'review',
    args: 'src/',
), timeout: 120.0); // How long to wait for the CLI response (seconds). Defaults to 30 seconds
// $result->error - Error message if execution failed (null on success)

// commands: respond to a queued command
$session->rpc()->commands()->respondToQueuedCommand(new CommandsRespondToQueuedCommandRequest(
    requestId: '...',
    result: new QueuedCommandResult(handled: true),
));

// ui: respond to a UI elicitation request
$session->rpc()->ui()->elicitation(new UIElicitationRequest(
    message: 'Question for the user',
    requestedSchema: ['type' => 'object', 'properties' => [...]],
));

// ui: an ephemeral query that isn't added to the conversation history
$result = $session->rpc()->ui()->ephemeralQuery(new UIEphemeralQueryRequest(
    question: 'Summarize the key points of the conversation so far.',
));
// $result->answer

// ui: respond to a pending elicitation request (via the elicitation.requested event)
$session->rpc()->ui()->handlePendingElicitation(new UIHandlePendingElicitationRequest(
    requestId: '...',
    result: ['action' => 'accept', 'content' => ['name' => 'John']],
));

// ui: respond to pending requests via broadcast events
use Revolution\Copilot\Enums\UIAutoModeSwitchResponse;
use Revolution\Copilot\Types\Rpc\UIExitPlanModeResponse;
use Revolution\Copilot\Types\Rpc\UIHandlePendingAutoModeSwitchRequest;
use Revolution\Copilot\Types\Rpc\UIHandlePendingExitPlanModeRequest;
use Revolution\Copilot\Types\Rpc\UIHandlePendingSamplingRequest;
use Revolution\Copilot\Types\Rpc\UIHandlePendingUserInputRequest;
use Revolution\Copilot\Types\Rpc\SessionUiRegisterDirectAutoModeSwitchHandlerRequest;
use Revolution\Copilot\Types\Rpc\UIUnregisterDirectAutoModeSwitchHandlerRequest;
use Revolution\Copilot\Types\Rpc\UIUserInputResponse;

$registration = $session->rpc()->ui()->registerDirectAutoModeSwitchHandler(
    new SessionUiRegisterDirectAutoModeSwitchHandlerRequest(autoModeRecovery: true),
);
// When you request autoModeRecovery, enable recovery handling only after confirming the returned value is true.
// Register the actual event listener separately. To remove the handler, unregister it with the same handle.
$session->rpc()->ui()->unregisterDirectAutoModeSwitchHandler(
    new UIUnregisterDirectAutoModeSwitchHandlerRequest(handle: $registration->handle),
);

$result = $session->rpc()->ui()->handlePendingUserInput(new UIHandlePendingUserInputRequest(
    requestId: '...',
    response: new UIUserInputResponse(answer: 'blue', wasFreeform: false),
));

$result = $session->rpc()->ui()->handlePendingExitPlanMode(new UIHandlePendingExitPlanModeRequest(
    requestId: '...',
    response: new UIExitPlanModeResponse(approved: true, selectedAction: 'autopilot_fleet'),
));

$result = $session->rpc()->ui()->handlePendingAutoModeSwitch(new UIHandlePendingAutoModeSwitchRequest(
    requestId: '...',
    response: UIAutoModeSwitchResponse::Yes,
));

// Answer data.requestId from auto_mode_recovery_consent.requested with the same RPC.
// The runtime retries or rewinds during recovery, so don't resend the prompt from your app.

$result = $session->rpc()->ui()->handlePendingSampling(new UIHandlePendingSamplingRequest(
    requestId: '...',
    response: ['result' => '...'],
));
// Each method returns UIHandlePendingResult. Check $result->success to see whether the response was accepted.

// onExitPlanModeRequest / onAutoModeSwitchRequest in SessionConfig respond automatically via reverse-RPC.
// If you respond manually to the same request via events, don't use both paths at the same time.
```

## ui handlePendingSessionLimitsExhausted (respond to an exhausted limit)

When a session reaches its AI credit limit, send the user's choice back to the runtime with `ui()->handlePendingSessionLimitsExhausted()`. Set `action` to a `SessionLimitsExhaustedResponseAction` case: `Add` adds the given credits to the limit, `Set` changes the limit to an absolute value, `Unset` removes the limit, and `Cancel` cancels the blocked request without changing the limit.

```php theme={null}
use Revolution\Copilot\Enums\SessionLimitsExhaustedResponseAction;
use Revolution\Copilot\Types\Rpc\UIHandlePendingSessionLimitsExhaustedRequest;
use Revolution\Copilot\Types\Rpc\UISessionLimitsExhaustedResponse;

$session->rpc()->ui()->handlePendingSessionLimitsExhausted(
    new UIHandlePendingSessionLimitsExhaustedRequest(
        requestId: $requestId,
        response: new UISessionLimitsExhaustedResponse(
            action: SessionLimitsExhaustedResponseAction::Add,
            additionalAiCredits: 10.0,
        ),
    ),
);
```

For details, see [Session AI credit limits](https://kawax.biz/en/packages/laravel-copilot-sdk/session-limits.md).

## commands enqueue (queue a command)

```php theme={null}
use Revolution\Copilot\Types\Rpc\EnqueueCommandParams;

$session->rpc()->commands()->enqueue(new EnqueueCommandParams('/compact'));
```


## Related topics

- [SessionRpc overview](https://kawax.biz/en/packages/laravel-copilot-sdk/rpc/session-overview.md)
- [RPC (Remote Procedure Call)](https://kawax.biz/en/packages/laravel-copilot-sdk/rpc.md)
- [Tools](https://kawax.biz/en/packages/laravel-copilot-sdk/tools.md)
- [Streaming events](https://kawax.biz/en/packages/laravel-copilot-sdk/streaming-events.md)
- [Laravel Doctor — application diagnostics tool](https://kawax.biz/en/blog/laravel-doctor-introduction.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.