An open-source, self-hostable PaaS alternative to Vercel, Heroku & Netlify that lets you easily deploy static sites, databases, full-stack applications and 360+ one-click services on your own servers.
PHP coolifydatabasesdeploymentdockerdocker-composeinertiajslaravelmariadbmysqlnextjsnodejsphppostgresredisself-hostedself-hostingserverstatic-sitesveltesvelte5
chore: merge main into release/v4.5
Andras Bacsaia82d32c94636
diff --cc app/Http/Controllers/Api/ApplicationsController.phpindex 2904a61806,3dac22efb3..3cd02d31ec--- a/app/Http/Controllers/Api/ApplicationsController.php+++ b/app/Http/Controllers/Api/ApplicationsController.php@@@ -3405,25 -3403,28 +3450,46 @@@ class ApplicationsController extends Co'errors' => $errors,], 422);}+ if ($forbidden = $this->manualWebhookSecretForbiddenResponse($request, $application)) {+ return $forbidden;+ }++ $githubApp = null;+ if ($request->has('github_app_uuid')) {+ if ($application->build_pack === 'dockerimage' || filled($application->dockerfile) || $application->deploymentType() === 'deploy_key') {+ return response()->json([+ 'message' => 'Validation failed.',+ 'errors' => [+ 'github_app_uuid' => 'The github_app_uuid can only be changed for applications deployed from a GitHub App or public repository.',+ ],+ ], 422);+ }+ $githubApp = GithubApp::where('uuid', $request->github_app_uuid)+ ->where(fn ($query) => $query->where('team_id', $teamId)->orWhere('is_system_wide', true))+ ->first();+ if (! $githubApp?->isConnected()) {+ return response()->json(['message' => 'Github App not found.'], 404);+ }+ }+ $githubApp = null;+ if ($request->has('github_app_uuid')) {+ if ($application->build_pack === 'dockerimage' || filled($application->dockerfile) || $application->deploymentType() === 'deploy_key') {+ return response()->json([+ 'message' => 'Validation failed.',+ 'errors' => [+ 'github_app_uuid' => 'The github_app_uuid can only be changed for applications deployed from a GitHub App or public repository.',+ ],+ ], 422);+ }+ $githubApp = GithubApp::where('uuid', $request->github_app_uuid)+ ->where(fn ($query) => $query->where('team_id', $teamId)->orWhere('is_system_wide', true))+ ->first();+ if (! $githubApp?->isConnected()) {+ return response()->json(['message' => 'Github App not found.'], 404);+ }+ }+$applicationSettings = $this->applicationSettingsFromRequest($request);if ($prefixValidation = $this->containerNamePrefixValidationResponse($applicationSettings, $application->destination->server, $application)) {return $prefixValidation;diff --cc app/Http/Controllers/Api/DatabasesController.phpindex 634f20720d,cee12701d5..5ecab6ed6d--- a/app/Http/Controllers/Api/DatabasesController.php+++ b/app/Http/Controllers/Api/DatabasesController.php@@@ -671,10 -603,13 +678,17 @@@ class DatabasesController extends Contr$this->authorize('manage', $database);}+ if ($redactAllEnvValuesInLogs !== null) {+ $this->authorize('manageEnvironment', $database);+ }++ if ($request->has('is_public') && (bool) $request->is_public !== (bool) $database->is_public) {+ $forbidden = $this->deployAbilityForbiddenResponse($request, 'Making a database public or private starts or stops its proxy on the server, so it needs a token with the deploy permission.');+ if ($forbidden) {+ return $forbidden;+ }+ }+if ($request->is_public && $request->public_port) {if (isPublicPortAlreadyUsed($database->destination->server, $request->public_port, $database->id)) {return response()->json(['message' => 'Public port already used by another database.'], 400);@@@ -987,11 -916,10 +1001,11 @@@'frequency' => ['type' => 'string', 'description' => 'Backup frequency (cron expression or: every_minute, hourly, daily, weekly, monthly, yearly)'],'enabled' => ['type' => 'boolean', 'description' => 'Whether the backup is enabled', 'default' => true],'save_s3' => ['type' => 'boolean', 'description' => 'Whether to save backups to S3', 'default' => false],- 's3_storage_uuid' => ['type' => 'string', 'description' => 'S3 storage UUID (required if save_s3 is true)'],+ 's3_storage_uuid' => ['type' => 'string', 'description' => 'Primary S3 storage UUID. Sent without s3_storage_uuids, it selects this storage as the only destination. Either field is required if save_s3 is true.'],+ 's3_storage_uuids' => ['type' => 'array', 'items' => ['type' => 'string'], 'description' => 'UUIDs of every S3 storage the backup is uploaded to. Replaces the current destinations. When s3_storage_uuid is also sent, it must be in this list and becomes the primary destination; otherwise the first entry is the primary destination.'],'databases_to_backup' => ['type' => 'string', 'description' => 'Comma separated list of databases to backup'],'dump_all' => ['type' => 'boolean', 'description' => 'Whether to dump all databases', 'default' => false],- 'backup_now' => ['type' => 'boolean', 'description' => 'Whether to trigger backup immediately after creation'],+ 'backup_now' => ['type' => 'boolean', 'description' => 'Whether to trigger backup immediately after creation. Needs a token with the deploy permission.'],'database_backup_retention_amount_locally' => ['type' => 'integer', 'description' => 'Number of backups to retain locally'],'database_backup_retention_days_locally' => ['type' => 'integer', 'description' => 'Number of days to retain backups locally'],'database_backup_retention_max_storage_locally' => ['type' => 'number', 'description' => 'Max storage (GB) for local backups'],@@@ -1231,9 -1183,8 +1256,9 @@@type: 'object',properties: ['save_s3' => ['type' => 'boolean', 'description' => 'Whether data is saved in s3 or not'],- 's3_storage_uuid' => ['type' => 'string', 'description' => 'S3 storage UUID'],+ 's3_storage_uuid' => ['type' => 'string', 'description' => 'Primary S3 storage UUID. Sent without s3_storage_uuids, it selects this storage as the only destination; when it is already a destination, it becomes the primary destination and the other destinations stay.'],+ 's3_storage_uuids' => ['type' => 'array', 'items' => ['type' => 'string'], 'description' => 'UUIDs of every S3 storage the backup is uploaded to. Replaces the current destinations. When s3_storage_uuid is also sent, it must be in this list and becomes the primary destination; otherwise the first entry is the primary destination.'],- 'backup_now' => ['type' => 'boolean', 'description' => 'Whether to take a backup now or not'],+ 'backup_now' => ['type' => 'boolean', 'description' => 'Whether to take a backup now or not. Needs a token with the deploy permission.'],'enabled' => ['type' => 'boolean', 'description' => 'Whether the backup is enabled or not'],'databases_to_backup' => ['type' => 'string', 'description' => 'Comma separated list of databases to backup'],'dump_all' => ['type' => 'boolean', 'description' => 'Whether all databases are dumped or not'],diff --cc app/Http/Controllers/Api/HostingerController.phpindex af4173e39d,0000000000..34eb2e94bfmode 100644,000000..100644--- a/app/Http/Controllers/Api/HostingerController.php+++ b/app/Http/Controllers/Api/HostingerController.php@@@ -1,370 -1,0 +1,376 @@@+<?php++namespace App\Http\Controllers\Api;++use App\Actions\Server\ValidateServer;+use App\Enums\ProxyTypes;+use App\Exceptions\RateLimitException;++use App\Http\Controllers\Api\Concerns\RequiresDeployAbility;+use App\Http\Controllers\Controller;+use App\Models\CloudProviderToken;+use App\Models\PrivateKey;+use App\Models\Server;+use App\Models\Team;+use App\Rules\ValidHostname;+use App\Services\HostingerService;+use Illuminate\Http\JsonResponse;+use Illuminate\Http\Request;+use OpenApi\Attributes as OA;++class HostingerController extends Controller+{++ use RequiresDeployAbility;+++ #[OA\Get(+ path: '/hostinger/data-centers',+ operationId: 'get-hostinger-data-centers',+ summary: 'Get Hostinger VPS data centers',+ security: [['bearerAuth' => []]],+ tags: ['Hostinger'],+ responses: [+ new OA\Response(response: 200, description: 'List of Hostinger VPS data centers.'),+ new OA\Response(response: 401, ref: '#/components/responses/401'),+ new OA\Response(response: 403, description: 'Hostinger denied access to this resource for the cloud provider token.'),+ new OA\Response(response: 422, description: 'Validation failed.'),+ new OA\Response(response: 429, description: 'Hostinger rate limit exceeded.'),+ ]+ )]+ public function dataCenters(Request $request): JsonResponse+ {+ return $this->providerData($request, 'getDataCenters', 'data centers');+ }++ #[OA\Get(+ path: '/hostinger/catalog',+ operationId: 'get-hostinger-catalog',+ summary: 'Get Hostinger VPS plans and prices',+ security: [['bearerAuth' => []]],+ tags: ['Hostinger'],+ responses: [+ new OA\Response(response: 200, description: 'List of Hostinger VPS plans and prices.'),+ new OA\Response(response: 401, ref: '#/components/responses/401'),+ new OA\Response(response: 403, description: 'Hostinger denied access to this resource for the cloud provider token.'),+ new OA\Response(response: 422, description: 'Validation failed.'),+ new OA\Response(response: 429, description: 'Hostinger rate limit exceeded.'),+ ]+ )]+ public function catalog(Request $request): JsonResponse+ {+ return $this->providerData($request, 'getCatalogItems', 'catalog');+ }++ #[OA\Get(+ path: '/hostinger/templates',+ operationId: 'get-hostinger-templates',+ summary: 'Get Hostinger VPS operating system templates',+ security: [['bearerAuth' => []]],+ tags: ['Hostinger'],+ responses: [+ new OA\Response(response: 200, description: 'List of Hostinger VPS templates.'),+ new OA\Response(response: 401, ref: '#/components/responses/401'),+ new OA\Response(response: 403, description: 'Hostinger denied access to this resource for the cloud provider token.'),+ new OA\Response(response: 422, description: 'Validation failed.'),+ new OA\Response(response: 429, description: 'Hostinger rate limit exceeded.'),+ ]+ )]+ public function templates(Request $request): JsonResponse+ {+ return $this->providerData($request, 'getTemplates', 'templates');+ }++ #[OA\Get(+ path: '/hostinger/ssh-keys',+ operationId: 'get-hostinger-ssh-keys',+ summary: 'Get Hostinger account SSH keys',+ security: [['bearerAuth' => []]],+ tags: ['Hostinger'],+ responses: [+ new OA\Response(response: 200, description: 'List of Hostinger account SSH keys.'),+ new OA\Response(response: 401, ref: '#/components/responses/401'),+ new OA\Response(response: 403, description: 'Hostinger denied access to this resource for the cloud provider token.'),+ new OA\Response(response: 422, description: 'Validation failed.'),+ new OA\Response(response: 429, description: 'Hostinger rate limit exceeded.'),+ ]+ )]+ public function sshKeys(Request $request): JsonResponse+ {+ return $this->providerData($request, 'getPublicKeys', 'SSH keys');+ }++ #[OA\Get(+ path: '/hostinger/post-install-scripts',+ operationId: 'get-hostinger-post-install-scripts',+ summary: 'Get Hostinger post-install scripts',+ security: [['bearerAuth' => []]],+ tags: ['Hostinger'],+ responses: [+ new OA\Response(response: 200, description: 'List of Hostinger post-install scripts.'),+ new OA\Response(response: 401, ref: '#/components/responses/401'),+ new OA\Response(response: 403, description: 'Hostinger denied access to this resource for the cloud provider token.'),+ new OA\Response(response: 422, description: 'Validation failed.'),+ new OA\Response(response: 429, description: 'Hostinger rate limit exceeded.'),+ ]+ )]+ public function postInstallScripts(Request $request): JsonResponse+ {+ return $this->providerData($request, 'getPostInstallScripts', 'post-install scripts');+ }++ #[OA\Post(+ path: '/servers/hostinger',+ operationId: 'create-hostinger-server',+ summary: 'Purchase a Hostinger VPS and create a linked server',+ security: [['bearerAuth' => []]],+ tags: ['Hostinger'],+ responses: [+ new OA\Response(response: 201, description: 'Hostinger VPS purchased and linked to a Coolify server.'),+ new OA\Response(response: 401, ref: '#/components/responses/401'),- new OA\Response(response: 403, description: 'The token needs the deploy ability to set post_install_script_id or public_key_ids.'),++ new OA\Response(response: 403, description: 'The token needs the deploy permission for a post-install script or extra SSH keys.'),+ new OA\Response(response: 422, description: 'Validation failed.'),+ new OA\Response(response: 429, description: 'Hostinger rate limit exceeded.'),+ ]+ )]+ public function createServer(Request $request): JsonResponse+ {+ $allowedFields = [+ 'cloud_provider_token_uuid',+ 'cloud_provider_token_id',+ 'item_id',+ 'data_center_id',+ 'template_id',+ 'name',+ 'private_key_uuid',+ 'enable_backups',+ 'public_key_ids',+ 'post_install_script_id',+ 'instant_validate',+ ];+ $teamId = getTeamIdFromToken();++ if (is_null($teamId)) {+ return invalidTokenResponse();+ }++ $this->authorize('create', [Server::class]);++ $return = validateIncomingRequest($request);+ if ($return instanceof JsonResponse) {+ return $return;+ }++ $validator = customApiValidator($request->all(), [+ 'cloud_provider_token_uuid' => 'required_without:cloud_provider_token_id|string',+ 'cloud_provider_token_id' => 'required_without:cloud_provider_token_uuid|string',+ 'item_id' => 'required|string',+ 'data_center_id' => 'required|integer',+ 'template_id' => 'required|integer',+ 'name' => ['nullable', 'string', 'max:253', new ValidHostname],+ 'private_key_uuid' => 'required|string',+ 'enable_backups' => 'nullable|boolean',+ 'public_key_ids' => 'nullable|array',+ 'public_key_ids.*' => 'integer',+ 'post_install_script_id' => 'nullable|integer',+ 'instant_validate' => 'nullable|boolean',+ ]);+ $extraFields = array_diff(array_keys($request->all()), $allowedFields);++ if ($validator->fails() || ! empty($extraFields)) {+ $errors = $validator->errors();+ foreach ($extraFields as $field) {+ $errors->add($field, 'This field is not allowed.');+ }++ return response()->json([+ 'message' => 'Validation failed.',+ 'errors' => $errors,+ ], 422);+ }++ if ($request->filled('post_install_script_id') || $request->array('public_key_ids')) {- abort_unless($request->user()->tokenCan('deploy') || $request->user()->tokenCan('root'), 403, 'Missing required permissions: deploy');++ $forbidden = $this->deployAbilityForbiddenResponse($request, 'A post-install script or extra SSH keys run as root on the new server, so it needs a token with the deploy permission.');++ if ($forbidden) {++ return $forbidden;++ }+ }++ $team = Team::find($teamId);+ if (Team::serverLimitReached($team)) {+ return response()->json(['message' => 'Server limit reached for your subscription.'], 400);+ }++ $token = $this->hostingerToken($request, $teamId);+ if ($token instanceof JsonResponse) {+ return $token;+ }++ $privateKey = PrivateKey::whereTeamId($teamId)->whereUuid($request->private_key_uuid)->first();+ if (! $privateKey) {+ return response()->json(['message' => 'Private key not found.'], 404);+ }++ $virtualMachineId = null;++ try {+ $hostingerService = new HostingerService($token->token);+ $normalizedServerName = strtolower(trim($request->name ?: generate_random_name()));+ $setup = [+ 'data_center_id' => $request->integer('data_center_id'),+ 'template_id' => $request->integer('template_id'),+ 'hostname' => $normalizedServerName,+ 'enable_backups' => $request->boolean('enable_backups'),+ 'public_key' => [+ 'name' => $privateKey->name,+ 'key' => $privateKey->getPublicKey(),+ ],+ ];+ if ($request->filled('post_install_script_id')) {+ $setup['post_install_script_id'] = $request->integer('post_install_script_id');+ }++ $virtualMachine = $hostingerService->purchaseVirtualMachine([+ 'item_id' => $request->item_id,+ 'setup' => $setup,+ ]);+ $virtualMachineId = (int) $virtualMachine['id'];++ $server = Server::create([+ 'name' => $normalizedServerName,+ 'ip' => Server::PLACEHOLDER_IP,+ 'user' => 'root',+ 'port' => 22,+ 'team_id' => $teamId,+ 'private_key_id' => $privateKey->id,+ 'cloud_provider_token_id' => $token->id,+ 'hostinger_virtual_machine_id' => $virtualMachine['id'],+ 'hostinger_virtual_machine_status' => $virtualMachine['state'] ?? null,+ ]);++ $server->proxy->set('status', 'exited');+ $server->proxy->set('type', ProxyTypes::TRAEFIK->value);+ $server->save();++ try {+ if ($request->array('public_key_ids')) {+ $hostingerService->attachPublicKeys((int) $virtualMachine['id'], $request->array('public_key_ids'));+ }+ $virtualMachine = $hostingerService->waitForPublicIp($virtualMachine);+ $ipAddress = $hostingerService->getPublicIpAddress($virtualMachine);+ if ($ipAddress) {+ $server->update([+ 'ip' => $ipAddress,+ 'hostinger_virtual_machine_status' => $virtualMachine['state'] ?? $server->hostinger_virtual_machine_status,+ ]);+ }+ } catch (\Throwable $e) {+ report($e);+ }++ $ipAddress = $server->fresh()->ip;++ if ($request->boolean('instant_validate') && ! $server->hasPlaceholderIp()) {+ ValidateServer::dispatch($server);+ }++ auditLog('api.hostinger_virtual_machine.created', [+ 'team_id' => $teamId,+ 'server_uuid' => $server->uuid,+ 'server_name' => $server->name,+ 'hostinger_virtual_machine_id' => $virtualMachine['id'],+ 'ip' => $ipAddress,+ ]);++ return response()->json([+ 'uuid' => $server->uuid,+ 'hostinger_virtual_machine_id' => $virtualMachine['id'],+ 'ip' => $ipAddress,+ 'provisioning' => $ipAddress === Server::PLACEHOLDER_IP,+ ])->setStatusCode(201);+ } catch (RateLimitException $e) {+ return $this->rateLimitResponse($e);+ } catch (\Throwable $e) {+ logger()->error('Failed to create Hostinger server', [+ 'error' => $e->getMessage(),+ 'team_id' => $teamId,+ 'hostinger_virtual_machine_id' => $virtualMachineId,+ ]);++ if ($e->getCode() === 202) {+ return response()->json(['message' => $e->getMessage()], 202);+ }++ return response()->json(array_filter([+ 'message' => $virtualMachineId+ ? 'The Hostinger VPS was purchased but could not be saved in Coolify. Manage it in hPanel.'+ : 'Failed to create Hostinger server.',+ 'hostinger_virtual_machine_id' => $virtualMachineId,+ ]), 500);+ }+ }++ private function providerData(Request $request, string $method, string $resource): JsonResponse+ {+ $teamId = getTeamIdFromToken();+ if (is_null($teamId)) {+ return invalidTokenResponse();+ }++ $token = $this->hostingerToken($request, $teamId);+ if ($token instanceof JsonResponse) {+ return $token;+ }++ try {+ return response()->json((new HostingerService($token->token))->{$method}());+ } catch (RateLimitException $e) {+ return $this->rateLimitResponse($e);+ } catch (\Throwable $e) {+ $hostingerErrorPrefix = 'Hostinger API error: ';+ if (in_array($e->getCode(), [401, 403], true) && str_starts_with($e->getMessage(), $hostingerErrorPrefix)) {+ $hostingerMessage = substr($e->getMessage(), strlen($hostingerErrorPrefix));++ return response()->json(['message' => "Hostinger denied access to {$resource}: {$hostingerMessage}"], 403);+ }++ return response()->json(['message' => "Failed to fetch Hostinger {$resource}."], 500);+ }+ }++ private function rateLimitResponse(RateLimitException $e): JsonResponse+ {+ $response = response()->json(['message' => $e->getMessage()], 429);+ if ($e->retryAfter !== null) {+ $response->header('Retry-After', $e->retryAfter);+ }++ return $response;+ }++ private function hostingerToken(Request $request, int $teamId): CloudProviderToken|JsonResponse+ {+ $validator = customApiValidator($request->all(), [+ 'cloud_provider_token_uuid' => 'required_without:cloud_provider_token_id|string',+ 'cloud_provider_token_id' => 'required_without:cloud_provider_token_uuid|string',+ ]);++ if ($validator->fails()) {+ return response()->json([+ 'message' => 'Validation failed.',+ 'errors' => $validator->errors(),+ ], 422);+ }++ $tokenUuid = $request->cloud_provider_token_uuid ?? $request->cloud_provider_token_id;+ $token = CloudProviderToken::whereTeamId($teamId)+ ->whereUuid($tokenUuid)+ ->where('provider', 'hostinger')+ ->first();++ if (! $token) {+ return response()->json(['message' => 'Hostinger cloud provider token not found.'], 404);+ }++ $this->authorize('view', $token);++ return $token;+ }+}diff --cc app/Http/Controllers/Api/VolumeBackupsController.phpindex a199f530db,97161d3111..16edac3bab--- a/app/Http/Controllers/Api/VolumeBackupsController.php+++ b/app/Http/Controllers/Api/VolumeBackupsController.php@@@ -27,9 -27,8 +28,9 @@@ use RuntimeExceptionnew OA\Property(property: 'enabled', type: 'boolean', default: true),new OA\Property(property: 'save_s3', type: 'boolean', default: false),new OA\Property(property: 'disable_local_backup', type: 'boolean', default: false),- new OA\Property(property: 'stop_during_backup', type: 'boolean', default: false),+ new OA\Property(property: 'stop_during_backup', type: 'boolean', default: false, description: 'Stop the resource containers during the backup. Needs a token with the deploy permission.'),- new OA\Property(property: 's3_storage_uuid', type: 'string', nullable: true),+ new OA\Property(property: 's3_storage_uuid', type: 'string', nullable: true, description: 'Primary S3 storage UUID. Sent without s3_storage_uuids, it selects this storage as the only destination.'),+ new OA\Property(property: 's3_storage_uuids', type: 'array', items: new OA\Items(type: 'string'), description: 'UUIDs of every S3 storage the backup is uploaded to. When s3_storage_uuid is also sent, it must be in this list and becomes the primary destination; otherwise the first entry is the primary destination. save_s3 requires at least one destination.'),new OA\Property(property: 'retention_amount_locally', type: 'integer', default: 7, minimum: 0, maximum: 10000),new OA\Property(property: 'retention_days_locally', type: 'integer', default: 0, maximum: 2147483647, minimum: 0),new OA\Property(property: 'retention_max_storage_locally', type: 'number', format: 'float', default: 0, maximum: 9999999999, minimum: 0),diff --cc app/Livewire/DeploymentsIndicator.phpindex 190da1a097,a59ccf9142..6f810b9edc--- a/app/Livewire/DeploymentsIndicator.php+++ b/app/Livewire/DeploymentsIndicator.php@@@ -3,9 -3,7 +3,8 @@@namespace App\Livewire;use App\Models\ApplicationDeploymentQueue;- use App\Models\Server;use Livewire\Attributes\Computed;+use Livewire\Attributes\Locked;use Livewire\Component;class DeploymentsIndicator extends Componentdiff --cc app/Mcp/Tools/CloudProvider.phpindex fdc545c258,0000000000..99b750ab70mode 100644,000000..100644--- a/app/Mcp/Tools/CloudProvider.php+++ b/app/Mcp/Tools/CloudProvider.php@@@ -1,72 -1,0 +1,72 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsOpenWorld;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+#[IsOpenWorld]+class CloudProvider extends RestActionTool+{+ protected string $name = 'cloud_provider';+- protected string $description = 'Manage cloud provider API tokens of the authenticated team (Hetzner, DigitalOcean, Vultr, Hostinger), read provider catalogs, and provision new paid servers. Provider tokens are never returned. Requires read ability for list_tokens/get_token/catalog, write ability for the rest. Same validation and permissions as the REST API.';++ protected string $description = 'Manage cloud provider API tokens of the authenticated team (Hetzner, DigitalOcean, Vultr, Hostinger), read provider catalogs, and provision new paid servers. Provider tokens are never returned. Requires read ability for list_tokens/get_token/catalog, write ability for the rest (provision_server with a cloud-init or post-install script or extra SSH keys also needs deploy). Same validation and permissions as the REST API.';++ private const CATALOG_PATHS = [+ 'hetzner_locations' => 'hetzner/locations',+ 'hetzner_server_types' => 'hetzner/server-types',+ 'hetzner_images' => 'hetzner/images',+ 'hetzner_ssh_keys' => 'hetzner/ssh-keys',+ 'hetzner_firewalls' => 'hetzner/firewalls',+ 'hetzner_networks' => 'hetzner/networks',+ 'digitalocean_regions' => 'digitalocean/regions',+ 'digitalocean_sizes' => 'digitalocean/sizes',+ 'digitalocean_images' => 'digitalocean/images',+ 'digitalocean_ssh_keys' => 'digitalocean/ssh-keys',+ 'vultr_regions' => 'vultr/regions',+ 'vultr_plans' => 'vultr/plans',+ 'vultr_os' => 'vultr/os',+ 'vultr_ssh_keys' => 'vultr/ssh-keys',+ 'hostinger_data_centers' => 'hostinger/data-centers',+ 'hostinger_catalog' => 'hostinger/catalog',+ 'hostinger_templates' => 'hostinger/templates',+ 'hostinger_ssh_keys' => 'hostinger/ssh-keys',+ 'hostinger_post_install_scripts' => 'hostinger/post-install-scripts',+ ];++ private const PROVISION_PATHS = [+ 'hetzner' => 'servers/hetzner',+ 'digitalocean' => 'servers/digitalocean',+ 'vultr' => 'servers/vultr',+ 'hostinger' => 'servers/hostinger',+ ];++ protected function actions(): array+ {+ return [+ 'list_tokens' => ['method' => 'GET', 'path' => 'cloud-tokens', 'ability' => 'read', 'description' => 'cloud provider tokens of the team (no token values)'],+ 'get_token' => ['method' => 'GET', 'path' => 'cloud-tokens/{uuid}', 'ability' => 'read', 'description' => 'one cloud provider token (no token value)'],+ 'create_token' => ['method' => 'POST', 'path' => 'cloud-tokens', 'ability' => 'write', 'description' => 'add a provider token; it is checked with the provider first (data: provider hetzner|digitalocean|vultr|hostinger, token, name)'],+ 'update_token' => ['method' => 'PATCH', 'path' => 'cloud-tokens/{uuid}', 'ability' => 'write', 'description' => 'rename a provider token (data: name)'],+ 'delete_token' => ['method' => 'DELETE', 'path' => 'cloud-tokens/{uuid}', 'ability' => 'write', 'confirm' => true, 'description' => 'delete a provider token that no server uses'],+ 'validate_token' => ['method' => 'POST', 'path' => 'cloud-tokens/{uuid}/validate', 'ability' => 'write', 'description' => 'check a stored provider token with the provider'],+ 'catalog' => ['method' => 'GET', 'paths' => self::CATALOG_PATHS, 'ability' => 'read', 'description' => 'read a provider catalog; resource is <provider>_<catalog>, for example hetzner_locations (data: cloud_provider_token_uuid)'],- 'provision_server' => ['method' => 'POST', 'paths' => self::PROVISION_PATHS, 'ability' => 'write', 'confirm' => true, 'description' => 'create a new paid server at the provider and add it to Coolify; resource is the provider (data: cloud_provider_token_uuid, private_key_uuid, name, and the provider fields, for example location, server_type, image for hetzner)'],++ 'provision_server' => ['method' => 'POST', 'paths' => self::PROVISION_PATHS, 'ability' => 'write', 'confirm' => true, 'description' => 'create a new paid server at the provider and add it to Coolify; resource is the provider (data: cloud_provider_token_uuid, private_key_uuid, name, and the provider fields, for example location, server_type, image for hetzner; a cloud-init or post-install script or extra SSH keys need deploy ability)'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Cloud provider token UUID (get_token, update_token, delete_token, validate_token).',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body or catalog query, same fields as the REST API. Catalogs and provision_server need cloud_provider_token_uuid.';+ }+}diff --cc app/Mcp/Tools/CreateApplication.phpindex 249c0b4b1c,0000000000..82c6413f8amode 100644,000000..100644--- a/app/Mcp/Tools/CreateApplication.php+++ b/app/Mcp/Tools/CreateApplication.php@@@ -1,39 -1,0 +1,39 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class CreateApplication extends RestActionTool+{+ protected string $name = 'create_application';+- protected string $description = 'Create an application in a project of the authenticated team, from a public Git repository, a private repository (GitHub App or deploy key), a Dockerfile, or a Docker image. Requires write ability (instant_deploy also needs deploy). Same validation and permissions as the REST API.';++ protected string $description = 'Create an application in a project of the authenticated team, from a public Git repository, a private repository (GitHub App or deploy key), a Dockerfile, or a Docker image. Requires write ability (instant_deploy and manual webhook secrets also need deploy). Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [+ 'public' => ['method' => 'POST', 'path' => 'applications/public', 'ability' => 'write', 'description' => 'create from a public Git repository (data: git_repository, git_branch, build_pack, ports_exposes)'],+ 'github_app' => ['method' => 'POST', 'path' => 'applications/private-github-app', 'ability' => 'write', 'description' => 'create from a private repository through a GitHub App (data: github_app_uuid, git_repository, git_branch, build_pack, ports_exposes)'],+ 'deploy_key' => ['method' => 'POST', 'path' => 'applications/private-deploy-key', 'ability' => 'write', 'description' => 'create from a private repository with a deploy key (data: private_key_uuid, git_repository, git_branch, build_pack, ports_exposes)'],+ 'dockerfile' => ['method' => 'POST', 'path' => 'applications/dockerfile', 'ability' => 'write', 'description' => 'create from a base64 encoded Dockerfile (data: dockerfile, ports_exposes)'],+ 'docker_image' => ['method' => 'POST', 'path' => 'applications/dockerimage', 'ability' => 'write', 'description' => 'create from a Docker image (data: docker_registry_image_name, docker_registry_image_tag, ports_exposes)'],+ ];+ }++ protected function pathParams(): array+ {+ return [];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API. Always: project_uuid, environment_name or environment_uuid, server_uuid, destination_uuid (required when the server has several destinations). '+ .'public / github_app / deploy_key: git_repository, git_branch, build_pack (nixpacks | railpack | static | dockerfile | dockercompose), ports_exposes (not for dockercompose); github_app also needs github_app_uuid, deploy_key needs private_key_uuid. '+ .'dockerfile: dockerfile (base64). docker_image: docker_registry_image_name, docker_registry_image_tag, ports_exposes. '+ .'Optional: name, description, domains, autogenerate_domain, git_commit_sha, base_directory, publish_directory, install_command, build_command, start_command, docker_compose_location, docker_compose_domains, is_static, is_spa, health_check_*, limits_*, tags, instant_deploy (needs deploy ability).';+ }+}diff --cc app/Mcp/Tools/DockerCleanup.phpindex 1136958250,0000000000..22f5c498bamode 100644,000000..100644--- a/app/Mcp/Tools/DockerCleanup.php+++ b/app/Mcp/Tools/DockerCleanup.php@@@ -1,37 -1,0 +1,37 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class DockerCleanup extends RestActionTool+{+ protected string $name = 'docker_cleanup';+- protected string $description = 'Read or change the Docker cleanup settings of a server of the authenticated team, list recent cleanup runs, or start a cleanup now. Requires read ability for get/executions, write ability for update/run. Same validation and permissions as the REST API.';++ protected string $description = 'Read or change the Docker cleanup settings of a server of the authenticated team, list recent cleanup runs, or start a cleanup now. Requires read ability for get/executions, write ability for update (turning on delete_unused_volumes also needs deploy), deploy ability for run. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [+ 'get' => ['method' => 'GET', 'path' => 'servers/{uuid}/docker-cleanup', 'ability' => 'read', 'description' => 'cleanup settings'],- 'update' => ['method' => 'PATCH', 'path' => 'servers/{uuid}/docker-cleanup', 'ability' => 'write', 'description' => 'change cleanup settings (data: docker_cleanup_frequency, docker_cleanup_threshold, force_docker_cleanup, delete_unused_volumes, delete_unused_networks, disable_application_image_retention)'],++ 'update' => ['method' => 'PATCH', 'path' => 'servers/{uuid}/docker-cleanup', 'ability' => 'write', 'description' => 'change cleanup settings (data: docker_cleanup_frequency, docker_cleanup_threshold, force_docker_cleanup, delete_unused_volumes, delete_unused_networks, disable_application_image_retention; turning on delete_unused_volumes needs deploy ability)'],+ 'executions' => ['method' => 'GET', 'path' => 'servers/{uuid}/docker-cleanup/executions', 'ability' => 'read', 'description' => 'last 20 cleanup runs'],- 'run' => ['method' => 'POST', 'path' => 'servers/{uuid}/docker-cleanup/run', 'ability' => 'write', 'confirm' => true, 'description' => 'start a cleanup now; removes unused images, and volumes/networks when enabled (data: delete_unused_volumes, delete_unused_networks)'],++ 'run' => ['method' => 'POST', 'path' => 'servers/{uuid}/docker-cleanup/run', 'ability' => 'deploy', 'confirm' => true, 'description' => 'start a cleanup now; removes unused images, and volumes/networks when enabled (data: delete_unused_volumes, delete_unused_networks)'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Server UUID.',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API: docker_cleanup_frequency, docker_cleanup_threshold, force_docker_cleanup, delete_unused_volumes, delete_unused_networks, disable_application_image_retention.';+ }+}diff --cc app/Mcp/Tools/ManageApplication.phpindex bdb1bf898a,0000000000..bf857b4fdamode 100644,000000..100644--- a/app/Mcp/Tools/ManageApplication.php+++ b/app/Mcp/Tools/ManageApplication.php@@@ -1,40 -1,0 +1,40 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManageApplication extends RestActionTool+{+ protected string $name = 'manage_application';+- protected string $description = 'Update, delete, clone, or move an application of the authenticated team, or add or remove an additional server destination. Requires write ability. Same validation and permissions as the REST API.';++ protected string $description = 'Update, delete, clone, or move an application of the authenticated team, or add or remove an additional server destination. Requires write ability; delete, instant_deploy, manual webhook secrets, and clone_volumes also need deploy. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [- 'update' => ['method' => 'PATCH', 'path' => 'applications/{uuid}', 'ability' => 'write', 'description' => 'update application settings (data: same fields as the REST update, e.g. name, domains, git_branch, ports_exposes, build_command)'],- 'delete' => ['method' => 'DELETE', 'path' => 'applications/{uuid}', 'ability' => 'write', 'confirm' => true, 'description' => 'delete the application and its containers (data: delete_volumes, delete_connected_networks, delete_configurations, docker_cleanup)'],- 'clone' => ['method' => 'POST', 'path' => 'applications/{uuid}/clone', 'ability' => 'write', 'description' => 'clone the application to a destination of the team (data: destination_uuid, name, clone_volumes)'],++ 'update' => ['method' => 'PATCH', 'path' => 'applications/{uuid}', 'ability' => 'write', 'description' => 'update application settings (data: same fields as the REST update, e.g. name, domains, git_branch, ports_exposes, build_command; instant_deploy and manual_webhook_secret_* need deploy ability)'],++ 'delete' => ['method' => 'DELETE', 'path' => 'applications/{uuid}', 'ability' => 'deploy', 'confirm' => true, 'description' => 'delete the application and its containers (data: delete_volumes, delete_connected_networks, delete_configurations, docker_cleanup)'],++ 'clone' => ['method' => 'POST', 'path' => 'applications/{uuid}/clone', 'ability' => 'write', 'description' => 'clone the application to a destination of the team (data: destination_uuid, name, clone_volumes; clone_volumes needs deploy ability)'],+ 'move' => ['method' => 'POST', 'path' => 'applications/{uuid}/move', 'ability' => 'write', 'confirm' => true, 'description' => 'move the application to another environment of the team (data: environment_uuid)'],+ 'add_server' => ['method' => 'POST', 'path' => 'applications/{uuid}/destinations', 'ability' => 'write', 'description' => 'attach an additional destination on another server (data: destination_uuid)'],+ 'remove_server' => ['method' => 'DELETE', 'path' => 'applications/{uuid}/destinations/{destination_uuid}', 'ability' => 'write', 'confirm' => true, 'description' => 'detach an additional destination'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Application UUID.',+ 'destination_uuid' => 'Destination UUID to detach (remove_server only).',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API. update: application fields; delete: delete_volumes, delete_connected_networks, delete_configurations, docker_cleanup; clone: destination_uuid, name, clone_volumes; move: environment_uuid; add_server: destination_uuid.';+ }+}diff --cc app/Mcp/Tools/ManageBackup.phpindex 244485fee5,0000000000..1a9441f693mode 100644,000000..100644--- a/app/Mcp/Tools/ManageBackup.php+++ b/app/Mcp/Tools/ManageBackup.php@@@ -1,39 -1,0 +1,39 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManageBackup extends RestActionTool+{+ protected string $name = 'manage_backup';+- protected string $description = 'Create, update, or delete a backup schedule of a database of the authenticated team, or delete one backup execution. Set data.backup_now=true on create or update to run a backup now. Requires write ability. Same validation and permissions as the REST API.';++ protected string $description = 'Create, update, or delete a backup schedule of a database of the authenticated team, or delete one backup execution. Set data.backup_now=true on create or update to run a backup now (requires deploy ability). Requires write ability. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [- 'create' => ['method' => 'POST', 'path' => 'databases/{uuid}/backups', 'ability' => 'write', 'description' => 'create a backup schedule (data: frequency, enabled, save_s3, s3_storage_uuid(s), retention fields, backup_now ...)'],- 'update' => ['method' => 'PATCH', 'path' => 'databases/{uuid}/backups/{scheduled_backup_uuid}', 'ability' => 'write', 'description' => 'update a backup schedule; data.backup_now=true runs a backup now'],++ 'create' => ['method' => 'POST', 'path' => 'databases/{uuid}/backups', 'ability' => 'write', 'description' => 'create a backup schedule (data: frequency, enabled, save_s3, s3_storage_uuid(s), retention fields, backup_now ...; backup_now needs deploy ability)'],++ 'update' => ['method' => 'PATCH', 'path' => 'databases/{uuid}/backups/{scheduled_backup_uuid}', 'ability' => 'write', 'description' => 'update a backup schedule; data.backup_now=true runs a backup now and needs deploy ability'],+ 'delete' => ['method' => 'DELETE', 'path' => 'databases/{uuid}/backups/{scheduled_backup_uuid}', 'ability' => 'write', 'confirm' => true, 'description' => 'delete a backup schedule and all its backup files (data.delete_s3=true also deletes S3 copies)'],+ 'delete_execution' => ['method' => 'DELETE', 'path' => 'databases/{uuid}/backups/{scheduled_backup_uuid}/executions/{execution_uuid}', 'ability' => 'write', 'confirm' => true, 'description' => 'delete one backup execution and its file (data.delete_s3=true also deletes the S3 copy)'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Database UUID.',+ 'scheduled_backup_uuid' => 'Backup schedule UUID (not needed for create).',+ 'execution_uuid' => 'Backup execution UUID (delete_execution only).',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API: frequency, enabled, save_s3, dump_all, backup_now, s3_storage_uuid, s3_storage_uuids, databases_to_backup, database_backup_retention_amount_locally, database_backup_retention_days_locally, database_backup_retention_max_storage_locally, database_backup_retention_amount_s3, database_backup_retention_days_s3, database_backup_retention_max_storage_s3, timeout, missing_backup_notification_days; delete_s3 for deletes.';+ }+}diff --cc app/Mcp/Tools/ManageDatabase.phpindex 3dadf67e26,0000000000..5e4c11308dmode 100644,000000..100644--- a/app/Mcp/Tools/ManageDatabase.php+++ b/app/Mcp/Tools/ManageDatabase.php@@@ -1,38 -1,0 +1,38 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManageDatabase extends RestActionTool+{+ protected string $name = 'manage_database';+- protected string $description = 'Update, delete, clone, move, or import a backup into a standalone database of the authenticated team. Requires write ability (an import from a server path also needs deploy). Same validation and permissions as the REST API.';++ protected string $description = 'Update, delete, clone, move, or import a backup into a standalone database of the authenticated team. Requires write ability; delete and import also need deploy, and so do instant_deploy, changing is_public, and clone_volumes. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [- 'update' => ['method' => 'PATCH', 'path' => 'databases/{uuid}', 'ability' => 'write', 'description' => 'update database settings (data: name, description, image, is_public, public_port, public_port_timeout, limits_*, type credentials and *_conf fields, redact_all_env_values_in_logs)'],- 'delete' => ['method' => 'DELETE', 'path' => 'databases/{uuid}', 'ability' => 'write', 'confirm' => true, 'description' => 'delete the database (data: delete_volumes, delete_connected_networks, delete_configurations, docker_cleanup; all default true)'],- 'clone' => ['method' => 'POST', 'path' => 'databases/{uuid}/clone', 'ability' => 'write', 'confirm' => true, 'description' => 'clone the database to a destination of the team (data: destination_uuid, name, clone_volumes; clone_volumes stops the source database while volumes are copied)'],++ 'update' => ['method' => 'PATCH', 'path' => 'databases/{uuid}', 'ability' => 'write', 'description' => 'update database settings (data: name, description, image, is_public, public_port, public_port_timeout, limits_*, type credentials and *_conf fields, redact_all_env_values_in_logs, instant_deploy; instant_deploy and changing is_public need deploy ability)'],++ 'delete' => ['method' => 'DELETE', 'path' => 'databases/{uuid}', 'ability' => 'deploy', 'confirm' => true, 'description' => 'delete the database (data: delete_volumes, delete_connected_networks, delete_configurations, docker_cleanup; all default true)'],++ 'clone' => ['method' => 'POST', 'path' => 'databases/{uuid}/clone', 'ability' => 'write', 'confirm' => true, 'description' => 'clone the database to a destination of the team (data: destination_uuid, name, clone_volumes; clone_volumes stops the source database while volumes are copied and needs deploy ability)'],+ 'move' => ['method' => 'POST', 'path' => 'databases/{uuid}/move', 'ability' => 'write', 'confirm' => true, 'description' => 'move the database to another environment of the team (data: environment_uuid)'],- 'import' => ['method' => 'POST', 'path' => 'databases/{uuid}/imports', 'ability' => 'write', 'confirm' => true, 'description' => 'import a backup into the database, can overwrite data (data: source s3 | server, s3_storage_uuid, path, dump_all, replace_existing, keep_owners, restore_mysql_users, sqlite_database); check progress with get_database_import'],++ 'import' => ['method' => 'POST', 'path' => 'databases/{uuid}/imports', 'ability' => 'deploy', 'confirm' => true, 'description' => 'import a backup into the database, can overwrite data (data: source s3 | server, s3_storage_uuid, path, dump_all, replace_existing, keep_owners, restore_mysql_users, sqlite_database); check progress with get_database_import'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Database UUID.',+ ];+ }++ protected function dataDescription(): string+ {- return 'Request body, same fields as the REST API (see the action descriptions). File uploads are not supported: import only from an S3 storage of the team (source=s3, s3_storage_uuid, path) or a server path (source=server, path; needs deploy ability).';++ return 'Request body, same fields as the REST API (see the action descriptions). File uploads are not supported: import only from an S3 storage of the team (source=s3, s3_storage_uuid, path) or a server path (source=server, path).';+ }+}diff --cc app/Mcp/Tools/ManagePreview.phpindex 0f4b92b339,0000000000..e1f6700e61mode 100644,000000..100644--- a/app/Mcp/Tools/ManagePreview.php+++ b/app/Mcp/Tools/ManagePreview.php@@@ -1,37 -1,0 +1,37 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManagePreview extends RestActionTool+{+ protected string $name = 'manage_preview';+- protected string $description = 'Create (and deploy), update the domains of, or delete a pull request preview deployment of an application of the authenticated team. create requires deploy ability, update and delete require write. Same validation and permissions as the REST API.';++ protected string $description = 'Create (and deploy), update the domains of, or delete a pull request preview deployment of an application of the authenticated team. create and delete require deploy ability, update requires write. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [+ 'create' => ['method' => 'POST', 'path' => 'applications/{uuid}/previews', 'ability' => 'deploy', 'description' => 'open or redeploy a preview (data: pull_request_id, pull_request_html_url, git_type, commit, docker_tag, force, instant_deploy)'],+ 'update' => ['method' => 'PATCH', 'path' => 'applications/{uuid}/previews/{pull_request_id}', 'ability' => 'write', 'description' => 'replace preview domains (data: domains, or docker_compose_domains for compose apps, force_domain_override)'],- 'delete' => ['method' => 'DELETE', 'path' => 'applications/{uuid}/previews/{pull_request_id}', 'ability' => 'write', 'confirm' => true, 'description' => 'delete the preview and its containers'],++ 'delete' => ['method' => 'DELETE', 'path' => 'applications/{uuid}/previews/{pull_request_id}', 'ability' => 'deploy', 'confirm' => true, 'description' => 'delete the preview and its containers'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Application UUID.',+ 'pull_request_id' => 'Pull request ID of the preview (update and delete).',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API. create: pull_request_id (required), pull_request_html_url, git_type (github | gitlab | gitea | bitbucket), commit, docker_tag (Docker image apps), force, instant_deploy; update: domains or docker_compose_domains, force_domain_override.';+ }+}diff --cc app/Mcp/Tools/ManageProxy.phpindex 64cb1faa40,0000000000..336ed495edmode 100644,000000..100644--- a/app/Mcp/Tools/ManageProxy.php+++ b/app/Mcp/Tools/ManageProxy.php@@@ -1,37 -1,0 +1,37 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManageProxy extends RestActionTool+{+ protected string $name = 'manage_proxy';+- protected string $description = 'Read or change the proxy of a server of the authenticated team: settings, configuration file, restart. Requires read ability for get, write ability for changes. Same validation and permissions as the REST API.';++ protected string $description = 'Read or change the proxy of a server of the authenticated team: settings, configuration file, restart. Requires read ability for get, write ability for update (changing proxy_type also needs deploy), deploy ability for set_configuration and restart. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [+ 'get' => ['method' => 'GET', 'path' => 'servers/{uuid}/proxy', 'ability' => 'read', 'description' => 'proxy type, status, and settings (the configuration file only with read:sensitive)'],- 'update' => ['method' => 'PATCH', 'path' => 'servers/{uuid}/proxy', 'ability' => 'write', 'confirm' => true, 'description' => 'change proxy settings (data: proxy_type, redirect_enabled, redirect_url, generate_exact_labels, traefik_certificate_resolver)'],- 'set_configuration' => ['method' => 'PUT', 'path' => 'servers/{uuid}/proxy/configuration', 'ability' => 'write', 'confirm' => true, 'description' => 'replace the proxy configuration file (data: configuration, plain or base64)'],- 'restart' => ['method' => 'POST', 'path' => 'servers/{uuid}/proxy/restart', 'ability' => 'write', 'confirm' => true, 'description' => 'restart the proxy; routed apps are briefly unreachable'],++ 'update' => ['method' => 'PATCH', 'path' => 'servers/{uuid}/proxy', 'ability' => 'write', 'confirm' => true, 'description' => 'change proxy settings (data: proxy_type, redirect_enabled, redirect_url, generate_exact_labels, traefik_certificate_resolver; changing proxy_type needs deploy ability)'],++ 'set_configuration' => ['method' => 'PUT', 'path' => 'servers/{uuid}/proxy/configuration', 'ability' => 'deploy', 'confirm' => true, 'description' => 'replace the proxy configuration file (data: configuration, plain or base64)'],++ 'restart' => ['method' => 'POST', 'path' => 'servers/{uuid}/proxy/restart', 'ability' => 'deploy', 'confirm' => true, 'description' => 'restart the proxy; routed apps are briefly unreachable'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Server UUID.',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API: proxy_type, redirect_enabled, redirect_url, generate_exact_labels, traefik_certificate_resolver (update); configuration (set_configuration).';+ }+}diff --cc app/Mcp/Tools/ManageRegistry.phpindex 59749acbcd,0000000000..77b5457954mode 100644,000000..100644--- a/app/Mcp/Tools/ManageRegistry.php+++ b/app/Mcp/Tools/ManageRegistry.php@@@ -1,38 -1,0 +1,38 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManageRegistry extends RestActionTool+{+ protected string $name = 'manage_registry';+- protected string $description = 'List, add, check, or remove Docker registry logins on a server of the authenticated team. Passwords are never returned. Requires read:sensitive ability for list, write ability for changes. Same validation and permissions as the REST API.';++ protected string $description = 'List, add, check, or remove Docker registry logins on a server of the authenticated team. Passwords are never returned. Requires read:sensitive ability for list, deploy ability for create, write ability for check and delete. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [+ 'list' => ['method' => 'GET', 'path' => 'servers/{uuid}/registries', 'ability' => 'read:sensitive', 'description' => 'registry logins on the server (registry and username only)'],- 'create' => ['method' => 'POST', 'path' => 'servers/{uuid}/registries', 'ability' => 'write', 'description' => 'log in to a registry on the server (data: registry, username, password)'],++ 'create' => ['method' => 'POST', 'path' => 'servers/{uuid}/registries', 'ability' => 'deploy', 'description' => 'log in to a registry on the server (data: registry, username, password)'],+ 'check' => ['method' => 'POST', 'path' => 'servers/{uuid}/registries/{registry}/check', 'ability' => 'write', 'description' => 'check that a registry login works'],+ 'delete' => ['method' => 'DELETE', 'path' => 'servers/{uuid}/registries/{registry}', 'ability' => 'write', 'confirm' => true, 'description' => 'log out of a registry; private image pulls can fail afterwards'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Server UUID.',+ 'registry' => 'Registry host, for example ghcr.io (check and delete). Hosts with a port are not supported here.',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API: registry, username, password (create).';+ }+}diff --cc app/Mcp/Tools/ManageScheduledTask.phpindex d5e0527404,0000000000..e476b3f12amode 100644,000000..100644--- a/app/Mcp/Tools/ManageScheduledTask.php+++ b/app/Mcp/Tools/ManageScheduledTask.php@@@ -1,50 -1,0 +1,50 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManageScheduledTask extends RestActionTool+{+ protected string $name = 'manage_scheduled_task';+- protected string $description = 'Create, update, delete, or run now a scheduled task of an application or service of the authenticated team. Requires write ability. Same validation and permissions as the REST API.';++ protected string $description = 'Create, update, delete, or run now a scheduled task of an application or service of the authenticated team. Requires write ability; run now and an enabled task also require deploy. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [+ 'create' => ['method' => 'POST', 'paths' => [+ 'application' => 'applications/{uuid}/scheduled-tasks',+ 'service' => 'services/{uuid}/scheduled-tasks',- ], 'ability' => 'write', 'description' => 'create a scheduled task (data: name, command, frequency, container, timeout, enabled)'],++ ], 'ability' => 'write', 'description' => 'create a scheduled task (data: name, command, frequency, container, timeout, enabled; an enabled task needs deploy ability)'],+ 'update' => ['method' => 'PATCH', 'paths' => [+ 'application' => 'applications/{uuid}/scheduled-tasks/{task_uuid}',+ 'service' => 'services/{uuid}/scheduled-tasks/{task_uuid}',- ], 'ability' => 'write', 'description' => 'update a scheduled task (data: any of name, command, frequency, container, timeout, enabled)'],++ ], 'ability' => 'write', 'description' => 'update a scheduled task (data: any of name, command, frequency, container, timeout, enabled; an enabled task needs deploy ability)'],+ 'delete' => ['method' => 'DELETE', 'paths' => [+ 'application' => 'applications/{uuid}/scheduled-tasks/{task_uuid}',+ 'service' => 'services/{uuid}/scheduled-tasks/{task_uuid}',+ ], 'ability' => 'write', 'confirm' => true, 'description' => 'delete a scheduled task'],+ 'execute' => ['method' => 'POST', 'paths' => [+ 'application' => 'applications/{uuid}/scheduled-tasks/{task_uuid}/execute',+ 'service' => 'services/{uuid}/scheduled-tasks/{task_uuid}/execute',- ], 'ability' => 'write', 'confirm' => true, 'description' => 'run the task command now'],++ ], 'ability' => 'deploy', 'confirm' => true, 'description' => 'run the task command now'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Application or service UUID.',+ 'task_uuid' => 'Scheduled task UUID (not needed for create).',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API: name, command, frequency (cron or every_minute, hourly, daily, weekly, monthly, yearly), container, timeout (seconds), enabled.';+ }+}diff --cc app/Mcp/Tools/ManageServer.phpindex 2a036e07f9,0000000000..7680d1c41bmode 100644,000000..100644--- a/app/Mcp/Tools/ManageServer.php+++ b/app/Mcp/Tools/ManageServer.php@@@ -1,37 -1,0 +1,37 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManageServer extends RestActionTool+{+ protected string $name = 'manage_server';+- protected string $description = 'Add, update, delete, or validate a server of the authenticated team. Requires write ability. Same validation and permissions as the REST API.';++ protected string $description = 'Add, update, delete, or validate a server of the authenticated team. Requires write ability; changing proxy_type, deleting with force or delete_from_provider, and validating with install also need deploy. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [+ 'create' => ['method' => 'POST', 'path' => 'servers', 'ability' => 'write', 'description' => 'add a server (data: ip, private_key_uuid, name, description, port, user, server_role, proxy_type, instant_validate)'],- 'update' => ['method' => 'PATCH', 'path' => 'servers/{uuid}', 'ability' => 'write', 'description' => 'update a server (data: name, description, ip, port, user, private_key_uuid, server_role, proxy_type, concurrent_builds, dynamic_timeout, deployment_queue_limit, connection_timeout, is_terminal_enabled, server_disk_usage_*)'],++ 'update' => ['method' => 'PATCH', 'path' => 'servers/{uuid}', 'ability' => 'write', 'description' => 'update a server (data: name, description, ip, port, user, private_key_uuid, server_role, proxy_type, concurrent_builds, dynamic_timeout, deployment_queue_limit, connection_timeout, is_terminal_enabled, server_disk_usage_*; changing proxy_type needs deploy ability)'],+ 'delete' => ['method' => 'DELETE', 'path' => 'servers/{uuid}', 'ability' => 'write', 'confirm' => true, 'description' => 'delete a server without resources (the Coolify host cannot be deleted)'],- 'validate' => ['method' => 'POST', 'path' => 'servers/{uuid}/validate', 'ability' => 'write', 'description' => 'start a server validation (data: install=true also installs Docker)'],++ 'validate' => ['method' => 'POST', 'path' => 'servers/{uuid}/validate', 'ability' => 'write', 'description' => 'start a server validation (data: install=true also installs Docker and needs deploy ability)'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Server UUID (not needed for create).',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API: name, description, ip, port, user, private_key_uuid, server_role (deployment|build|both), proxy_type, instant_validate, install (validate only).';+ }+}diff --cc app/Mcp/Tools/ManageService.phpindex bdbc6c0050,0000000000..efa6d99fddmode 100644,000000..100644--- a/app/Mcp/Tools/ManageService.php+++ b/app/Mcp/Tools/ManageService.php@@@ -1,42 -1,0 +1,42 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManageService extends RestActionTool+{+ protected string $name = 'manage_service';+- protected string $description = 'Update, delete, clone, or move a service of the authenticated team, update one of its applications or databases, or import a backup into a service database. Requires write ability (instant_deploy and an import from a server path also need deploy). Same validation and permissions as the REST API.';++ protected string $description = 'Update, delete, clone, or move a service of the authenticated team, update one of its applications or databases, or import a backup into a service database. Requires write ability; delete and import_database also need deploy, and so do instant_deploy, changing is_public of a service database, and clone_volumes. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [- 'update' => ['method' => 'PATCH', 'path' => 'services/{uuid}', 'ability' => 'write', 'description' => 'update the service (data: name, description, docker_compose_raw base64, connect_to_docker_network, urls, force_domain_override, is_container_label_escape_enabled, redact_all_env_values_in_logs, instant_deploy)'],- 'delete' => ['method' => 'DELETE', 'path' => 'services/{uuid}', 'ability' => 'write', 'confirm' => true, 'description' => 'delete the service (data: delete_volumes, delete_connected_networks, delete_configurations, docker_cleanup, delete_from_coolify_only)'],- 'clone' => ['method' => 'POST', 'path' => 'services/{uuid}/clone', 'ability' => 'write', 'confirm' => true, 'description' => 'clone the service to a destination of the team (data: destination_uuid, name, clone_volumes; clone_volumes stops the source service while volumes are copied)'],++ 'update' => ['method' => 'PATCH', 'path' => 'services/{uuid}', 'ability' => 'write', 'description' => 'update the service (data: name, description, docker_compose_raw base64, connect_to_docker_network, urls, force_domain_override, is_container_label_escape_enabled, redact_all_env_values_in_logs, instant_deploy; instant_deploy needs deploy ability)'],++ 'delete' => ['method' => 'DELETE', 'path' => 'services/{uuid}', 'ability' => 'deploy', 'confirm' => true, 'description' => 'delete the service (data: delete_volumes, delete_connected_networks, delete_configurations, docker_cleanup, delete_from_coolify_only)'],++ 'clone' => ['method' => 'POST', 'path' => 'services/{uuid}/clone', 'ability' => 'write', 'confirm' => true, 'description' => 'clone the service to a destination of the team (data: destination_uuid, name, clone_volumes; clone_volumes stops the source service while volumes are copied and needs deploy ability)'],+ 'move' => ['method' => 'POST', 'path' => 'services/{uuid}/move', 'ability' => 'write', 'confirm' => true, 'description' => 'move the service to another environment of the team (data: environment_uuid)'],+ 'update_application' => ['method' => 'PATCH', 'path' => 'services/{uuid}/applications/{app_uuid}', 'ability' => 'write', 'description' => 'update a service application (data: url, noindex_domains, human_name, description, image, exclude_from_status, is_log_drain_enabled, is_gzip_enabled, traefik_certificate_resolver, is_stripprefix_enabled, is_force_https_enabled, max_restart_count)'],- 'update_database' => ['method' => 'PATCH', 'path' => 'services/{uuid}/databases/{database_uuid}', 'ability' => 'write', 'description' => 'update a service database (data: human_name, description, image, exclude_from_status, is_log_drain_enabled, is_public, public_port, public_port_timeout)'],- 'import_database' => ['method' => 'POST', 'path' => 'services/{uuid}/databases/{database_uuid}/imports', 'ability' => 'write', 'confirm' => true, 'description' => 'import a backup into a service database, can overwrite data (data: source s3 | server, s3_storage_uuid, path, dump_all, replace_existing, keep_owners, restore_mysql_users); check progress with get_database_import'],++ 'update_database' => ['method' => 'PATCH', 'path' => 'services/{uuid}/databases/{database_uuid}', 'ability' => 'write', 'description' => 'update a service database (data: human_name, description, image, exclude_from_status, is_log_drain_enabled, is_public, public_port, public_port_timeout; changing is_public needs deploy ability)'],++ 'import_database' => ['method' => 'POST', 'path' => 'services/{uuid}/databases/{database_uuid}/imports', 'ability' => 'deploy', 'confirm' => true, 'description' => 'import a backup into a service database, can overwrite data (data: source s3 | server, s3_storage_uuid, path, dump_all, replace_existing, keep_owners, restore_mysql_users); check progress with get_database_import'],+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Service UUID.',+ 'app_uuid' => 'Service application UUID (update_application).',+ 'database_uuid' => 'Service database UUID (update_database, import_database).',+ ];+ }++ protected function dataDescription(): string+ {- return 'Request body, same fields as the REST API (see the action descriptions). File uploads are not supported: import only from an S3 storage of the team (source=s3, s3_storage_uuid, path) or a server path (source=server, path; needs deploy ability).';++ return 'Request body, same fields as the REST API (see the action descriptions). File uploads are not supported: import only from an S3 storage of the team (source=s3, s3_storage_uuid, path) or a server path (source=server, path).';+ }+}diff --cc app/Mcp/Tools/ManageStorage.phpindex d59d95ca14,0000000000..5fdf754964mode 100644,000000..100644--- a/app/Mcp/Tools/ManageStorage.php+++ b/app/Mcp/Tools/ManageStorage.php@@@ -1,52 -1,0 +1,52 @@@+<?php++namespace App\Mcp\Tools;++use Laravel\Mcp\Server\Tools\Annotations\IsDestructive;+use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;++#[IsReadOnly(false)]+#[IsDestructive]+class ManageStorage extends RestActionTool+{+ protected string $name = 'manage_storage';+- protected string $description = 'Create, update, or delete a persistent volume or file storage of an application, database, or service of the authenticated team, and set, remove, or run its volume backup schedule. Requires write ability. Same validation and permissions as the REST API.';++ protected string $description = 'Create, update, or delete a persistent volume or file storage of an application, database, or service of the authenticated team, and set, remove, or run its volume backup schedule. Requires write ability; run_backup also requires deploy, and so do file content, mounts outside the resource directory, and stop_during_backup. Same validation and permissions as the REST API.';++ protected function actions(): array+ {+ return [- 'create' => ['method' => 'POST', 'paths' => $this->paths('storages'), 'ability' => 'write', 'description' => 'create a storage (data: type persistent|file, name, mount_path, content, is_directory, is_host_file, fs_path; services also resource_uuid)'],- 'update' => ['method' => 'PATCH', 'paths' => $this->paths('storages'), 'ability' => 'write', 'description' => 'update a storage (data: uuid of the storage, type, name, mount_path, content, is_preview_suffix_enabled)'],++ 'create' => ['method' => 'POST', 'paths' => $this->paths('storages'), 'ability' => 'write', 'description' => 'create a storage (data: type persistent|file, name, mount_path, content, is_directory, is_host_file, fs_path; services also resource_uuid; file content and an fs_path outside the resource directory need deploy ability)'],++ 'update' => ['method' => 'PATCH', 'paths' => $this->paths('storages'), 'ability' => 'write', 'description' => 'update a storage (data: uuid of the storage, type, name, mount_path, content, is_preview_suffix_enabled; content of a file outside the resource directory needs deploy ability)'],+ 'delete' => ['method' => 'DELETE', 'paths' => $this->paths('storages/{storage_uuid}'), 'ability' => 'write', 'confirm' => true, 'description' => 'delete a storage'],- 'set_backup' => ['method' => 'PUT', 'paths' => $this->paths('storages/{storage_uuid}/backups'), 'ability' => 'write', 'description' => 'create or replace the volume backup schedule (data: frequency, enabled, save_s3, s3_storage_uuid(s), stop_during_backup, retention fields ...)'],++ 'set_backup' => ['method' => 'PUT', 'paths' => $this->paths('storages/{storage_uuid}/backups'), 'ability' => 'write', 'description' => 'create or replace the volume backup schedule (data: frequency, enabled, save_s3, s3_storage_uuid(s), stop_during_backup, retention fields ...; stop_during_backup needs deploy ability)'],+ 'remove_backup' => ['method' => 'DELETE', 'paths' => $this->paths('storages/{storage_uuid}/backups'), 'ability' => 'write', 'confirm' => true, 'description' => 'delete the volume backup schedule and its local and S3 archives'],- 'run_backup' => ['method' => 'POST', 'paths' => $this->paths('storages/{storage_uuid}/backups/run'), 'ability' => 'write', 'confirm' => true, 'description' => 'run the volume backup now (can stop the resource when stop_during_backup is set)'],++ 'run_backup' => ['method' => 'POST', 'paths' => $this->paths('storages/{storage_uuid}/backups/run'), 'ability' => 'deploy', 'confirm' => true, 'description' => 'run the volume backup now (can stop the resource when stop_during_backup is set)'],+ ];+ }++ /**+ * @return array<string, string>+ */+ private function paths(string $suffix): array+ {+ return [+ 'application' => "applications/{uuid}/{$suffix}",+ 'database' => "databases/{uuid}/{$suffix}",+ 'service' => "services/{uuid}/{$suffix}",+ ];+ }++ protected function pathParams(): array+ {+ return [+ 'uuid' => 'Application, database, or service UUID.',+ 'storage_uuid' => 'Storage UUID (delete and backup actions).',+ ];+ }++ protected function dataDescription(): string+ {+ return 'Request body, same fields as the REST API. Storage: type, name, mount_path, content, is_directory, is_host_file, fs_path, resource_uuid (service), uuid (update). Backup: frequency, enabled, save_s3, disable_local_backup, stop_during_backup, s3_storage_uuid, s3_storage_uuids, retention_amount_locally, retention_days_locally, retention_max_storage_locally, retention_amount_s3, retention_days_s3, retention_max_storage_s3, timeout, missing_backup_notification_days.';+ }+}diff --cc app/Models/ApplicationDeploymentQueue.phpindex 2979cab170,e25b032630..3af70a5610--- a/app/Models/ApplicationDeploymentQueue.php+++ b/app/Models/ApplicationDeploymentQueue.php@@@ -4,7 -4,7 +4,8 @@@ namespace App\Modelsuse App\Casts\EncryptedArrayCast;use App\Enums\ApplicationDeploymentStatus;+use App\Services\Security\SensitiveDataRedactor;+ use Illuminate\Database\Eloquent\Builder;use Illuminate\Database\Eloquent\Casts\Attribute;use Illuminate\Database\Eloquent\Model;use Illuminate\Support\Carbon;diff --cc openapi.jsonindex 70c4ec8c47,28c0ed18db..07caa78eb6--- a/openapi.json+++ b/openapi.json@@@ -10941,9 -10764,10 +10988,10 @@@"maxLength": 255},"network": {+ "description": "Name of a new Docker network. Must not be bridge, host, none, or a network that already exists on the server.","type": "string",- "maxLength": 255,- "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._-]*$"+ "pattern": "^[a-zA-Z0-9][a-zA-Z0-9._-]*$",+ "maxLength": 255},"type": {"type": "string",diff --cc openapi.yamlindex 7d82b2ef23,71c6507b97..eebac91795--- a/openapi.yaml+++ b/openapi.yaml@@@ -4915,14 -4783,10 +4942,14 @@@ pathsdescription: 'Whether data is saved in s3 or not's3_storage_uuid:type: string- description: 'S3 storage UUID'+ description: 'Primary S3 storage UUID. Sent without s3_storage_uuids, it selects this storage as the only destination; when it is already a destination, it becomes the primary destination and the other destinations stay.'+ s3_storage_uuids:+ type: array+ items: { type: string }+ description: 'UUIDs of every S3 storage the backup is uploaded to. Replaces the current destinations. When s3_storage_uuid is also sent, it must be in this list and becomes the primary destination; otherwise the first entry is the primary destination.'backup_now:type: boolean- description: 'Whether to take a backup now or not'+ description: 'Whether to take a backup now or not. Needs a token with the deploy permission.'enabled:type: booleandescription: 'Whether the backup is enabled or not'@@@ -7142,9 -7011,10 +7174,10 @@@type: stringmaxLength: 255network:+ description: 'Name of a new Docker network. Must not be bridge, host, none, or a network that already exists on the server.'type: string- maxLength: 255pattern: '^[a-zA-Z0-9][a-zA-Z0-9._-]*$'+ maxLength: 255type:type: stringenum: [standalone, swarm]diff --cc routes/api.phpindex f985b94332,bfbb2d29fa..2b0e8ff02d--- a/routes/api.php+++ b/routes/api.php@@@ -200,12 -202,12 +200,12 @@@ Route::group(Route::get('/servers/{uuid}/proxy', [ServerProxyController::class, 'show'])->middleware(['api.ability:read']);Route::patch('/servers/{uuid}/proxy', [ServerProxyController::class, 'update'])->middleware(['api.ability:write']);Route::put('/servers/{uuid}/proxy/configuration', [ServerProxyController::class, 'saveConfiguration'])->middleware(['api.ability:write']);- Route::post('/servers/{uuid}/proxy/restart', [ServerProxyController::class, 'restart'])->middleware(['api.ability:write']);+ Route::post('/servers/{uuid}/proxy/restart', [ServerProxyController::class, 'restart'])->middleware(['api.ability:deploy']);Route::post('/servers', [ServersController::class, 'create_server'])->middleware(['api.ability:write']);+ Route::get('/servers/import/check', [ServerTransferController::class, 'check'])->middleware(['api.ability:write']);- Route::post('/servers/import', [ServerTransferController::class, 'import'])->middleware(['api.ability:write']);+ Route::post('/servers/import', [ServerTransferController::class, 'import'])->middleware(['api.ability:write', 'api.ability:deploy']);- Route::get('/servers/{uuid}/export', [ServerTransferController::class, 'export'])->middleware(['api.ability:read']);- Route::post('/servers/{uuid}/export/mailbox', [ServerTransferController::class, 'writeMailbox'])->middleware(['api.ability:write']);+ Route::get('/servers/{uuid}/transfer', [ServerTransferController::class, 'status'])->middleware(['api.ability:read,write']);Route::post('/servers/{uuid}/transfer/complete', [ServerTransferController::class, 'complete'])->middleware(['api.ability:write']);Route::post('/servers/{uuid}/migrate', [ServerTransferController::class, 'migrate'])->middleware(['api.ability:write']);Route::patch('/servers/{uuid}', [ServersController::class, 'update_server'])->middleware(['api.ability:write']);diff --cc tests/Feature/HostingerApiTest.phpindex 08454fb5a9,0000000000..3351b2dd10mode 100644,000000..100644--- a/tests/Feature/HostingerApiTest.php+++ b/tests/Feature/HostingerApiTest.php@@@ -1,324 -1,0 +1,324 @@@+<?php++use App\Models\CloudProviderToken;+use App\Models\InstanceSettings;+use App\Models\PrivateKey;+use App\Models\Team;+use App\Models\User;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Once;++uses(RefreshDatabase::class);++beforeEach(function () {+ Http::preventStrayRequests();++ InstanceSettings::query()->whereKey(0)->delete();+ InstanceSettings::unguarded(fn () => InstanceSettings::query()->create([+ 'id' => 0,+ 'is_api_enabled' => true,+ ]));+ Once::flush();++ $this->team = Team::factory()->create();+ $this->user = User::factory()->create();+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);+ session(['currentTeam' => $this->team]);++ $this->bearerToken = $this->user->createToken('test-token', ['*'])->plainTextToken;+ $this->hostingerToken = CloudProviderToken::factory()->create([+ 'team_id' => $this->team->id,+ 'provider' => 'hostinger',+ 'token' => 'hostinger-api-token',+ ]);+ $this->privateKey = PrivateKey::factory()->create(['team_id' => $this->team->id]);+});++it('gets Hostinger data centers', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/data-centers' => Http::response([+ ['id' => 19, 'city' => 'Amsterdam', 'location' => 'nl'],+ ]),+ ]);++ $this->withToken($this->bearerToken)+ ->getJson('/api/v1/hostinger/data-centers?cloud_provider_token_id='.$this->hostingerToken->uuid)+ ->assertSuccessful()+ ->assertJsonFragment(['id' => 19, 'city' => 'Amsterdam']);+});++it('gets Hostinger SSH keys and post-install scripts', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/public-keys' => Http::response([+ 'data' => [['id' => 42, 'name' => 'Operations']],+ ]),+ 'https://developers.hostinger.com/api/vps/v1/post-install-scripts' => Http::response([+ 'data' => [['id' => 73, 'name' => 'Bootstrap Coolify']],+ ]),+ ]);++ $query = '?cloud_provider_token_id='.$this->hostingerToken->uuid;++ $this->withToken($this->bearerToken)+ ->getJson('/api/v1/hostinger/ssh-keys'.$query)+ ->assertSuccessful()+ ->assertJsonFragment(['id' => 42, 'name' => 'Operations']);++ $this->withToken($this->bearerToken)+ ->getJson('/api/v1/hostinger/post-install-scripts'.$query)+ ->assertSuccessful()+ ->assertJsonFragment(['id' => 73, 'name' => 'Bootstrap Coolify']);+});++it('gets only Hostinger KVM plans through the API', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/billing/v1/catalog*' => Http::response([+ ['id' => 'hostingercom-vps-kvm1', 'name' => 'KVM 1', 'prices' => []],+ ['id' => 'hostingercom-vps-kvmminecraftalex', 'name' => 'Game Panel 1', 'prices' => []],+ ]),+ ]);++ $this->withToken($this->bearerToken)+ ->getJson('/api/v1/hostinger/catalog?cloud_provider_token_id='.$this->hostingerToken->uuid)+ ->assertSuccessful()+ ->assertJsonCount(1)+ ->assertJsonFragment(['id' => 'hostingercom-vps-kvm1'])+ ->assertJsonMissing(['id' => 'hostingercom-vps-kvmminecraftalex']);+});++it('returns 403 with the Hostinger message when Hostinger denies a provider list', function (int $hostingerStatus) {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/post-install-scripts' => Http::response([+ 'message' => '[VPS:2000] Unauthorized',+ ], $hostingerStatus),+ ]);++ $this->withToken($this->bearerToken)+ ->getJson('/api/v1/hostinger/post-install-scripts?cloud_provider_token_id='.$this->hostingerToken->uuid)+ ->assertForbidden()+ ->assertExactJson(['message' => 'Hostinger denied access to post-install scripts: [VPS:2000] Unauthorized']);+})->with([401, 403]);++it('returns 429 when Hostinger rate limits a provider list', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/templates' => Http::response([+ 'message' => 'Too many requests.',+ ], 429, ['Retry-After' => '30']),+ ]);++ $this->withToken($this->bearerToken)+ ->getJson('/api/v1/hostinger/templates?cloud_provider_token_id='.$this->hostingerToken->uuid)+ ->assertStatus(429)+ ->assertHeader('Retry-After', '30')+ ->assertExactJson(['message' => 'Rate limit exceeded. Please try again later.']);+});++it('returns a generic error when a Hostinger provider list fails', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/data-centers' => Http::response([+ 'message' => 'Invalid request',+ ], 422),+ ]);++ $this->withToken($this->bearerToken)+ ->getJson('/api/v1/hostinger/data-centers?cloud_provider_token_id='.$this->hostingerToken->uuid)+ ->assertServerError()+ ->assertExactJson(['message' => 'Failed to fetch Hostinger data centers.']);+});++it('creates a Hostinger VPS server through the API', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/virtual-machines' => Http::response([+ 'order' => ['id' => 2957086, 'status' => 'completed'],+ 'virtual_machine' => [+ 'id' => 17923,+ 'state' => 'creating',+ 'ipv4' => [['address' => '203.0.113.10']],+ ],+ ]),+ ]);++ $this->withToken($this->bearerToken)+ ->postJson('/api/v1/servers/hostinger', [+ 'cloud_provider_token_id' => $this->hostingerToken->uuid,+ 'item_id' => 'hostingercom-vps-kvm2-usd-1m',+ 'data_center_id' => 19,+ 'template_id' => 1130,+ 'name' => 'api-hostinger.example.com',+ 'private_key_uuid' => $this->privateKey->uuid,+ 'enable_backups' => true,+ ])+ ->assertCreated()+ ->assertJsonFragment([+ 'hostinger_virtual_machine_id' => 17923,+ 'ip' => '203.0.113.10',+ ]);++ $this->assertDatabaseHas('servers', [+ 'team_id' => $this->team->id,+ 'hostinger_virtual_machine_id' => 17923,+ 'ip' => '203.0.113.10',+ ]);++ Http::assertSent(fn ($request) => $request->method() === 'POST'+ && $request->url() === 'https://developers.hostinger.com/api/vps/v1/virtual-machines'+ && $request['setup']['enable_backups'] === true);+});++it('turns paid Hostinger backups off when the API request does not enable them', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/virtual-machines' => Http::response([+ 'virtual_machine' => [+ 'id' => 17923,+ 'state' => 'creating',+ 'ipv4' => [['address' => '203.0.113.10']],+ ],+ ]),+ ]);++ $this->withToken($this->bearerToken)+ ->postJson('/api/v1/servers/hostinger', [+ 'cloud_provider_token_uuid' => $this->hostingerToken->uuid,+ 'item_id' => 'hostingercom-vps-kvm1-usd-1m',+ 'data_center_id' => 19,+ 'template_id' => 1130,+ 'private_key_uuid' => $this->privateKey->uuid,+ ])+ ->assertCreated();++ Http::assertSent(fn ($request) => $request->method() === 'POST'+ && $request->url() === 'https://developers.hostinger.com/api/vps/v1/virtual-machines'+ && $request['setup']['enable_backups'] === false);+});++it('requires the deploy ability to run a post-install script or add SSH keys on a Hostinger VPS', function (array $extra) {+ Http::fake();+ $writeToken = $this->user->createToken('write-token', ['read', 'write'])->plainTextToken;++ $this->withToken($writeToken)+ ->postJson('/api/v1/servers/hostinger', [+ 'cloud_provider_token_uuid' => $this->hostingerToken->uuid,+ 'item_id' => 'hostingercom-vps-kvm1-usd-1m',+ 'data_center_id' => 19,+ 'template_id' => 1130,+ 'private_key_uuid' => $this->privateKey->uuid,+ ...$extra,+ ])+ ->assertForbidden()- ->assertJsonFragment(['message' => 'Missing required permissions: deploy']);++ ->assertJsonPath('message', fn (string $message) => str_starts_with($message, 'Missing required permissions: deploy.'));++ Http::assertNothingSent();+ $this->assertDatabaseMissing('servers', ['team_id' => $this->team->id]);+})->with([+ 'post-install script' => [['post_install_script_id' => 73]],+ 'extra SSH keys' => [['public_key_ids' => [42]]],+]);++it('lets a deploy token run a post-install script on a Hostinger VPS', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/virtual-machines' => Http::response([+ 'virtual_machine' => [+ 'id' => 17923,+ 'state' => 'creating',+ 'ipv4' => [['address' => '203.0.113.10']],+ ],+ ]),+ ]);+ $deployToken = $this->user->createToken('deploy-token', ['read', 'write', 'deploy'])->plainTextToken;++ $this->withToken($deployToken)+ ->postJson('/api/v1/servers/hostinger', [+ 'cloud_provider_token_uuid' => $this->hostingerToken->uuid,+ 'item_id' => 'hostingercom-vps-kvm1-usd-1m',+ 'data_center_id' => 19,+ 'template_id' => 1130,+ 'private_key_uuid' => $this->privateKey->uuid,+ 'post_install_script_id' => 73,+ ])+ ->assertCreated();++ Http::assertSent(fn ($request) => $request->method() === 'POST'+ && $request->url() === 'https://developers.hostinger.com/api/vps/v1/virtual-machines'+ && $request['setup']['post_install_script_id'] === 73);+});++it('keeps a charged Hostinger VPS when the purchase returns an error through the API', function () {+ $listRequests = 0;+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/virtual-machines/2008976/setup' => Http::response([+ 'id' => 2008976,+ 'state' => 'creating',+ 'ipv4' => [['address' => '72.61.180.163']],+ ]),+ 'https://developers.hostinger.com/api/vps/v1/virtual-machines' => function ($request) use (&$listRequests) {+ if ($request->method() === 'POST') {+ return Http::response(['message' => '[VPS:2004] Wrong hostname FQDN format'], 422);+ }++ return Http::response($listRequests++ === 0 ? [] : [['id' => 2008976, 'state' => 'initial']]);+ },+ ]);++ $this->withToken($this->bearerToken)+ ->postJson('/api/v1/servers/hostinger', [+ 'cloud_provider_token_id' => $this->hostingerToken->uuid,+ 'item_id' => 'hostingercom-vps-kvm1-usd-1m',+ 'data_center_id' => 19,+ 'template_id' => 1077,+ 'private_key_uuid' => $this->privateKey->uuid,+ ])+ ->assertCreated()+ ->assertJsonFragment([+ 'hostinger_virtual_machine_id' => 2008976,+ 'ip' => '72.61.180.163',+ ]);++ $this->assertDatabaseHas('servers', [+ 'team_id' => $this->team->id,+ 'hostinger_virtual_machine_id' => 2008976,+ 'ip' => '72.61.180.163',+ ]);+});++it('reports a Hostinger order that is waiting for payment through the API', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/virtual-machines' => Http::response([+ 'id' => 2957086,+ 'status' => 'payment_initiated',+ ], 202),+ ]);++ $this->withToken($this->bearerToken)+ ->postJson('/api/v1/servers/hostinger', [+ 'cloud_provider_token_id' => $this->hostingerToken->uuid,+ 'item_id' => 'hostingercom-vps-kvm2-usd-1m',+ 'data_center_id' => 19,+ 'template_id' => 1130,+ 'private_key_uuid' => $this->privateKey->uuid,+ ])+ ->assertStatus(202)+ ->assertJsonFragment(['message' => 'Hostinger order 2957086 is waiting for payment. Finish the VPS setup in hPanel.']);++ $this->assertDatabaseMissing('servers', ['team_id' => $this->team->id]);+});++it('accepts Hostinger cloud provider tokens through the API', function () {+ Http::fake([+ 'https://developers.hostinger.com/api/vps/v1/virtual-machines' => Http::response([]),+ ]);++ $this->withToken($this->bearerToken)+ ->postJson('/api/v1/cloud-tokens', [+ 'provider' => 'hostinger',+ 'token' => 'another-hostinger-token',+ 'name' => 'Another Hostinger Token',+ ])+ ->assertCreated();++ $this->assertDatabaseHas('cloud_provider_tokens', [+ 'team_id' => $this->team->id,+ 'provider' => 'hostinger',+ 'name' => 'Another Hostinger Token',+ ]);+});diff --cc tests/Feature/Mcp/McpApplicationToolsTest.phpindex 00c4e4d6dc,0000000000..ffec7af91emode 100644,000000..100644--- a/tests/Feature/Mcp/McpApplicationToolsTest.php+++ b/tests/Feature/Mcp/McpApplicationToolsTest.php@@@ -1,520 -1,0 +1,530 @@@+<?php++use App\Jobs\DeleteResourceJob;+use App\Models\Application;+use App\Models\ApplicationDeploymentQueue;+use App\Models\ApplicationPreview;+use App\Models\Environment;+use App\Models\GithubApp;+use App\Models\InstanceSettings;+use App\Models\PrivateKey;+use App\Models\Project;+use App\Models\Server;+use App\Models\StandaloneDocker;+use App\Models\Team;+use App\Models\User;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\Bus;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Once;++uses(RefreshDatabase::class);++beforeEach(function () {+ config()->set('app.maintenance.store', 'array');+ Queue::fake();+ Bus::fake();+ Process::fake();+ Server::flushIdentityMap();++ InstanceSettings::query()->delete();+ $settings = new InstanceSettings(['is_mcp_server_enabled' => true, 'is_api_enabled' => true]);+ $settings->id = 0;+ $settings->save();+ Once::flush();++ $this->team = Team::factory()->create();+ $this->user = User::factory()->create();+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);++ $this->otherTeam = Team::factory()->create();+ $this->otherUser = User::factory()->create();+ $this->otherTeam->members()->attach($this->otherUser->id, ['role' => 'owner']);++ session(['currentTeam' => $this->team]);++ $this->server = Server::factory()->create(['team_id' => $this->team->id]);+ $this->destination = StandaloneDocker::where('server_id', $this->server->id)->firstOrFail();+ $this->project = Project::factory()->create(['team_id' => $this->team->id]);+ $this->environment = $this->project->environments()->first()+ ?? Environment::factory()->create(['project_id' => $this->project->id]);+ $this->application = mcpAppCreateApplication($this->environment, $this->destination, 'mine');++ $this->otherServer = Server::factory()->create(['team_id' => $this->otherTeam->id]);+ $this->otherDestination = StandaloneDocker::where('server_id', $this->otherServer->id)->firstOrFail();+ $this->otherProject = Project::factory()->create(['team_id' => $this->otherTeam->id]);+ $this->otherEnvironment = $this->otherProject->environments()->first()+ ?? Environment::factory()->create(['project_id' => $this->otherProject->id]);+ $this->otherApplication = mcpAppCreateApplication($this->otherEnvironment, $this->otherDestination, 'theirs');+});++function mcpAppCreateApplication(Environment $environment, StandaloneDocker $destination, string $name): Application+{+ $application = Application::factory()->create([+ 'name' => $name,+ 'environment_id' => $environment->id,+ 'destination_id' => $destination->id,+ 'destination_type' => $destination->getMorphClass(),+ ]);+ $application->settings->fill(['is_container_label_readonly_enabled' => false])->save();++ return $application;+}++function mcpAppToken(User $user, array $abilities = ['write']): string+{+ return $user->createToken('mcp-app', $abilities)->plainTextToken;+}++function mcpAppCall(string $token, string $tool, array $arguments = [])+{+ app('auth')->forgetGuards();++ return test()->withHeaders([+ 'Authorization' => 'Bearer '.$token,+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson('/mcp', [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'tools/call',+ 'params' => ['name' => $tool, 'arguments' => (object) $arguments],+ ]);+}++function mcpAppText($response): string+{+ return (string) ($response->json('result.content.0.text') ?? $response->json('error.message'));+}++function mcpAppIsError($response): bool+{+ return $response->json('result.isError') === true || $response->json('error') !== null;+}++/**+ * @return array<string, mixed>+ */+function mcpAppPublicData(array $overrides = []): array+{+ return array_merge([+ 'project_uuid' => test()->project->uuid,+ 'environment_uuid' => test()->environment->uuid,+ 'server_uuid' => test()->server->uuid,+ 'git_repository' => 'https://gitlab.com/coolify/test-static-app',+ 'git_branch' => 'main',+ 'build_pack' => 'static',+ 'ports_exposes' => '80',+ 'autogenerate_domain' => false,+ 'name' => 'mcp-created',+ ], $overrides);+}++function mcpAppCreatedCount(): int+{+ return Application::where('name', 'mcp-created')->count();+}++// create_application++test('create_application creates a public app in the token team, not the session team', function () {+ $token = mcpAppToken($this->user);+ $sessionTeam = Team::factory()->create();+ $sessionTeam->members()->attach($this->user->id, ['role' => 'owner']);+ $sessionProject = Project::factory()->create(['team_id' => $sessionTeam->id]);+ session(['currentTeam' => $sessionTeam]);++ $response = mcpAppCall($token, 'create_application', ['action' => 'public', 'data' => mcpAppPublicData()]);++ expect(mcpAppIsError($response))->toBeFalse(mcpAppText($response));+ $application = Application::where('name', 'mcp-created')->sole();+ expect($application->environment->project->team_id)->toBe($this->team->id)+ ->and($application->destination_id)->toBe($this->destination->id);++ $intoSessionTeam = mcpAppCall($token, 'create_application', ['action' => 'public', 'data' => mcpAppPublicData([+ 'project_uuid' => $sessionProject->uuid,+ 'environment_name' => 'production',+ 'name' => 'session-team-app',+ ])]);+ expect(mcpAppIsError($intoSessionTeam))->toBeTrue()+ ->and(Application::where('name', 'session-team-app')->exists())->toBeFalse();+});++test('create_application creates a docker image app', function () {+ $response = mcpAppCall(mcpAppToken($this->user), 'create_application', ['action' => 'docker_image', 'data' => [+ 'project_uuid' => $this->project->uuid,+ 'environment_uuid' => $this->environment->uuid,+ 'server_uuid' => $this->server->uuid,+ 'docker_registry_image_name' => 'nginx',+ 'docker_registry_image_tag' => 'latest',+ 'ports_exposes' => '80',+ 'autogenerate_domain' => false,+ 'name' => 'mcp-created',+ ]]);++ expect(mcpAppIsError($response))->toBeFalse(mcpAppText($response))+ ->and(Application::where('name', 'mcp-created')->sole()->build_pack)->toBe('dockerimage');+});++test('create_application rejects a project or server of another team', function (string $field) {+ $data = mcpAppPublicData([$field => $field === 'project_uuid' ? $this->otherProject->uuid : $this->otherServer->uuid]);++ $response = mcpAppCall(mcpAppToken($this->user), 'create_application', ['action' => 'public', 'data' => $data]);++ expect(mcpAppIsError($response))->toBeTrue()+ ->and(mcpAppCreatedCount())->toBe(0);+})->with(['project_uuid', 'server_uuid']);++test('create_application rejects a destination of another team', function () {+ $extra = StandaloneDocker::forceCreate([+ 'name' => 'second',+ 'network' => 'second-network',+ 'server_id' => $this->server->id,+ ]);+ expect($this->server->destinations()->count())->toBeGreaterThan(1);++ $response = mcpAppCall(mcpAppToken($this->user), 'create_application', ['action' => 'public', 'data' => mcpAppPublicData([+ 'destination_uuid' => $this->otherDestination->uuid,+ ])]);++ expect(mcpAppIsError($response))->toBeTrue()+ ->and(mcpAppText($response))->toContain('destination_uuid')+ ->and(mcpAppCreatedCount())->toBe(0);++ $ok = mcpAppCall(mcpAppToken($this->user), 'create_application', ['action' => 'public', 'data' => mcpAppPublicData([+ 'destination_uuid' => $extra->uuid,+ ])]);+ expect(mcpAppIsError($ok))->toBeFalse(mcpAppText($ok))+ ->and(Application::where('name', 'mcp-created')->sole()->destination_id)->toBe($extra->id);+});++test('create_application rejects a private key of another team', function () {+ $foreignKey = PrivateKey::factory()->create(['team_id' => $this->otherTeam->id]);++ $response = mcpAppCall(mcpAppToken($this->user), 'create_application', ['action' => 'deploy_key', 'data' => mcpAppPublicData([+ 'git_repository' => '[email protected]:coolify/private-app.git',+ 'private_key_uuid' => $foreignKey->uuid,+ ])]);++ expect(mcpAppIsError($response))->toBeTrue()+ ->and(mcpAppText($response))->toContain('Private Key not found')+ ->and(mcpAppCreatedCount())->toBe(0)+ ->and(mcpAppText($response))->not->toContain('PRIVATE KEY');+});++test('create_application rejects a GitHub App of another team', function () {+ $foreignApp = GithubApp::forceCreate([+ 'name' => 'Their GitHub App',+ 'api_url' => 'https://api.github.com',+ 'html_url' => 'https://github.com',+ 'team_id' => $this->otherTeam->id,+ 'is_system_wide' => false,+ 'private_key_id' => PrivateKey::factory()->create(['team_id' => $this->otherTeam->id])->id,+ ]);++ $response = mcpAppCall(mcpAppToken($this->user), 'create_application', ['action' => 'github_app', 'data' => mcpAppPublicData([+ 'git_repository' => 'their-org/their-repo',+ 'github_app_uuid' => $foreignApp->uuid,+ ])]);++ expect(mcpAppIsError($response))->toBeTrue()+ ->and(mcpAppText($response))->toContain('Github App not found')+ ->and(mcpAppCreatedCount())->toBe(0);+});++test('create_application rejects read-only and member tokens', function () {+ $member = User::factory()->create();+ $this->team->members()->attach($member->id, ['role' => 'member']);++ foreach ([mcpAppToken($this->user, ['read']), mcpAppToken($member, ['read']), mcpAppToken($member, ['write'])] as $token) {+ $response = mcpAppCall($token, 'create_application', ['action' => 'public', 'data' => mcpAppPublicData()]);+ expect(mcpAppIsError($response))->toBeTrue();+ }++ expect(mcpAppCreatedCount())->toBe(0);+});++test('create_application instant_deploy needs the deploy ability', function () {+ $response = mcpAppCall(mcpAppToken($this->user), 'create_application', ['action' => 'public', 'data' => mcpAppPublicData(['instant_deploy' => true])]);++ expect(mcpAppIsError($response))->toBeTrue()+ ->and(mcpAppText($response))->toContain('deploy')+ ->and(mcpAppCreatedCount())->toBe(0)+ ->and(ApplicationDeploymentQueue::count())->toBe(0);+});++// manage_application++test('manage_application accepts scalar and null unused path parameters', function (mixed $destinationUuid) {+ $response = mcpAppCall(mcpAppToken($this->user), 'manage_application', [+ 'action' => 'update',+ 'uuid' => $this->application->uuid,+ 'destination_uuid' => $destinationUuid,+ 'data' => ['name' => 'changed'],+ ]);++ $response->assertOk()->assertJsonMissingPath('error');+ expect(mcpAppIsError($response))->toBeFalse()+ ->and($this->application->fresh()->name)->toBe('changed');+})->with([+ 'string' => ['unused'],+ 'integer' => [123],+ 'float' => [1.5],+ 'boolean' => [false],+ 'null' => [null],+]);++test('manage_application rejects non-scalar unused path parameters before updating', function (mixed $destinationUuid) {+ $response = mcpAppCall(mcpAppToken($this->user), 'manage_application', [+ 'action' => 'update',+ 'uuid' => $this->application->uuid,+ 'destination_uuid' => $destinationUuid,+ 'data' => ['name' => 'changed'],+ ]);++ $response->assertOk()->assertJsonPath('result.isError', true)->assertJsonMissingPath('error');+ expect(mcpAppText($response))->toContain('destination_uuid must be a string.')+ ->and($this->application->fresh()->name)->toBe('mine');+})->with([+ 'array' => [['invalid']],+ 'object' => [(object) ['uuid' => 'invalid']],+]);++test('manage_application updates, clones and moves an application of the token team', function () {+ $token = mcpAppToken($this->user);++ $updated = mcpAppCall($token, 'manage_application', ['action' => 'update', 'uuid' => $this->application->uuid, 'data' => ['name' => 'renamed']]);+ expect(mcpAppIsError($updated))->toBeFalse(mcpAppText($updated))+ ->and($this->application->fresh()->name)->toBe('renamed');++ $cloned = mcpAppCall($token, 'manage_application', ['action' => 'clone', 'uuid' => $this->application->uuid, 'data' => ['destination_uuid' => $this->destination->uuid, 'name' => 'cloned']]);+ expect(mcpAppIsError($cloned))->toBeFalse(mcpAppText($cloned))+ ->and(Application::where('name', 'cloned')->sole()->environment_id)->toBe($this->environment->id);++ $target = Environment::factory()->create(['project_id' => $this->project->id, 'name' => 'staging']);+ $moved = mcpAppCall($token, 'manage_application', ['action' => 'move', 'uuid' => $this->application->uuid, 'confirm' => true, 'data' => ['environment_uuid' => $target->uuid]]);+ expect(mcpAppIsError($moved))->toBeFalse(mcpAppText($moved))+ ->and($this->application->fresh()->environment_id)->toBe($target->id);+});+- test('manage_application deletes an application only with confirm=true', function () {- $token = mcpAppToken($this->user);++test('manage_application deletes an application only with confirm=true and a deploy token', function () {++ $writeOnly = mcpAppCall(mcpAppToken($this->user), 'manage_application', ['action' => 'delete', 'uuid' => $this->application->uuid, 'confirm' => true]);++ expect(mcpAppIsError($writeOnly))->toBeTrue()++ ->and(mcpAppText($writeOnly))->toContain('Missing required permissions: deploy')++ ->and(Application::find($this->application->id))->not->toBeNull();++++ $token = mcpAppToken($this->user, ['write', 'deploy']);++ $denied = mcpAppCall($token, 'manage_application', ['action' => 'delete', 'uuid' => $this->application->uuid]);+ expect(mcpAppIsError($denied))->toBeTrue()+ ->and(mcpAppText($denied))->toContain('confirm=true')+ ->and(Application::find($this->application->id))->not->toBeNull();++ $deleted = mcpAppCall($token, 'manage_application', ['action' => 'delete', 'uuid' => $this->application->uuid, 'confirm' => true]);+ expect(mcpAppIsError($deleted))->toBeFalse(mcpAppText($deleted))+ ->and(Application::find($this->application->id))->toBeNull();+ Bus::assertDispatched(DeleteResourceJob::class);+});++test('manage_application needs confirm for move and remove_server', function (string $action) {+ $response = mcpAppCall(mcpAppToken($this->user), 'manage_application', [+ 'action' => $action,+ 'uuid' => $this->application->uuid,+ 'destination_uuid' => $this->destination->uuid,+ 'data' => [],+ ]);++ expect(mcpAppIsError($response))->toBeTrue()+ ->and(mcpAppText($response))->toContain('confirm=true')+ ->and($this->application->fresh()->environment_id)->toBe($this->environment->id);+})->with(['move', 'remove_server']);++test('manage_application cannot touch an application of another team', function (string $action, array $data) {+ $before = $this->otherApplication->fresh()->toArray();+- $response = mcpAppCall(mcpAppToken($this->user), 'manage_application', [++ $response = mcpAppCall(mcpAppToken($this->user, ['write', 'deploy']), 'manage_application', [+ 'action' => $action,+ 'uuid' => $this->otherApplication->uuid,+ 'destination_uuid' => $this->otherDestination->uuid,+ 'confirm' => true,+ 'data' => $data,+ ]);++ expect(mcpAppIsError($response))->toBeTrue()+ ->and(Application::find($this->otherApplication->id))->not->toBeNull()+ ->and($this->otherApplication->fresh()->name)->toBe($before['name'])+ ->and($this->otherApplication->fresh()->environment_id)->toBe($before['environment_id'])+ ->and(Application::where('name', 'hijacked')->exists())->toBeFalse();+})->with([+ 'update' => ['update', ['name' => 'hijacked']],+ 'delete' => ['delete', []],+ 'clone' => ['clone', ['destination_uuid' => 'placeholder', 'name' => 'hijacked']],+ 'move' => ['move', ['environment_uuid' => 'placeholder']],+ 'add_server' => ['add_server', ['destination_uuid' => 'placeholder']],+ 'remove_server' => ['remove_server', []],+]);++test('manage_application rejects a destination or environment of another team', function () {+ $token = mcpAppToken($this->user);++ $clone = mcpAppCall($token, 'manage_application', ['action' => 'clone', 'uuid' => $this->application->uuid, 'data' => ['destination_uuid' => $this->otherDestination->uuid, 'name' => 'hijacked']]);+ expect(mcpAppIsError($clone))->toBeTrue()+ ->and(Application::where('name', 'hijacked')->exists())->toBeFalse();++ $move = mcpAppCall($token, 'manage_application', ['action' => 'move', 'uuid' => $this->application->uuid, 'confirm' => true, 'data' => ['environment_uuid' => $this->otherEnvironment->uuid]]);+ expect(mcpAppIsError($move))->toBeTrue()+ ->and($this->application->fresh()->environment_id)->toBe($this->environment->id);++ $addServer = mcpAppCall($token, 'manage_application', ['action' => 'add_server', 'uuid' => $this->application->uuid, 'data' => ['destination_uuid' => $this->otherDestination->uuid]]);+ expect(mcpAppIsError($addServer))->toBeTrue()+ ->and($this->application->fresh()->additional_networks)->toHaveCount(0);+});++test('manage_application adds and removes an additional server of the token team', function () {+ $token = mcpAppToken($this->user);+ $secondServer = Server::factory()->create(['team_id' => $this->team->id]);+ $secondDestination = StandaloneDocker::where('server_id', $secondServer->id)->firstOrFail();++ $added = mcpAppCall($token, 'manage_application', ['action' => 'add_server', 'uuid' => $this->application->uuid, 'data' => ['destination_uuid' => $secondDestination->uuid]]);+ expect(mcpAppIsError($added))->toBeFalse(mcpAppText($added))+ ->and($this->application->fresh()->additional_networks)->toHaveCount(1);++ $removed = mcpAppCall($token, 'manage_application', ['action' => 'remove_server', 'uuid' => $this->application->uuid, 'destination_uuid' => $secondDestination->uuid, 'confirm' => true]);+ expect(mcpAppIsError($removed))->toBeFalse(mcpAppText($removed))+ ->and($this->application->fresh()->additional_networks)->toHaveCount(0);+});++test('manage_application rejects read-only and member tokens', function () {+ $member = User::factory()->create();+ $this->team->members()->attach($member->id, ['role' => 'member']);++ foreach ([mcpAppToken($this->user, ['read']), mcpAppToken($member, ['read']), mcpAppToken($member, ['write'])] as $token) {+ $update = mcpAppCall($token, 'manage_application', ['action' => 'update', 'uuid' => $this->application->uuid, 'data' => ['name' => 'nope']]);+ $delete = mcpAppCall($token, 'manage_application', ['action' => 'delete', 'uuid' => $this->application->uuid, 'confirm' => true]);+ expect(mcpAppIsError($update))->toBeTrue()+ ->and(mcpAppIsError($delete))->toBeTrue();+ }++ expect($this->application->fresh()->name)->toBe('mine');+});++// manage_preview and get_application_preview++test('manage_preview creates, updates and deletes a preview of the token team', function () {+ $writeToken = mcpAppToken($this->user, ['write']);+ $deployToken = mcpAppToken($this->user, ['deploy']);++ $writeOnly = mcpAppCall($writeToken, 'manage_preview', ['action' => 'create', 'uuid' => $this->application->uuid, 'data' => ['pull_request_id' => 7, 'git_type' => 'github', 'instant_deploy' => false]]);+ expect(mcpAppIsError($writeOnly))->toBeTrue()+ ->and(mcpAppText($writeOnly))->toContain('deploy');++ $created = mcpAppCall($deployToken, 'manage_preview', ['action' => 'create', 'uuid' => $this->application->uuid, 'data' => ['pull_request_id' => 7, 'git_type' => 'github', 'instant_deploy' => false]]);+ expect(mcpAppIsError($created))->toBeFalse(mcpAppText($created))+ ->and(ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', 7)->exists())->toBeTrue();++ $updated = mcpAppCall($writeToken, 'manage_preview', ['action' => 'update', 'uuid' => $this->application->uuid, 'pull_request_id' => '7', 'data' => ['domains' => 'https://pr7.example.com']]);+ expect(mcpAppIsError($updated))->toBeFalse(mcpAppText($updated))+ ->and(ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', 7)->sole()->fqdn)->toBe('https://pr7.example.com');+- $denied = mcpAppCall($writeToken, 'manage_preview', ['action' => 'delete', 'uuid' => $this->application->uuid, 'pull_request_id' => '7']);++ $writeOnlyDelete = mcpAppCall($writeToken, 'manage_preview', ['action' => 'delete', 'uuid' => $this->application->uuid, 'pull_request_id' => '7', 'confirm' => true]);++ expect(mcpAppIsError($writeOnlyDelete))->toBeTrue()++ ->and(mcpAppText($writeOnlyDelete))->toContain('Missing required permissions: deploy');++++ $writeDeployToken = mcpAppToken($this->user, ['write', 'deploy']);++ $denied = mcpAppCall($writeDeployToken, 'manage_preview', ['action' => 'delete', 'uuid' => $this->application->uuid, 'pull_request_id' => '7']);+ expect(mcpAppIsError($denied))->toBeTrue()+ ->and(mcpAppText($denied))->toContain('confirm=true');+- $deleted = mcpAppCall($writeToken, 'manage_preview', ['action' => 'delete', 'uuid' => $this->application->uuid, 'pull_request_id' => '7', 'confirm' => true]);++ $deleted = mcpAppCall($writeDeployToken, 'manage_preview', ['action' => 'delete', 'uuid' => $this->application->uuid, 'pull_request_id' => '7', 'confirm' => true]);+ expect(mcpAppIsError($deleted))->toBeFalse(mcpAppText($deleted))+ ->and(ApplicationPreview::where('application_id', $this->application->id)->where('pull_request_id', 7)->exists())->toBeFalse();+});++test('manage_preview cannot touch previews of another team', function () {+ $foreignPreview = ApplicationPreview::create(['application_id' => $this->otherApplication->id, 'pull_request_id' => 3, 'pull_request_html_url' => '', 'fqdn' => 'https://theirs.example.com']);+ $token = mcpAppToken($this->user, ['write', 'deploy']);++ $create = mcpAppCall($token, 'manage_preview', ['action' => 'create', 'uuid' => $this->otherApplication->uuid, 'data' => ['pull_request_id' => 9, 'git_type' => 'github', 'instant_deploy' => false]]);+ $update = mcpAppCall($token, 'manage_preview', ['action' => 'update', 'uuid' => $this->otherApplication->uuid, 'pull_request_id' => '3', 'data' => ['domains' => 'https://hijacked.example.com']]);+ $delete = mcpAppCall($token, 'manage_preview', ['action' => 'delete', 'uuid' => $this->otherApplication->uuid, 'pull_request_id' => '3', 'confirm' => true]);++ expect(mcpAppIsError($create))->toBeTrue()+ ->and(mcpAppIsError($update))->toBeTrue()+ ->and(mcpAppIsError($delete))->toBeTrue()+ ->and(ApplicationPreview::where('application_id', $this->otherApplication->id)->where('pull_request_id', 9)->exists())->toBeFalse()+ ->and($foreignPreview->fresh())->not->toBeNull()+ ->and($foreignPreview->fresh()->fqdn)->toBe('https://theirs.example.com');+});++test('manage_preview rejects read-only tokens', function () {+ ApplicationPreview::create(['application_id' => $this->application->id, 'pull_request_id' => 4, 'pull_request_html_url' => '']);+ $token = mcpAppToken($this->user, ['read']);++ expect(mcpAppIsError(mcpAppCall($token, 'manage_preview', ['action' => 'create', 'uuid' => $this->application->uuid, 'data' => ['pull_request_id' => 5, 'git_type' => 'github']])))->toBeTrue()+ ->and(mcpAppIsError(mcpAppCall($token, 'manage_preview', ['action' => 'delete', 'uuid' => $this->application->uuid, 'pull_request_id' => '4', 'confirm' => true])))->toBeTrue()+ ->and(ApplicationPreview::where('application_id', $this->application->id)->count())->toBe(1);+});++test('get_application_preview returns a preview of the token team only', function () {+ ApplicationPreview::create(['application_id' => $this->application->id, 'pull_request_id' => 12, 'pull_request_html_url' => '', 'fqdn' => 'https://pr12.example.com']);+ ApplicationPreview::create(['application_id' => $this->otherApplication->id, 'pull_request_id' => 12, 'pull_request_html_url' => '', 'fqdn' => 'https://theirs.example.com']);+ $token = mcpAppToken($this->user, ['read']);++ $mine = mcpAppCall($token, 'get_application_preview', ['action' => 'get', 'uuid' => $this->application->uuid, 'pull_request_id' => '12']);+ expect(mcpAppIsError($mine))->toBeFalse(mcpAppText($mine))+ ->and(mcpAppText($mine))->toContain('pr12.example.com');++ $theirs = mcpAppCall($token, 'get_application_preview', ['action' => 'get', 'uuid' => $this->otherApplication->uuid, 'pull_request_id' => '12']);+ expect(mcpAppIsError($theirs))->toBeTrue()+ ->and(mcpAppText($theirs))->not->toContain('theirs.example.com');+});++test('get_application_preview logs need read:sensitive and stay inside the token team', function () {+ ApplicationPreview::create(['application_id' => $this->otherApplication->id, 'pull_request_id' => 12, 'pull_request_html_url' => '']);++ $readOnly = mcpAppCall(mcpAppToken($this->user, ['read']), 'get_application_preview', ['action' => 'logs', 'uuid' => $this->application->uuid, 'pull_request_id' => '12']);+ expect(mcpAppIsError($readOnly))->toBeTrue()+ ->and(mcpAppText($readOnly))->toContain('read:sensitive');++ $foreign = mcpAppCall(mcpAppToken($this->user, ['read', 'read:sensitive']), 'get_application_preview', ['action' => 'logs', 'uuid' => $this->otherApplication->uuid, 'pull_request_id' => '12']);+ expect(mcpAppIsError($foreign))->toBeTrue()+ ->and(mcpAppText($foreign))->toContain('not found');+ Process::assertNothingRan();+});++// rollback_application and list_rollback_images++test('rollback_application needs confirm and the deploy ability, then queues a rollback', function () {+ $writeOnly = mcpAppCall(mcpAppToken($this->user, ['write']), 'rollback_application', ['action' => 'rollback', 'uuid' => $this->application->uuid, 'confirm' => true, 'data' => ['commit' => 'abc1234']]);+ expect(mcpAppIsError($writeOnly))->toBeTrue()+ ->and(mcpAppText($writeOnly))->toContain('Tool [rollback_application] not found');++ $deployToken = mcpAppToken($this->user, ['deploy']);+ $unconfirmed = mcpAppCall($deployToken, 'rollback_application', ['action' => 'rollback', 'uuid' => $this->application->uuid, 'data' => ['commit' => 'abc1234']]);+ expect(mcpAppIsError($unconfirmed))->toBeTrue()+ ->and(mcpAppText($unconfirmed))->toContain('confirm=true')+ ->and(ApplicationDeploymentQueue::count())->toBe(0);++ $queued = mcpAppCall($deployToken, 'rollback_application', ['action' => 'rollback', 'uuid' => $this->application->uuid, 'confirm' => true, 'data' => ['commit' => 'abc1234']]);+ expect(mcpAppIsError($queued))->toBeFalse(mcpAppText($queued))+ ->and(ApplicationDeploymentQueue::where('application_id', $this->application->id)->where('commit', 'abc1234')->where('rollback', true)->exists())->toBeTrue();+});++test('rollback_application cannot roll back an application of another team', function () {+ $response = mcpAppCall(mcpAppToken($this->user, ['deploy']), 'rollback_application', ['action' => 'rollback', 'uuid' => $this->otherApplication->uuid, 'confirm' => true, 'data' => ['commit' => 'abc1234']]);++ expect(mcpAppIsError($response))->toBeTrue()+ ->and(ApplicationDeploymentQueue::count())->toBe(0);+});++test('list_rollback_images lists images for the token team only', function () {+ $token = mcpAppToken($this->user, ['read']);++ $mine = mcpAppCall($token, 'list_rollback_images', ['action' => 'list', 'uuid' => $this->application->uuid]);+ expect(mcpAppIsError($mine))->toBeFalse(mcpAppText($mine))+ ->and(mcpAppText($mine))->toContain('images');++ $theirs = mcpAppCall($token, 'list_rollback_images', ['action' => 'list', 'uuid' => $this->otherApplication->uuid]);+ expect(mcpAppIsError($theirs))->toBeTrue()+ ->and(mcpAppText($theirs))->toContain('not found');+});diff --cc tests/Feature/Mcp/McpDataToolsTest.phpindex 6e14c17ff2,0000000000..dd96ca9cd9mode 100644,000000..100644--- a/tests/Feature/Mcp/McpDataToolsTest.php+++ b/tests/Feature/Mcp/McpDataToolsTest.php@@@ -1,787 -1,0 +1,799 @@@+<?php++use App\Models\Application;+use App\Models\Environment;+use App\Models\EnvironmentVariable;+use App\Models\InstanceSettings;+use App\Models\Project;+use App\Models\S3Storage;+use App\Models\Server;+use App\Models\Service;+use App\Models\ServiceApplication;+use App\Models\ServiceDatabase;+use App\Models\SharedEnvironmentVariable;+use App\Models\StandaloneDocker;+use App\Models\StandalonePostgresql;+use App\Models\Team;+use App\Models\User;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Once;+use Illuminate\Support\Str;+use Spatie\Activitylog\Models\Activity;++uses(RefreshDatabase::class);++beforeEach(function () {+ config()->set('app.maintenance.store', 'array');+ InstanceSettings::query()->delete();+ $settings = new InstanceSettings(['is_mcp_server_enabled' => true, 'is_api_enabled' => true]);+ $settings->id = 0;+ $settings->save();+ Once::flush();+ Server::flushIdentityMap();+ Queue::fake();+ Process::fake();++ $this->team = Team::factory()->create();+ $this->user = User::factory()->create();+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);++ $this->otherTeam = Team::factory()->create();+ $this->otherUser = User::factory()->create();+ $this->otherTeam->members()->attach($this->otherUser->id, ['role' => 'owner']);++ $this->mine = mcpDataSeedTeam($this->team);+ $this->theirs = mcpDataSeedTeam($this->otherTeam);++ session(['currentTeam' => $this->team]);+});++afterEach(function () {+ Server::flushIdentityMap();+});++/**+ * @return array{server: Server, destination: StandaloneDocker, project: Project, environment: Environment, database: StandalonePostgresql, service: Service, service_app: ServiceApplication, service_db: ServiceDatabase, application: Application}+ */+function mcpDataSeedTeam(Team $team): array+{+ $server = Server::factory()->create(['team_id' => $team->id]);+ $destination = StandaloneDocker::where('server_id', $server->id)->firstOrFail();+ $project = Project::factory()->create(['team_id' => $team->id]);+ $environment = Environment::factory()->create(['project_id' => $project->id]);+ $database = StandalonePostgresql::create([+ 'uuid' => (string) Str::uuid(),+ 'name' => 'db-'.$team->id,+ 'postgres_user' => 'postgres',+ 'postgres_password' => 'pg-secret-'.$team->id,+ 'postgres_db' => 'app',+ 'image' => 'postgres:17',+ 'environment_id' => $environment->id,+ 'destination_id' => $destination->id,+ 'destination_type' => $destination->getMorphClass(),+ ]);+ $service = Service::factory()->create([+ 'name' => 'svc-'.$team->id,+ 'environment_id' => $environment->id,+ 'server_id' => $server->id,+ 'destination_id' => $destination->id,+ 'destination_type' => $destination->getMorphClass(),+ 'docker_compose_raw' => "services:\n web:\n image: nginx:alpine\n",+ ]);+ $serviceApp = ServiceApplication::create(['uuid' => (string) Str::uuid(), 'name' => 'web', 'service_id' => $service->id, 'image' => 'nginx:alpine']);+ $serviceDb = ServiceDatabase::create(['uuid' => (string) Str::uuid(), 'name' => 'postgres', 'service_id' => $service->id, 'image' => 'postgres:17']);+ $application = Application::factory()->create([+ 'environment_id' => $environment->id,+ 'destination_id' => $destination->id,+ 'destination_type' => $destination->getMorphClass(),+ ]);++ return [+ 'server' => $server,+ 'destination' => $destination,+ 'project' => $project,+ 'environment' => $environment,+ 'database' => $database,+ 'service' => $service,+ 'service_app' => $serviceApp,+ 'service_db' => $serviceDb,+ 'application' => $application,+ ];+}++function mcpDataToken(User $user, array $abilities = ['write']): string+{+ return $user->createToken('mcp-data', $abilities)->plainTextToken;+}++function mcpDataCall(string $token, string $tool, array $arguments = [])+{+ // Each call authenticates its own token; the guard would otherwise keep the user of the previous call.+ app('auth')->forgetGuards();++ return test()->withHeaders([+ 'Authorization' => 'Bearer '.$token,+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson('/mcp', [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'tools/call',+ 'params' => ['name' => $tool, 'arguments' => (object) $arguments],+ ]);+}++function mcpDataText($response): string+{+ return (string) ($response->json('result.content.0.text') ?? $response->json('error.message'));+}++/**+ * A tool error (result.isError) or a JSON-RPC error, for example the MCP endpoint rejecting a member token with write abilities.+ */+function mcpDataIsError($response): bool+{+ return $response->json('result.isError') === true || $response->json('error') !== null;+}++function mcpDataJson($response): array+{+ return json_decode(mcpDataText($response), true) ?? [];+}++function mcpDataMember(Team $team): User+{+ $member = User::factory()->create();+ $team->members()->attach($member->id, ['role' => 'member']);++ return $member;+}++function mcpDataDbEnv(StandalonePostgresql $database, string $key, string $value, bool $shownOnce = false): EnvironmentVariable+{+ return EnvironmentVariable::create([+ 'key' => $key,+ 'value' => $value,+ 'is_shown_once' => $shownOnce,+ 'resourceable_type' => $database->getMorphClass(),+ 'resourceable_id' => $database->id,+ ]);+}++function mcpDataS3(Team $team): S3Storage+{+ return S3Storage::create([+ 'name' => 'backups-'.$team->id,+ 'region' => 'us-east-1',+ 'key' => 'AKIADATATEST',+ 'secret' => 's3-secret-'.$team->id,+ 'bucket' => 'bucket',+ 'endpoint' => 'https://s3.example.com',+ 'team_id' => $team->id,+ 'is_usable' => true,+ ]);+}++// create_database++test('create_database creates a database in the token team and never returns connection URLs', function (array $abilities) {+ $response = mcpDataCall(mcpDataToken($this->user, $abilities), 'create_database', ['action' => 'postgresql', 'data' => [+ 'project_uuid' => $this->mine['project']->uuid,+ 'environment_uuid' => $this->mine['environment']->uuid,+ 'server_uuid' => $this->mine['server']->uuid,+ 'name' => 'from-mcp',+ 'postgres_password' => 'VeryS3cretPass',+ 'is_public' => true,+ 'public_port' => 15432,+ ]]);++ expect(mcpDataIsError($response))->toBeFalse();+ $uuid = mcpDataJson($response)['data']['uuid'];+ $database = StandalonePostgresql::whereUuid($uuid)->sole();+ expect($database->name)->toBe('from-mcp')+ ->and($database->environment_id)->toBe($this->mine['environment']->id)+ ->and(mcpDataText($response))->not->toContain('VeryS3cretPass')+ ->and(mcpDataText($response))->not->toContain('internal_db_url')+ ->and(mcpDataText($response))->not->toContain('external_db_url')+ ->and(mcpDataText($response))->not->toContain('postgres_password');+})->with([+ 'write' => [['write']],+ 'root' => [['root']],+ 'write and read:sensitive' => [['write', 'read:sensitive']],+]);++test('create_database rejects a project, server, or destination of another team', function (string $field) {+ $own = $this->mine;+ StandaloneDocker::create(['name' => 'second', 'network' => 'second-net', 'server_id' => $own['server']->id]);+ $data = [+ 'project_uuid' => $own['project']->uuid,+ 'environment_uuid' => $own['environment']->uuid,+ 'server_uuid' => $own['server']->uuid,+ 'destination_uuid' => $own['destination']->uuid,+ 'name' => 'cross-team',+ ];+ $data[$field] = match ($field) {+ 'project_uuid' => $this->theirs['project']->uuid,+ 'environment_uuid' => $this->theirs['environment']->uuid,+ 'server_uuid' => $this->theirs['server']->uuid,+ 'destination_uuid' => $this->theirs['destination']->uuid,+ };++ $response = mcpDataCall(mcpDataToken($this->user), 'create_database', ['action' => 'postgresql', 'data' => $data]);++ expect(mcpDataIsError($response))->toBeTrue()+ ->and(StandalonePostgresql::where('name', 'cross-team')->exists())->toBeFalse();+})->with(['project_uuid', 'environment_uuid', 'server_uuid', 'destination_uuid']);++test('create_database rejects read-only and member tokens, and instant_deploy without deploy', function () {+ $data = [+ 'project_uuid' => $this->mine['project']->uuid,+ 'environment_uuid' => $this->mine['environment']->uuid,+ 'server_uuid' => $this->mine['server']->uuid,+ 'name' => 'denied',+ ];+ $member = mcpDataMember($this->team);++ $read = mcpDataCall(mcpDataToken($this->user, ['read']), 'create_database', ['action' => 'redis', 'data' => $data]);+ $memberResponse = mcpDataCall(mcpDataToken($member, ['write']), 'create_database', ['action' => 'redis', 'data' => $data]);+ $instant = mcpDataCall(mcpDataToken($this->user), 'create_database', ['action' => 'redis', 'data' => $data + ['instant_deploy' => true]]);++ expect(mcpDataIsError($read))->toBeTrue()+ ->and(mcpDataText($read))->toContain('Tool [create_database] not found')+ ->and(mcpDataIsError($memberResponse))->toBeTrue()+ ->and(mcpDataIsError($instant))->toBeTrue()+ ->and(mcpDataText($instant))->toContain('deploy');+ expect(StandalonePostgresql::where('name', 'denied')->exists())->toBeFalse();+});++// manage_database++test('manage_database updates a database of the token team', function () {+ $response = mcpDataCall(mcpDataToken($this->user), 'manage_database', ['action' => 'update', 'uuid' => $this->mine['database']->uuid, 'data' => ['name' => 'renamed']]);++ expect(mcpDataIsError($response))->toBeFalse()+ ->and($this->mine['database']->fresh()->name)->toBe('renamed');+});++test('manage_database cannot touch a database of another team', function (string $action, array $data) {+ $foreign = $this->theirs['database'];+- $response = mcpDataCall(mcpDataToken($this->user), 'manage_database', ['action' => $action, 'uuid' => $foreign->uuid, 'confirm' => true, 'data' => $data]);++ $response = mcpDataCall(mcpDataToken($this->user, ['write', 'deploy']), 'manage_database', ['action' => $action, 'uuid' => $foreign->uuid, 'confirm' => true, 'data' => $data]);++ expect(mcpDataIsError($response))->toBeTrue();+ $fresh = StandalonePostgresql::withTrashed()->find($foreign->id);+ expect($fresh->trashed())->toBeFalse()+ ->and($fresh->name)->toBe($foreign->name)+ ->and($fresh->environment_id)->toBe($foreign->environment_id)+ ->and(StandalonePostgresql::count())->toBe(2);+})->with([+ 'update' => ['update', ['name' => 'hijacked']],+ 'delete' => ['delete', []],+ 'clone' => ['clone', ['destination_uuid' => 'placeholder']],+ 'move' => ['move', ['environment_uuid' => 'placeholder']],+ 'import' => ['import', ['source' => 's3', 's3_storage_uuid' => 'x', 'path' => '/a.sql']],+]);++test('manage_database rejects a destination, environment, or S3 storage of another team', function () {+ $own = $this->mine['database'];- $token = mcpDataToken($this->user);++ $token = mcpDataToken($this->user, ['write', 'deploy']);+ $foreignS3 = mcpDataS3($this->otherTeam);++ $clone = mcpDataCall($token, 'manage_database', ['action' => 'clone', 'uuid' => $own->uuid, 'confirm' => true, 'data' => ['destination_uuid' => $this->theirs['destination']->uuid]]);+ $move = mcpDataCall($token, 'manage_database', ['action' => 'move', 'uuid' => $own->uuid, 'confirm' => true, 'data' => ['environment_uuid' => $this->theirs['environment']->uuid]]);+ $import = mcpDataCall($token, 'manage_database', ['action' => 'import', 'uuid' => $own->uuid, 'confirm' => true, 'data' => ['source' => 's3', 's3_storage_uuid' => $foreignS3->uuid, 'path' => '/backup.sql']]);++ expect(mcpDataIsError($clone))->toBeTrue()+ ->and(mcpDataIsError($move))->toBeTrue()+ ->and(mcpDataIsError($import))->toBeTrue()+ ->and(StandalonePostgresql::count())->toBe(2)+ ->and($own->fresh()->environment_id)->toBe($this->mine['environment']->id)+ ->and(mcpDataText($import))->not->toContain('s3-secret');+});++test('manage_database clones to an own destination and moves to an own environment', function () {+ $own = $this->mine['database'];+ $token = mcpDataToken($this->user);+ $target = Environment::factory()->create(['project_id' => $this->mine['project']->id]);++ $clone = mcpDataCall($token, 'manage_database', ['action' => 'clone', 'uuid' => $own->uuid, 'confirm' => true, 'data' => ['destination_uuid' => $this->mine['destination']->uuid, 'name' => 'the-clone']]);+ $move = mcpDataCall($token, 'manage_database', ['action' => 'move', 'uuid' => $own->uuid, 'confirm' => true, 'data' => ['environment_uuid' => $target->uuid]]);++ expect(mcpDataIsError($clone))->toBeFalse()+ ->and(StandalonePostgresql::where('name', 'the-clone')->sole()->environment_id)->toBe($this->mine['environment']->id)+ ->and(mcpDataIsError($move))->toBeFalse()+ ->and($own->fresh()->environment_id)->toBe($target->id);+});++test('manage_database destructive actions need confirm=true', function (string $action, array $data) {+ $own = $this->mine['database'];+- $denied = mcpDataCall(mcpDataToken($this->user), 'manage_database', ['action' => $action, 'uuid' => $own->uuid, 'data' => $data]);++ $denied = mcpDataCall(mcpDataToken($this->user, ['write', 'deploy']), 'manage_database', ['action' => $action, 'uuid' => $own->uuid, 'data' => $data]);++ expect(mcpDataIsError($denied))->toBeTrue()+ ->and(mcpDataText($denied))->toContain('confirm=true')+ ->and(StandalonePostgresql::count())->toBe(2)+ ->and($own->fresh())->not->toBeNull();+})->with([+ 'delete' => ['delete', []],+ 'clone' => ['clone', ['destination_uuid' => 'x']],+ 'move' => ['move', ['environment_uuid' => 'x']],+ 'import' => ['import', ['source' => 'server', 'path' => '/tmp/a.sql']],+]);++test('manage_database delete with confirm=true deletes an own database', function () {+ $own = $this->mine['database'];+- $response = mcpDataCall(mcpDataToken($this->user), 'manage_database', ['action' => 'delete', 'uuid' => $own->uuid, 'confirm' => true]);++ $writeOnly = mcpDataCall(mcpDataToken($this->user), 'manage_database', ['action' => 'delete', 'uuid' => $own->uuid, 'confirm' => true]);++ expect(mcpDataIsError($writeOnly))->toBeTrue()++ ->and(mcpDataText($writeOnly))->toContain('Missing required permissions: deploy')++ ->and(StandalonePostgresql::find($own->id))->not->toBeNull();++++ $response = mcpDataCall(mcpDataToken($this->user, ['write', 'deploy']), 'manage_database', ['action' => 'delete', 'uuid' => $own->uuid, 'confirm' => true]);++ expect(mcpDataIsError($response))->toBeFalse()+ ->and(StandalonePostgresql::find($own->id))->toBeNull();+});+- test('manage_database import runs REST validation and needs deploy for a server path', function () {++test('manage_database import needs deploy and runs REST validation', function () {+ $own = $this->mine['database'];- $token = mcpDataToken($this->user);++ $writeOnly = mcpDataToken($this->user);+- $invalid = mcpDataCall($token, 'manage_database', ['action' => 'import', 'uuid' => $own->uuid, 'confirm' => true, 'data' => ['source' => 's3']]);- $serverPath = mcpDataCall($token, 'manage_database', ['action' => 'import', 'uuid' => $own->uuid, 'confirm' => true, 'data' => ['source' => 'server', 'path' => '/etc/passwd']]);++ foreach ([['source' => 's3', 's3_storage_uuid' => 'x', 'path' => '/a.sql'], ['source' => 'server', 'path' => '/etc/passwd']] as $data) {++ $denied = mcpDataCall($writeOnly, 'manage_database', ['action' => 'import', 'uuid' => $own->uuid, 'confirm' => true, 'data' => $data]);++ expect(mcpDataIsError($denied))->toBeTrue()++ ->and(mcpDataText($denied))->toContain('Missing required permissions: deploy');++ }+++ $invalid = mcpDataCall(mcpDataToken($this->user, ['write', 'deploy']), 'manage_database', ['action' => 'import', 'uuid' => $own->uuid, 'confirm' => true, 'data' => ['source' => 's3']]);+ expect(mcpDataIsError($invalid))->toBeTrue()- ->and(mcpDataText($invalid))->toContain('s3_storage_uuid')- ->and(mcpDataIsError($serverPath))->toBeTrue()- ->and(mcpDataText($serverPath))->toContain('deploy');++ ->and(mcpDataText($invalid))->toContain('s3_storage_uuid');+});++test('manage_database rejects read-only and member tokens', function () {+ $own = $this->mine['database'];+ $member = mcpDataMember($this->team);++ $read = mcpDataCall(mcpDataToken($this->user, ['read']), 'manage_database', ['action' => 'update', 'uuid' => $own->uuid, 'data' => ['name' => 'nope']]);+ $memberResponse = mcpDataCall(mcpDataToken($member, ['read']), 'manage_database', ['action' => 'update', 'uuid' => $own->uuid, 'data' => ['name' => 'nope']]);++ expect(mcpDataIsError($read))->toBeTrue()+ ->and(mcpDataIsError($memberResponse))->toBeTrue()+ ->and($own->fresh()->name)->not->toBe('nope');+});++// get_database_import++test('get_database_import returns an own import and hides imports of other teams', function () {+ $own = $this->mine['database'];+ $foreign = $this->theirs['database'];+ $makeActivity = fn (Team $team, StandalonePostgresql $database): Activity => Activity::create([+ 'log_name' => 'default',+ 'description' => 'import',+ 'properties' => ['team_id' => $team->id, 'type_uuid' => $database->uuid, 'operation' => 'database_import', 'status' => 'finished'],+ ]);+ $ownActivity = $makeActivity($this->team, $own);+ $foreignActivity = $makeActivity($this->otherTeam, $foreign);+ $token = mcpDataToken($this->user, ['read']);++ $ok = mcpDataCall($token, 'get_database_import', ['action' => 'get', 'resource' => 'database', 'uuid' => $own->uuid, 'activity_id' => (string) $ownActivity->id]);+ $foreignUuid = mcpDataCall($token, 'get_database_import', ['action' => 'get', 'resource' => 'database', 'uuid' => $foreign->uuid, 'activity_id' => (string) $foreignActivity->id]);+ $foreignId = mcpDataCall($token, 'get_database_import', ['action' => 'get', 'resource' => 'database', 'uuid' => $own->uuid, 'activity_id' => (string) $foreignActivity->id]);++ expect(mcpDataIsError($ok))->toBeFalse()+ ->and(mcpDataJson($ok)['data']['status'])->toBe('finished')+ ->and(mcpDataJson($ok)['data']['output'])->toBeNull()+ ->and(mcpDataIsError($foreignUuid))->toBeTrue()+ ->and(mcpDataIsError($foreignId))->toBeTrue();+});++test('get_database_import rejects a service database of another team', function () {+ $response = mcpDataCall(mcpDataToken($this->user, ['read']), 'get_database_import', [+ 'action' => 'get',+ 'resource' => 'service_database',+ 'uuid' => $this->mine['service']->uuid,+ 'database_uuid' => $this->theirs['service_db']->uuid,+ 'activity_id' => '1',+ ]);++ expect(mcpDataIsError($response))->toBeTrue()+ ->and(mcpDataText($response))->toContain('not found');+});++// list_service_templates++test('list_service_templates lists template metadata without Compose content', function () {+ $templates = get_service_templates();+ $type = (string) $templates->keys()->first();++ $response = mcpDataCall(mcpDataToken($this->user, ['read']), 'list_service_templates', ['search' => $type, 'per_page' => 100]);++ expect(mcpDataIsError($response))->toBeFalse();+ $items = collect(mcpDataJson($response)['data']);+ expect($items->pluck('type'))->toContain($type)+ ->and(array_keys($items->first()))->toEqualCanonicalizing(['type', 'slogan', 'category', 'tags', 'documentation', 'port'])+ ->and(mcpDataText($response))->not->toContain((string) data_get($templates->get($type), 'compose'));+});++test('list_service_templates paginates and requires a valid token', function () {+ $response = mcpDataCall(mcpDataToken($this->user, ['read']), 'list_service_templates', ['per_page' => 2]);+ $payload = mcpDataJson($response);++ expect($payload['data'])->toHaveCount(2)+ ->and($payload['_pagination']['total'])->toBe(get_service_templates()->count())+ ->and($payload['_pagination']['next']['args']['page'])->toBe(2);++ $none = mcpDataCall(mcpDataToken($this->user, []), 'list_service_templates');+ expect(mcpDataIsError($none))->toBeTrue();+});++// create_service++test('create_service creates a Compose service in the token team', function () {+ $response = mcpDataCall(mcpDataToken($this->user), 'create_service', ['action' => 'compose', 'data' => [+ 'project_uuid' => $this->mine['project']->uuid,+ 'environment_uuid' => $this->mine['environment']->uuid,+ 'server_uuid' => $this->mine['server']->uuid,+ 'name' => 'mcp-service',+ 'docker_compose_raw' => base64_encode("services:\n app:\n image: nginx:alpine\n"),+ ]]);++ expect(mcpDataIsError($response))->toBeFalse();+ $service = Service::whereUuid(mcpDataJson($response)['data']['uuid'])->sole();+ expect($service->name)->toBe('mcp-service')+ ->and($service->environment_id)->toBe($this->mine['environment']->id)+ ->and($service->server_id)->toBe($this->mine['server']->id);+});++test('create_service rejects a project, server, or destination of another team', function (string $field) {+ $own = $this->mine;+ StandaloneDocker::create(['name' => 'second', 'network' => 'second-net', 'server_id' => $own['server']->id]);+ $data = [+ 'project_uuid' => $own['project']->uuid,+ 'environment_uuid' => $own['environment']->uuid,+ 'server_uuid' => $own['server']->uuid,+ 'destination_uuid' => $own['destination']->uuid,+ 'name' => 'cross-team-service',+ 'docker_compose_raw' => base64_encode("services:\n app:\n image: nginx:alpine\n"),+ ];+ $data[$field] = match ($field) {+ 'project_uuid' => $this->theirs['project']->uuid,+ 'environment_uuid' => $this->theirs['environment']->uuid,+ 'server_uuid' => $this->theirs['server']->uuid,+ 'destination_uuid' => $this->theirs['destination']->uuid,+ };++ $response = mcpDataCall(mcpDataToken($this->user), 'create_service', ['action' => 'compose', 'data' => $data]);++ expect(mcpDataIsError($response))->toBeTrue()+ ->and(Service::where('name', 'cross-team-service')->exists())->toBeFalse();+})->with(['project_uuid', 'environment_uuid', 'server_uuid', 'destination_uuid']);++test('create_service rejects read-only and member tokens', function () {+ $data = [+ 'project_uuid' => $this->mine['project']->uuid,+ 'environment_uuid' => $this->mine['environment']->uuid,+ 'server_uuid' => $this->mine['server']->uuid,+ 'name' => 'denied-service',+ 'docker_compose_raw' => base64_encode("services:\n app:\n image: nginx:alpine\n"),+ ];++ $read = mcpDataCall(mcpDataToken($this->user, ['read']), 'create_service', ['action' => 'compose', 'data' => $data]);+ $member = mcpDataCall(mcpDataToken(mcpDataMember($this->team), ['write']), 'create_service', ['action' => 'compose', 'data' => $data]);++ expect(mcpDataIsError($read))->toBeTrue()+ ->and(mcpDataIsError($member))->toBeTrue()+ ->and(Service::where('name', 'denied-service')->exists())->toBeFalse();+});++// manage_service++test('manage_service updates a service, its application, and its database', function () {+ $own = $this->mine;+ $token = mcpDataToken($this->user);++ $service = mcpDataCall($token, 'manage_service', ['action' => 'update', 'uuid' => $own['service']->uuid, 'data' => ['name' => 'renamed-service']]);+ $app = mcpDataCall($token, 'manage_service', ['action' => 'update_application', 'uuid' => $own['service']->uuid, 'app_uuid' => $own['service_app']->uuid, 'data' => ['human_name' => 'Web']]);+ $db = mcpDataCall($token, 'manage_service', ['action' => 'update_database', 'uuid' => $own['service']->uuid, 'database_uuid' => $own['service_db']->uuid, 'data' => ['human_name' => 'DB']]);++ expect(mcpDataIsError($service))->toBeFalse()+ ->and($own['service']->fresh()->name)->toBe('renamed-service')+ ->and(mcpDataIsError($app))->toBeFalse()+ ->and($own['service_app']->fresh()->human_name)->toBe('Web')+ ->and(mcpDataIsError($db))->toBeFalse()+ ->and($own['service_db']->fresh()->human_name)->toBe('DB');+});++test('manage_service cannot touch a service of another team', function (string $action, array $data) {+ $foreign = $this->theirs;+- $response = mcpDataCall(mcpDataToken($this->user), 'manage_service', [++ $response = mcpDataCall(mcpDataToken($this->user, ['write', 'deploy']), 'manage_service', [+ 'action' => $action,+ 'uuid' => $foreign['service']->uuid,+ 'app_uuid' => $foreign['service_app']->uuid,+ 'database_uuid' => $foreign['service_db']->uuid,+ 'confirm' => true,+ 'data' => $data,+ ]);++ expect(mcpDataIsError($response))->toBeTrue();+ $fresh = Service::withTrashed()->find($foreign['service']->id);+ expect($fresh->trashed())->toBeFalse()+ ->and($fresh->name)->toBe($foreign['service']->name)+ ->and($fresh->environment_id)->toBe($foreign['environment']->id)+ ->and($foreign['service_app']->fresh()->human_name)->toBeNull()+ ->and($foreign['service_db']->fresh()->human_name)->toBeNull()+ ->and(Service::count())->toBe(2);+})->with([+ 'update' => ['update', ['name' => 'hijacked']],+ 'delete' => ['delete', []],+ 'clone' => ['clone', ['destination_uuid' => 'placeholder']],+ 'move' => ['move', ['environment_uuid' => 'placeholder']],+ 'update_application' => ['update_application', ['human_name' => 'hijacked']],+ 'update_database' => ['update_database', ['human_name' => 'hijacked']],+ 'import_database' => ['import_database', ['source' => 's3', 's3_storage_uuid' => 'x', 'path' => '/a.sql']],+]);++test('manage_service cannot reach an application or database of another team through an own service', function () {+ $token = mcpDataToken($this->user);++ $app = mcpDataCall($token, 'manage_service', ['action' => 'update_application', 'uuid' => $this->mine['service']->uuid, 'app_uuid' => $this->theirs['service_app']->uuid, 'data' => ['human_name' => 'hijacked']]);+ $db = mcpDataCall($token, 'manage_service', ['action' => 'update_database', 'uuid' => $this->mine['service']->uuid, 'database_uuid' => $this->theirs['service_db']->uuid, 'data' => ['human_name' => 'hijacked']]);++ expect(mcpDataIsError($app))->toBeTrue()+ ->and(mcpDataIsError($db))->toBeTrue()+ ->and($this->theirs['service_app']->fresh()->human_name)->toBeNull()+ ->and($this->theirs['service_db']->fresh()->human_name)->toBeNull();+});++test('manage_service rejects a destination, environment, or S3 storage of another team', function () {+ $own = $this->mine;- $token = mcpDataToken($this->user);++ $token = mcpDataToken($this->user, ['write', 'deploy']);+ $foreignS3 = mcpDataS3($this->otherTeam);++ $clone = mcpDataCall($token, 'manage_service', ['action' => 'clone', 'uuid' => $own['service']->uuid, 'confirm' => true, 'data' => ['destination_uuid' => $this->theirs['destination']->uuid]]);+ $move = mcpDataCall($token, 'manage_service', ['action' => 'move', 'uuid' => $own['service']->uuid, 'confirm' => true, 'data' => ['environment_uuid' => $this->theirs['environment']->uuid]]);+ $import = mcpDataCall($token, 'manage_service', ['action' => 'import_database', 'uuid' => $own['service']->uuid, 'database_uuid' => $own['service_db']->uuid, 'confirm' => true, 'data' => ['source' => 's3', 's3_storage_uuid' => $foreignS3->uuid, 'path' => '/a.sql']]);++ expect(mcpDataIsError($clone))->toBeTrue()+ ->and(mcpDataIsError($move))->toBeTrue()+ ->and(mcpDataIsError($import))->toBeTrue()+ ->and(Service::count())->toBe(2)+ ->and($own['service']->fresh()->environment_id)->toBe($own['environment']->id);+});++test('manage_service destructive actions need confirm=true', function (string $action) {+ $own = $this->mine;+- $denied = mcpDataCall(mcpDataToken($this->user), 'manage_service', ['action' => $action, 'uuid' => $own['service']->uuid, 'database_uuid' => $own['service_db']->uuid, 'data' => ['destination_uuid' => 'x']]);++ $denied = mcpDataCall(mcpDataToken($this->user, ['write', 'deploy']), 'manage_service', ['action' => $action, 'uuid' => $own['service']->uuid, 'database_uuid' => $own['service_db']->uuid, 'data' => ['destination_uuid' => 'x']]);++ expect(mcpDataIsError($denied))->toBeTrue()+ ->and(mcpDataText($denied))->toContain('confirm=true')+ ->and($own['service']->fresh())->not->toBeNull();+})->with(['delete', 'clone', 'move', 'import_database']);++test('manage_service delete with confirm=true deletes an own service', function () {- $response = mcpDataCall(mcpDataToken($this->user), 'manage_service', ['action' => 'delete', 'uuid' => $this->mine['service']->uuid, 'confirm' => true]);++ $writeOnly = mcpDataCall(mcpDataToken($this->user), 'manage_service', ['action' => 'delete', 'uuid' => $this->mine['service']->uuid, 'confirm' => true]);++ expect(mcpDataIsError($writeOnly))->toBeTrue()++ ->and(mcpDataText($writeOnly))->toContain('Missing required permissions: deploy')++ ->and(Service::find($this->mine['service']->id))->not->toBeNull();++++ $response = mcpDataCall(mcpDataToken($this->user, ['write', 'deploy']), 'manage_service', ['action' => 'delete', 'uuid' => $this->mine['service']->uuid, 'confirm' => true]);++ expect(mcpDataIsError($response))->toBeFalse()+ ->and(Service::find($this->mine['service']->id))->toBeNull();+});++test('manage_service rejects read-only tokens', function () {+ $response = mcpDataCall(mcpDataToken($this->user, ['read']), 'manage_service', ['action' => 'update', 'uuid' => $this->mine['service']->uuid, 'data' => ['name' => 'nope']]);++ expect(mcpDataIsError($response))->toBeTrue()+ ->and($this->mine['service']->fresh()->name)->not->toBe('nope');+});++// manage_env++test('manage_env creates, updates, and deletes variables without returning values', function (string $resource) {+ $target = match ($resource) {+ 'application' => $this->mine['application'],+ 'database' => $this->mine['database'],+ 'service' => $this->mine['service'],+ };+ $token = mcpDataToken($this->user);+ $env = fn (string $key) => EnvironmentVariable::where('resourceable_type', $target->getMorphClass())->where('resourceable_id', $target->id)->where('key', $key)->where('is_preview', false)->first();++ $create = mcpDataCall($token, 'manage_env', ['action' => 'create', 'resource' => $resource, 'uuid' => $target->uuid, 'data' => ['key' => 'MCP_KEY', 'value' => 'first-secret-value']]);+ $update = mcpDataCall($token, 'manage_env', ['action' => 'update', 'resource' => $resource, 'uuid' => $target->uuid, 'data' => ['key' => 'MCP_KEY', 'value' => 'second-secret-value']]);++ expect(mcpDataIsError($create))->toBeFalse()+ ->and(mcpDataIsError($update))->toBeFalse()+ ->and($env('MCP_KEY')->value)->toBe('second-secret-value');+ foreach ([$create, $update] as $response) {+ expect(mcpDataText($response))->not->toContain('secret-value');+ }++ $uuid = $env('MCP_KEY')->uuid;+ $denied = mcpDataCall($token, 'manage_env', ['action' => 'delete', 'resource' => $resource, 'uuid' => $target->uuid, 'env_uuid' => $uuid]);+ expect(mcpDataIsError($denied))->toBeTrue()+ ->and(mcpDataText($denied))->toContain('confirm=true')+ ->and($env('MCP_KEY'))->not->toBeNull();++ $deleted = mcpDataCall($token, 'manage_env', ['action' => 'delete', 'resource' => $resource, 'uuid' => $target->uuid, 'env_uuid' => $uuid, 'confirm' => true]);+ expect(mcpDataIsError($deleted))->toBeFalse()+ ->and($env('MCP_KEY'))->toBeNull();+})->with(['application', 'database', 'service']);++test('manage_env bulk updates variables without returning values', function (string $resource) {+ $target = match ($resource) {+ 'application' => $this->mine['application'],+ 'database' => $this->mine['database'],+ 'service' => $this->mine['service'],+ };++ $bulk = mcpDataCall(mcpDataToken($this->user), 'manage_env', ['action' => 'bulk_update', 'resource' => $resource, 'uuid' => $target->uuid, 'data' => ['data' => [['key' => 'MCP_BULK', 'value' => 'bulk-secret-value']]]]);++ expect(mcpDataIsError($bulk))->toBeFalse()+ ->and(mcpDataText($bulk))->not->toContain('bulk-secret-value')+ ->and(EnvironmentVariable::where('resourceable_type', $target->getMorphClass())->where('resourceable_id', $target->id)->where('key', 'MCP_BULK')->where('is_preview', false)->sole()->value)->toBe('bulk-secret-value');+})->with(['application', 'database', 'service']);++test('manage_env cannot change variables of another team', function (string $action) {+ $foreign = $this->theirs['database'];+ $foreignEnv = mcpDataDbEnv($foreign, 'THEIR_KEY', 'their-value');+ $token = mcpDataToken($this->user);++ $viaForeignUuid = mcpDataCall($token, 'manage_env', ['action' => $action, 'resource' => 'database', 'uuid' => $foreign->uuid, 'env_uuid' => $foreignEnv->uuid, 'confirm' => true, 'data' => ['key' => 'THEIR_KEY', 'value' => 'hijacked', 'data' => [['key' => 'THEIR_KEY', 'value' => 'hijacked']]]]);+ $viaOwnUuid = mcpDataCall($token, 'manage_env', ['action' => 'delete', 'resource' => 'database', 'uuid' => $this->mine['database']->uuid, 'env_uuid' => $foreignEnv->uuid, 'confirm' => true]);++ expect(mcpDataIsError($viaForeignUuid))->toBeTrue()+ ->and(mcpDataIsError($viaOwnUuid))->toBeTrue()+ ->and($foreignEnv->fresh()->value)->toBe('their-value')+ ->and(EnvironmentVariable::where('resourceable_id', $foreign->id)->where('resourceable_type', $foreign->getMorphClass())->count())->toBe(1);+})->with(['create', 'update', 'bulk_update', 'delete']);++test('manage_env rejects read-only and member tokens', function () {+ $own = $this->mine['database'];+ $data = ['action' => 'create', 'resource' => 'database', 'uuid' => $own->uuid, 'data' => ['key' => 'DENIED', 'value' => 'x']];++ $read = mcpDataCall(mcpDataToken($this->user, ['read']), 'manage_env', $data);+ $member = mcpDataCall(mcpDataToken(mcpDataMember($this->team), ['write']), 'manage_env', $data);++ expect(mcpDataIsError($read))->toBeTrue()+ ->and(mcpDataIsError($member))->toBeTrue()+ ->and(EnvironmentVariable::where('key', 'DENIED')->exists())->toBeFalse();+});++// manage_shared_env++test('manage_shared_env creates, updates, and deletes shared variables in the token team', function (string $resource) {+ $args = match ($resource) {+ 'team' => [],+ 'project' => ['uuid' => $this->mine['project']->uuid],+ 'environment' => ['uuid' => $this->mine['project']->uuid, 'environment_name_or_uuid' => $this->mine['environment']->uuid],+ 'server' => ['uuid' => $this->mine['server']->uuid],+ };+ $token = mcpDataToken($this->user);++ $create = mcpDataCall($token, 'manage_shared_env', ['action' => 'create', 'resource' => $resource, 'data' => ['key' => 'SHARED_MCP', 'value' => 'shared-value']] + $args);+ expect(mcpDataIsError($create))->toBeFalse();+ $envId = mcpDataJson($create)['data']['id'];+ expect($envId)->not->toBeNull();+ $env = SharedEnvironmentVariable::where('key', 'SHARED_MCP')->sole();+ expect($env->team_id)->toBe($this->team->id)+ ->and($env->type)->toBe($resource);++ $update = mcpDataCall($token, 'manage_shared_env', ['action' => 'update', 'resource' => $resource, 'env_id' => (string) $envId, 'data' => ['value' => 'updated-value']] + $args);+ expect(mcpDataIsError($update))->toBeFalse()+ ->and($env->fresh()->value)->toBe('updated-value')+ ->and(mcpDataText($update))->not->toContain('updated-value');++ $denied = mcpDataCall($token, 'manage_shared_env', ['action' => 'delete', 'resource' => $resource, 'env_id' => (string) $envId] + $args);+ expect(mcpDataIsError($denied))->toBeTrue()+ ->and(mcpDataText($denied))->toContain('confirm=true')+ ->and($env->fresh())->not->toBeNull();++ $deleted = mcpDataCall($token, 'manage_shared_env', ['action' => 'delete', 'resource' => $resource, 'env_id' => (string) $envId, 'confirm' => true] + $args);+ expect(mcpDataIsError($deleted))->toBeFalse()+ ->and(SharedEnvironmentVariable::find($env->id))->toBeNull();+})->with(['team', 'project', 'environment', 'server']);++test('manage_shared_env cannot create in or change shared variables of another team', function (string $resource) {+ $foreignArgs = match ($resource) {+ 'team' => [],+ 'project' => ['uuid' => $this->theirs['project']->uuid],+ 'environment' => ['uuid' => $this->theirs['project']->uuid, 'environment_name_or_uuid' => $this->theirs['environment']->uuid],+ 'server' => ['uuid' => $this->theirs['server']->uuid],+ };+ $foreignEnv = SharedEnvironmentVariable::create([+ 'key' => 'THEIR_SHARED',+ 'value' => 'their-shared-value',+ 'type' => $resource,+ 'team_id' => $this->otherTeam->id,+ 'project_id' => in_array($resource, ['project', 'environment'], true) ? $this->theirs['project']->id : null,+ 'environment_id' => $resource === 'environment' ? $this->theirs['environment']->id : null,+ 'server_id' => $resource === 'server' ? $this->theirs['server']->id : null,+ ]);+ $token = mcpDataToken($this->user);++ $update = mcpDataCall($token, 'manage_shared_env', ['action' => 'update', 'resource' => $resource, 'env_id' => (string) $foreignEnv->id, 'data' => ['value' => 'hijacked']] + $foreignArgs);+ $delete = mcpDataCall($token, 'manage_shared_env', ['action' => 'delete', 'resource' => $resource, 'env_id' => (string) $foreignEnv->id, 'confirm' => true] + $foreignArgs);++ expect(mcpDataIsError($update))->toBeTrue()+ ->and(mcpDataIsError($delete))->toBeTrue()+ ->and($foreignEnv->fresh()->value)->toBe('their-shared-value');++ if ($resource !== 'team') {+ $create = mcpDataCall($token, 'manage_shared_env', ['action' => 'create', 'resource' => $resource, 'data' => ['key' => 'INJECTED', 'value' => 'x']] + $foreignArgs);+ expect(mcpDataIsError($create))->toBeTrue()+ ->and(SharedEnvironmentVariable::where('key', 'INJECTED')->exists())->toBeFalse();+ }+})->with(['team', 'project', 'environment', 'server']);++test('manage_shared_env rejects read-only tokens', function () {+ $response = mcpDataCall(mcpDataToken($this->user, ['read']), 'manage_shared_env', ['action' => 'create', 'resource' => 'team', 'data' => ['key' => 'DENIED_SHARED', 'value' => 'x']]);++ expect(mcpDataIsError($response))->toBeTrue()+ ->and(SharedEnvironmentVariable::where('key', 'DENIED_SHARED')->exists())->toBeFalse();+});++// get_env_values++test('get_env_values returns values for an owner token with read:sensitive', function () {+ $own = $this->mine['database'];+ mcpDataDbEnv($own, 'DB_VISIBLE', 'visible-value');+ mcpDataDbEnv($own, 'DB_ONCE', 'shown-once-value', shownOnce: true);+ SharedEnvironmentVariable::create(['key' => 'TEAM_VISIBLE', 'value' => 'team-value', 'type' => 'team', 'team_id' => $this->team->id]);+ $token = mcpDataToken($this->user, ['read', 'read:sensitive']);++ $database = mcpDataCall($token, 'get_env_values', ['action' => 'list', 'resource' => 'database', 'uuid' => $own->uuid]);+ $team = mcpDataCall($token, 'get_env_values', ['action' => 'list', 'resource' => 'team']);++ expect(mcpDataIsError($database))->toBeFalse()+ ->and(collect(mcpDataJson($database)['data'])->firstWhere('key', 'DB_VISIBLE')['value'])->toBe('visible-value')+ ->and(mcpDataText($database))->not->toContain('shown-once-value')+ ->and(mcpDataIsError($team))->toBeFalse()+ ->and(collect(mcpDataJson($team)['data'])->firstWhere('key', 'TEAM_VISIBLE')['value'])->toBe('team-value');+});++test('get_env_values never returns values without read:sensitive or to members', function (array $abilities, bool $asMember) {+ $own = $this->mine['database'];+ mcpDataDbEnv($own, 'DB_HIDDEN', 'hidden-value');+ $user = $asMember ? mcpDataMember($this->team) : $this->user;++ $response = mcpDataCall(mcpDataToken($user, $abilities), 'get_env_values', ['action' => 'list', 'resource' => 'database', 'uuid' => $own->uuid]);++ expect(mcpDataIsError($response))->toBeTrue()+ ->and(mcpDataText($response))->not->toContain('hidden-value');+})->with([+ 'read token' => [['read'], false],+ 'write token' => [['read', 'write'], false],+ 'member with read:sensitive' => [['read', 'read:sensitive'], true],+]);++test('get_env_values cannot read variables of another team', function (string $resource) {+ $foreign = $this->theirs;+ mcpDataDbEnv($foreign['database'], 'THEIR_DB', 'their-db-value');+ SharedEnvironmentVariable::create(['key' => 'THEIR_PROJECT', 'value' => 'their-project-value', 'type' => 'project', 'team_id' => $this->otherTeam->id, 'project_id' => $foreign['project']->id]);+ $args = match ($resource) {+ 'application' => ['uuid' => $foreign['application']->uuid],+ 'database' => ['uuid' => $foreign['database']->uuid],+ 'service' => ['uuid' => $foreign['service']->uuid],+ 'project' => ['uuid' => $foreign['project']->uuid],+ 'environment' => ['uuid' => $foreign['project']->uuid, 'environment_name_or_uuid' => $foreign['environment']->uuid],+ 'server' => ['uuid' => $foreign['server']->uuid],+ };++ $response = mcpDataCall(mcpDataToken($this->user, ['read', 'read:sensitive']), 'get_env_values', ['action' => 'list', 'resource' => $resource] + $args);++ expect(mcpDataIsError($response))->toBeTrue()+ ->and(mcpDataText($response))->not->toContain('their-');+})->with(['application', 'database', 'service', 'project', 'environment', 'server']);++test('get_env_values for the team returns only the token team variables', function () {+ SharedEnvironmentVariable::create(['key' => 'THEIR_TEAM', 'value' => 'their-team-value', 'type' => 'team', 'team_id' => $this->otherTeam->id]);++ $response = mcpDataCall(mcpDataToken($this->user, ['read', 'read:sensitive']), 'get_env_values', ['action' => 'list', 'resource' => 'team']);++ expect(mcpDataIsError($response))->toBeFalse()+ ->and(mcpDataText($response))->not->toContain('their-team-value');+});diff --cc tests/Feature/Mcp/McpOperationsToolsTest.phpindex 193639dfe9,0000000000..db2a0c60fbmode 100644,000000..100644--- a/tests/Feature/Mcp/McpOperationsToolsTest.php+++ b/tests/Feature/Mcp/McpOperationsToolsTest.php@@@ -1,618 -1,0 +1,618 @@@+<?php++use App\Actions\Service\DeployServiceApplication;+use App\Actions\Service\RestartServiceApplication;+use App\Actions\Service\StopServiceApplication;+use App\Jobs\DatabaseBackupJob;+use App\Jobs\ScheduledTaskJob;+use App\Jobs\VolumeBackupJob;+use App\Models\Application;+use App\Models\ApplicationDeploymentQueue;+use App\Models\Environment;+use App\Models\InstanceSettings;+use App\Models\LocalPersistentVolume;+use App\Models\Project;+use App\Models\S3Storage;+use App\Models\ScheduledDatabaseBackup;+use App\Models\ScheduledDatabaseBackupExecution;+use App\Models\ScheduledTask;+use App\Models\ScheduledVolumeBackup;+use App\Models\Server;+use App\Models\Service;+use App\Models\ServiceApplication;+use App\Models\ServiceDatabase;+use App\Models\StandaloneDocker;+use App\Models\StandalonePostgresql;+use App\Models\Tag;+use App\Models\Team;+use App\Models\User;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Once;++uses(RefreshDatabase::class);++beforeEach(function () {+ config()->set('app.maintenance.store', 'array');+ config()->set('cache.default', 'array');+ Server::flushIdentityMap();+ Process::fake();+ InstanceSettings::query()->delete();+ $settings = new InstanceSettings(['is_mcp_server_enabled' => true, 'is_api_enabled' => true]);+ $settings->id = 0;+ $settings->save();+ Once::flush();++ $this->team = Team::factory()->create();+ $this->user = User::factory()->create();+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);+ $this->own = mcpOpsSeedTeam($this->team);++ $this->otherTeam = Team::factory()->create();+ $this->otherUser = User::factory()->create();+ $this->otherTeam->members()->attach($this->otherUser->id, ['role' => 'owner']);+ $this->other = mcpOpsSeedTeam($this->otherTeam);++ session(['currentTeam' => $this->team]);+ Queue::fake();+});++/**+ * @return array<string, mixed>+ */+function mcpOpsSeedTeam(Team $team): array+{+ $server = Server::factory()->create(['team_id' => $team->id]);+ $server->settings->update(['is_reachable' => true, 'is_usable' => true, 'force_disabled' => false]);+ $destination = StandaloneDocker::query()->where('server_id', $server->id)->firstOrFail();+ $project = Project::factory()->create(['team_id' => $team->id]);+ $environment = Environment::factory()->create(['project_id' => $project->id]);+ $destinationAttributes = [+ 'environment_id' => $environment->id,+ 'destination_id' => $destination->id,+ 'destination_type' => $destination->getMorphClass(),+ ];++ $application = Application::factory()->create($destinationAttributes);+ $database = StandalonePostgresql::create([+ 'name' => 'ops-postgres-'.$team->id,+ 'image' => 'postgres:17-alpine',+ 'postgres_user' => 'postgres',+ 'postgres_password' => 'db-password-'.$team->id,+ 'postgres_db' => 'postgres',+ ...$destinationAttributes,+ ]);+ $service = Service::factory()->create($destinationAttributes);+ $serviceApplication = ServiceApplication::create([+ 'uuid' => new_public_id(),+ 'name' => 'ops-service-app',+ 'image' => 'nginx:alpine',+ 'service_id' => $service->id,+ ]);+ $serviceDatabase = ServiceDatabase::create([+ 'uuid' => new_public_id(),+ 'name' => 'ops-service-db',+ 'image' => 'postgres:17-alpine',+ 'service_id' => $service->id,+ ]);+ $volume = LocalPersistentVolume::create([+ 'name' => $application->uuid.'-data',+ 'mount_path' => '/data',+ 'resource_id' => $application->id,+ 'resource_type' => $application->getMorphClass(),+ ]);+ $s3 = S3Storage::create([+ 'name' => 'ops-s3-'.$team->id,+ 'region' => 'us-east-1',+ 'key' => 'S3KEY'.$team->id,+ 'secret' => 'S3SECRET'.$team->id,+ 'bucket' => 'bucket',+ 'endpoint' => 'https://s3.example.com',+ 'team_id' => $team->id,+ 'is_usable' => true,+ ]);++ return compact('server', 'destination', 'project', 'environment', 'application', 'database', 'service', 'serviceApplication', 'serviceDatabase', 'volume', 's3');+}++function mcpOpsToken(User $user, array $abilities = ['read', 'write']): string+{+ return $user->createToken('mcp-ops', $abilities)->plainTextToken;+}++function mcpOpsCall(string $token, string $tool, array $arguments = [])+{+ auth()->forgetGuards();++ return test()->withHeaders([+ 'Authorization' => 'Bearer '.$token,+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson('/mcp', [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'tools/call',+ 'params' => ['name' => $tool, 'arguments' => (object) $arguments],+ ]);+}++function mcpOpsText($response): string+{+ return (string) ($response->json('result.content.0.text') ?? $response->json('error.message'));+}++function mcpOpsIsError($response): bool+{+ return $response->json('result.isError') === true || $response->json('error') !== null;+}++function mcpOpsMember(Team $team): User+{+ $member = User::factory()->create();+ $team->members()->attach($member->id, ['role' => 'member']);++ return $member;+}++// ---------------------------------------------------------------- control++test('control starts, restarts, and stops a service application and service database of the token team', function () {+ $token = mcpOpsToken($this->user, ['read', 'deploy']);++ $start = mcpOpsCall($token, 'control', ['resource' => 'service_application', 'action' => 'start', 'service_uuid' => $this->own['service']->uuid, 'uuid' => $this->own['serviceApplication']->uuid]);+ expect(mcpOpsIsError($start))->toBeFalse()+ ->and(mcpOpsText($start))->toContain('deploy request queued');+ DeployServiceApplication::assertPushed();++ $restart = mcpOpsCall($token, 'control', ['resource' => 'service_database', 'action' => 'restart', 'service_uuid' => $this->own['service']->uuid, 'uuid' => $this->own['serviceDatabase']->uuid]);+ expect(mcpOpsIsError($restart))->toBeFalse()+ ->and(mcpOpsText($restart))->toContain('restart request queued');+ RestartServiceApplication::assertPushed();++ $stop = mcpOpsCall($token, 'control', ['resource' => 'service_application', 'action' => 'stop', 'service_uuid' => $this->own['service']->uuid, 'uuid' => $this->own['serviceApplication']->uuid, 'confirm' => true]);+ expect(mcpOpsIsError($stop))->toBeFalse();+ StopServiceApplication::assertPushed();+});++test('control rejects service children of another team, also under an own service_uuid', function (string $resource, string $childKey, bool $ownParent) {+ $token = mcpOpsToken($this->user, ['read', 'deploy']);+ $parent = $ownParent ? $this->own['service'] : $this->other['service'];++ $response = mcpOpsCall($token, 'control', ['resource' => $resource, 'action' => 'restart', 'service_uuid' => $parent->uuid, 'uuid' => $this->other[$childKey]->uuid]);++ expect(mcpOpsIsError($response))->toBeTrue()+ ->and(mcpOpsText($response))->toContain('not found');+ Queue::assertNothingPushed();+})->with([+ 'foreign app, own service' => ['service_application', 'serviceApplication', true],+ 'foreign app, foreign service' => ['service_application', 'serviceApplication', false],+ 'foreign db, own service' => ['service_database', 'serviceDatabase', true],+ 'foreign db, foreign service' => ['service_database', 'serviceDatabase', false],+]);++test('control service child stop needs confirm and service_uuid', function () {+ $token = mcpOpsToken($this->user, ['read', 'deploy']);++ $noConfirm = mcpOpsCall($token, 'control', ['resource' => 'service_application', 'action' => 'stop', 'service_uuid' => $this->own['service']->uuid, 'uuid' => $this->own['serviceApplication']->uuid]);+ expect(mcpOpsIsError($noConfirm))->toBeTrue()+ ->and(mcpOpsText($noConfirm))->toContain('confirm=true');++ $noParent = mcpOpsCall($token, 'control', ['resource' => 'service_database', 'action' => 'start', 'uuid' => $this->own['serviceDatabase']->uuid]);+ expect(mcpOpsIsError($noParent))->toBeTrue()+ ->and(mcpOpsText($noParent))->toContain('service_uuid');++ Queue::assertNothingPushed();+});++test('control service child rejects read-only and member tokens', function () {+ $args = ['resource' => 'service_application', 'action' => 'restart', 'service_uuid' => $this->own['service']->uuid, 'uuid' => $this->own['serviceApplication']->uuid];++ expect(mcpOpsIsError(mcpOpsCall(mcpOpsToken($this->user, ['read', 'write']), 'control', $args)))->toBeTrue();+ expect(mcpOpsIsError(mcpOpsCall(mcpOpsToken(mcpOpsMember($this->team), ['read', 'deploy']), 'control', $args)))->toBeTrue();++ Queue::assertNothingPushed();+});++// ---------------------------------------------------------------- deploy by tag++test('deploy by tag deploys only the token team resources with that tag', function () {+ $ownTag = Tag::create(['name' => 'prod', 'team_id' => $this->team->id]);+ $this->own['application']->tags()->attach($ownTag->id);+ $foreignTag = Tag::create(['name' => 'prod', 'team_id' => $this->otherTeam->id]);+ $this->other['application']->tags()->attach($foreignTag->id);++ $response = mcpOpsCall(mcpOpsToken($this->user, ['read', 'deploy']), 'deploy', ['tag' => 'prod', 'confirm' => true]);++ expect(mcpOpsIsError($response))->toBeFalse()+ ->and(mcpOpsText($response))->toContain($this->own['application']->uuid)+ ->and(ApplicationDeploymentQueue::where('application_id', $this->own['application']->id)->count())->toBe(1)+ ->and(ApplicationDeploymentQueue::where('application_id', $this->other['application']->id)->count())->toBe(0);+});++test('deploy by a tag that only another team has deploys nothing', function () {+ $foreignTag = Tag::create(['name' => 'theirs', 'team_id' => $this->otherTeam->id]);+ $this->other['application']->tags()->attach($foreignTag->id);++ $response = mcpOpsCall(mcpOpsToken($this->user, ['read', 'deploy']), 'deploy', ['tag' => 'theirs', 'confirm' => true]);++ expect(mcpOpsIsError($response))->toBeTrue()+ ->and(ApplicationDeploymentQueue::count())->toBe(0);+});++test('deploy by tag needs confirm and exactly one of uuid or tag', function (array $args, string $message) {+ $tag = Tag::create(['name' => 'prod', 'team_id' => $this->team->id]);+ $this->own['application']->tags()->attach($tag->id);+ $args = array_map(fn ($value) => $value === 'APP' ? $this->own['application']->uuid : $value, $args);++ $response = mcpOpsCall(mcpOpsToken($this->user, ['read', 'deploy']), 'deploy', $args);++ expect(mcpOpsIsError($response))->toBeTrue()+ ->and(mcpOpsText($response))->toContain($message)+ ->and(ApplicationDeploymentQueue::count())->toBe(0);+})->with([+ 'no confirm' => [['tag' => 'prod'], 'confirm=true'],+ 'both' => [['tag' => 'prod', 'uuid' => 'APP', 'confirm' => true], 'exactly one'],+ 'neither' => [[], 'exactly one'],+ 'tag with pull request' => [['tag' => 'prod', 'pull_request_id' => 3, 'confirm' => true], 'pull_request_id'],+]);++test('deploy by tag rejects read-only and member tokens', function () {+ $tag = Tag::create(['name' => 'prod', 'team_id' => $this->team->id]);+ $this->own['application']->tags()->attach($tag->id);++ expect(mcpOpsIsError(mcpOpsCall(mcpOpsToken($this->user, ['read', 'write']), 'deploy', ['tag' => 'prod', 'confirm' => true])))->toBeTrue();+ expect(mcpOpsIsError(mcpOpsCall(mcpOpsToken(mcpOpsMember($this->team), ['read', 'deploy']), 'deploy', ['tag' => 'prod', 'confirm' => true])))->toBeTrue();+ expect(ApplicationDeploymentQueue::count())->toBe(0);+});++// ---------------------------------------------------------------- manage_scheduled_task++test('manage_scheduled_task creates, updates, executes, and deletes tasks of the token team', function (string $resource, string $key) {- $token = mcpOpsToken($this->user);++ $token = mcpOpsToken($this->user, ['read', 'write', 'deploy']);+ $owner = $this->own[$key];++ $created = mcpOpsCall($token, 'manage_scheduled_task', ['action' => 'create', 'resource' => $resource, 'uuid' => $owner->uuid, 'data' => ['name' => 'cleanup', 'command' => 'echo SECRETCMD', 'frequency' => 'daily']]);+ expect(mcpOpsIsError($created))->toBeFalse()+ ->and(mcpOpsText($created))->not->toContain('SECRETCMD');+ $task = ScheduledTask::where('name', 'cleanup')->sole();+ expect($task->team_id)->toBe($this->team->id)+ ->and($task->{$resource.'_id'})->toBe($owner->id);++ $updated = mcpOpsCall($token, 'manage_scheduled_task', ['action' => 'update', 'resource' => $resource, 'uuid' => $owner->uuid, 'task_uuid' => $task->uuid, 'data' => ['frequency' => 'hourly']]);+ expect(mcpOpsIsError($updated))->toBeFalse()+ ->and($task->fresh()->frequency)->toBe('hourly');++ $executed = mcpOpsCall($token, 'manage_scheduled_task', ['action' => 'execute', 'resource' => $resource, 'uuid' => $owner->uuid, 'task_uuid' => $task->uuid, 'confirm' => true]);+ expect(mcpOpsIsError($executed))->toBeFalse();+ Queue::assertPushed(ScheduledTaskJob::class);++ $deleted = mcpOpsCall($token, 'manage_scheduled_task', ['action' => 'delete', 'resource' => $resource, 'uuid' => $owner->uuid, 'task_uuid' => $task->uuid, 'confirm' => true]);+ expect(mcpOpsIsError($deleted))->toBeFalse()+ ->and($task->fresh())->toBeNull();+})->with([+ 'application' => ['application', 'application'],+ 'service' => ['service', 'service'],+]);++test('manage_scheduled_task cannot reach tasks or resources of another team', function (string $action, bool $ownParent) {+ $foreignTask = ScheduledTask::factory()->create(['team_id' => $this->otherTeam->id, 'application_id' => $this->other['application']->id, 'name' => 'theirs']);+ $parent = $ownParent ? $this->own['application'] : $this->other['application'];+- $response = mcpOpsCall(mcpOpsToken($this->user), 'manage_scheduled_task', [++ $response = mcpOpsCall(mcpOpsToken($this->user, ['read', 'write', 'deploy']), 'manage_scheduled_task', [+ 'action' => $action, 'resource' => 'application', 'uuid' => $parent->uuid, 'task_uuid' => $foreignTask->uuid,+ 'confirm' => true, 'data' => $action === 'create' ? ['name' => 'evil', 'command' => 'id', 'frequency' => 'daily'] : ($action === 'update' ? ['name' => 'hijacked'] : []),+ ]);++ expect(mcpOpsIsError($response))->toBeTrue()+ ->and($foreignTask->fresh()?->name)->toBe('theirs')+ ->and(ScheduledTask::where('name', 'evil')->exists())->toBeFalse();+ Queue::assertNotPushed(ScheduledTaskJob::class);+})->with([+ 'create on foreign app' => ['create', false],+ 'update via own app' => ['update', true],+ 'update via foreign app' => ['update', false],+ 'delete via own app' => ['delete', true],+ 'execute via own app' => ['execute', true],+ 'execute via foreign app' => ['execute', false],+]);++test('manage_scheduled_task needs confirm for delete and execute and rejects read-only tokens', function () {+ $task = ScheduledTask::factory()->create(['team_id' => $this->team->id, 'application_id' => $this->own['application']->id]);- $token = mcpOpsToken($this->user);++ $token = mcpOpsToken($this->user, ['read', 'write', 'deploy']);++ foreach (['delete', 'execute'] as $action) {+ $response = mcpOpsCall($token, 'manage_scheduled_task', ['action' => $action, 'resource' => 'application', 'uuid' => $this->own['application']->uuid, 'task_uuid' => $task->uuid]);+ expect(mcpOpsIsError($response))->toBeTrue()+ ->and(mcpOpsText($response))->toContain('confirm=true');+ }++ $readOnly = mcpOpsCall(mcpOpsToken($this->user, ['read']), 'manage_scheduled_task', ['action' => 'execute', 'resource' => 'application', 'uuid' => $this->own['application']->uuid, 'task_uuid' => $task->uuid, 'confirm' => true]);+ expect(mcpOpsIsError($readOnly))->toBeTrue();++ $member = mcpOpsCall(mcpOpsToken(mcpOpsMember($this->team), ['read']), 'manage_scheduled_task', ['action' => 'delete', 'resource' => 'application', 'uuid' => $this->own['application']->uuid, 'task_uuid' => $task->uuid, 'confirm' => true]);+ expect(mcpOpsIsError($member))->toBeTrue();++ expect($task->fresh())->not->toBeNull();+ Queue::assertNotPushed(ScheduledTaskJob::class);+});++// ---------------------------------------------------------------- manage_backup++test('manage_backup creates, updates, runs, and deletes a backup schedule of the token team', function () {- $token = mcpOpsToken($this->user);++ $token = mcpOpsToken($this->user, ['read', 'write', 'deploy']);+ $database = $this->own['database'];++ $created = mcpOpsCall($token, 'manage_backup', ['action' => 'create', 'uuid' => $database->uuid, 'data' => ['frequency' => 'daily', 'save_s3' => true, 's3_storage_uuid' => $this->own['s3']->uuid]]);+ expect(mcpOpsIsError($created))->toBeFalse()+ ->and(mcpOpsText($created))->not->toContain('S3SECRET')+ ->and(mcpOpsText($created))->not->toContain('S3KEY');+ $backup = ScheduledDatabaseBackup::where('database_id', $database->id)->sole();+ expect($backup->team_id)->toBe($this->team->id)+ ->and($backup->s3_storage_id)->toBe($this->own['s3']->id);++ $updated = mcpOpsCall($token, 'manage_backup', ['action' => 'update', 'uuid' => $database->uuid, 'scheduled_backup_uuid' => $backup->uuid, 'data' => ['frequency' => 'hourly', 'backup_now' => true]]);+ expect(mcpOpsIsError($updated))->toBeFalse()+ ->and($backup->fresh()->frequency)->toBe('hourly');+ Queue::assertPushed(DatabaseBackupJob::class);++ $execution = ScheduledDatabaseBackupExecution::create(['scheduled_database_backup_id' => $backup->id, 'database_name' => 'postgres', 'status' => 'success']);+ $deletedExecution = mcpOpsCall($token, 'manage_backup', ['action' => 'delete_execution', 'uuid' => $database->uuid, 'scheduled_backup_uuid' => $backup->uuid, 'execution_uuid' => $execution->uuid, 'confirm' => true]);+ expect(mcpOpsIsError($deletedExecution))->toBeFalse()+ ->and($execution->fresh())->toBeNull();++ $deleted = mcpOpsCall($token, 'manage_backup', ['action' => 'delete', 'uuid' => $database->uuid, 'scheduled_backup_uuid' => $backup->uuid, 'confirm' => true]);+ expect(mcpOpsIsError($deleted))->toBeFalse()+ ->and($backup->fresh())->toBeNull();+});++test('manage_backup rejects an S3 storage of another team', function () {+ $token = mcpOpsToken($this->user);+ $database = $this->own['database'];++ $created = mcpOpsCall($token, 'manage_backup', ['action' => 'create', 'uuid' => $database->uuid, 'data' => ['frequency' => 'daily', 'save_s3' => true, 's3_storage_uuid' => $this->other['s3']->uuid]]);+ expect(mcpOpsIsError($created))->toBeTrue()+ ->and(ScheduledDatabaseBackup::where('database_id', $database->id)->exists())->toBeFalse();++ $backup = ScheduledDatabaseBackup::create(['team_id' => $this->team->id, 'frequency' => 'daily', 'database_id' => $database->id, 'database_type' => $database->getMorphClass()]);+ $updated = mcpOpsCall($token, 'manage_backup', ['action' => 'update', 'uuid' => $database->uuid, 'scheduled_backup_uuid' => $backup->uuid, 'data' => ['save_s3' => true, 's3_storage_uuids' => [$this->other['s3']->uuid], 'frequency' => 'hourly']]);+ expect(mcpOpsIsError($updated))->toBeTrue()+ ->and($backup->fresh()->s3_storage_id)->toBeNull()+ ->and($backup->fresh()->frequency)->toBe('daily')+ ->and($backup->fresh()->s3Storages()->exists())->toBeFalse();+});++test('manage_backup cannot reach backups of another team', function (string $action, bool $ownParent) {+ $foreignDatabase = $this->other['database'];+ $foreignBackup = ScheduledDatabaseBackup::create(['team_id' => $this->otherTeam->id, 'frequency' => 'daily', 'database_id' => $foreignDatabase->id, 'database_type' => $foreignDatabase->getMorphClass()]);+ $foreignExecution = ScheduledDatabaseBackupExecution::create(['scheduled_database_backup_id' => $foreignBackup->id, 'database_name' => 'postgres', 'status' => 'success']);+ $parent = $ownParent ? $this->own['database'] : $foreignDatabase;++ $response = mcpOpsCall(mcpOpsToken($this->user), 'manage_backup', [+ 'action' => $action, 'uuid' => $parent->uuid, 'scheduled_backup_uuid' => $foreignBackup->uuid, 'execution_uuid' => $foreignExecution->uuid,+ 'confirm' => true, 'data' => $action === 'delete' || $action === 'delete_execution' ? [] : ['frequency' => 'hourly', 'backup_now' => true],+ ]);++ expect(mcpOpsIsError($response))->toBeTrue()+ ->and($foreignBackup->fresh()?->frequency)->toBe('daily')+ ->and($foreignExecution->fresh())->not->toBeNull()+ ->and(ScheduledDatabaseBackup::where('team_id', $this->team->id)->exists())->toBeFalse();+ Queue::assertNotPushed(DatabaseBackupJob::class);+})->with([+ 'create on foreign db' => ['create', false],+ 'update via own db' => ['update', true],+ 'update via foreign db' => ['update', false],+ 'delete via own db' => ['delete', true],+ 'delete execution via own db' => ['delete_execution', true],+ 'delete execution via foreign db' => ['delete_execution', false],+]);++test('manage_backup needs confirm for deletes and rejects read-only tokens', function () {+ $database = $this->own['database'];+ $backup = ScheduledDatabaseBackup::create(['team_id' => $this->team->id, 'frequency' => 'daily', 'database_id' => $database->id, 'database_type' => $database->getMorphClass()]);+ $execution = ScheduledDatabaseBackupExecution::create(['scheduled_database_backup_id' => $backup->id, 'database_name' => 'postgres', 'status' => 'success']);+ $token = mcpOpsToken($this->user);++ foreach (['delete', 'delete_execution'] as $action) {+ $response = mcpOpsCall($token, 'manage_backup', ['action' => $action, 'uuid' => $database->uuid, 'scheduled_backup_uuid' => $backup->uuid, 'execution_uuid' => $execution->uuid]);+ expect(mcpOpsIsError($response))->toBeTrue()+ ->and(mcpOpsText($response))->toContain('confirm=true');+ }++ $readOnly = mcpOpsCall(mcpOpsToken($this->user, ['read']), 'manage_backup', ['action' => 'create', 'uuid' => $database->uuid, 'data' => ['frequency' => 'daily']]);+ expect(mcpOpsIsError($readOnly))->toBeTrue()+ ->and($backup->fresh())->not->toBeNull()+ ->and($execution->fresh())->not->toBeNull()+ ->and(ScheduledDatabaseBackup::count())->toBe(1);+});++// ---------------------------------------------------------------- manage_storage++test('manage_storage creates, updates, and deletes storages of the token team', function () {+ $token = mcpOpsToken($this->user);+ $application = $this->own['application'];++ $created = mcpOpsCall($token, 'manage_storage', ['action' => 'create', 'resource' => 'application', 'uuid' => $application->uuid, 'data' => ['type' => 'persistent', 'name' => 'cache', 'mount_path' => '/cache']]);+ expect(mcpOpsIsError($created))->toBeFalse();+ $volume = LocalPersistentVolume::where('name', $application->uuid.'-cache')->sole();++ $updated = mcpOpsCall($token, 'manage_storage', ['action' => 'update', 'resource' => 'application', 'uuid' => $application->uuid, 'data' => ['type' => 'persistent', 'uuid' => $volume->uuid, 'mount_path' => '/cache2']]);+ expect(mcpOpsIsError($updated))->toBeFalse()+ ->and($volume->fresh()->mount_path)->toBe('/cache2');++ $dbCreated = mcpOpsCall($token, 'manage_storage', ['action' => 'create', 'resource' => 'database', 'uuid' => $this->own['database']->uuid, 'data' => ['type' => 'persistent', 'name' => 'extra', 'mount_path' => '/extra']]);+ expect(mcpOpsIsError($dbCreated))->toBeFalse();++ $serviceCreated = mcpOpsCall($token, 'manage_storage', ['action' => 'create', 'resource' => 'service', 'uuid' => $this->own['service']->uuid, 'data' => ['type' => 'persistent', 'name' => 'svc', 'mount_path' => '/svc', 'resource_uuid' => $this->own['serviceApplication']->uuid]]);+ expect(mcpOpsIsError($serviceCreated))->toBeFalse()+ ->and(LocalPersistentVolume::where('resource_id', $this->own['serviceApplication']->id)->where('mount_path', '/svc')->exists())->toBeTrue();++ $deleted = mcpOpsCall($token, 'manage_storage', ['action' => 'delete', 'resource' => 'application', 'uuid' => $application->uuid, 'storage_uuid' => $volume->uuid, 'confirm' => true]);+ expect(mcpOpsIsError($deleted))->toBeFalse()+ ->and($volume->fresh())->toBeNull();+});++test('manage_storage sets, runs, and removes a volume backup without returning S3 secrets', function () {- $token = mcpOpsToken($this->user);++ $token = mcpOpsToken($this->user, ['read', 'write', 'deploy']);+ $args = ['resource' => 'application', 'uuid' => $this->own['application']->uuid, 'storage_uuid' => $this->own['volume']->uuid];++ $set = mcpOpsCall($token, 'manage_storage', [...$args, 'action' => 'set_backup', 'data' => ['frequency' => 'daily', 'save_s3' => true, 's3_storage_uuid' => $this->own['s3']->uuid]]);+ expect(mcpOpsIsError($set))->toBeFalse()+ ->and(mcpOpsText($set))->not->toContain('S3SECRET')+ ->and(mcpOpsText($set))->not->toContain('S3KEY');+ $backup = ScheduledVolumeBackup::query()->sole();+ expect($backup->s3_storage_id)->toBe($this->own['s3']->id);++ $run = mcpOpsCall($token, 'manage_storage', [...$args, 'action' => 'run_backup', 'confirm' => true]);+ expect(mcpOpsIsError($run))->toBeFalse();+ Queue::assertPushed(VolumeBackupJob::class);++ $removed = mcpOpsCall($token, 'manage_storage', [...$args, 'action' => 'remove_backup', 'confirm' => true]);+ expect(mcpOpsIsError($removed))->toBeFalse()+ ->and($backup->fresh())->toBeNull();+});++test('manage_storage rejects an S3 storage and a service child of another team', function () {+ $token = mcpOpsToken($this->user);++ $set = mcpOpsCall($token, 'manage_storage', ['action' => 'set_backup', 'resource' => 'application', 'uuid' => $this->own['application']->uuid, 'storage_uuid' => $this->own['volume']->uuid, 'data' => ['frequency' => 'daily', 'save_s3' => true, 's3_storage_uuid' => $this->other['s3']->uuid]]);+ expect(mcpOpsIsError($set))->toBeTrue()+ ->and(ScheduledVolumeBackup::query()->exists())->toBeFalse();++ $create = mcpOpsCall($token, 'manage_storage', ['action' => 'create', 'resource' => 'service', 'uuid' => $this->own['service']->uuid, 'data' => ['type' => 'persistent', 'name' => 'evil', 'mount_path' => '/evil', 'resource_uuid' => $this->other['serviceApplication']->uuid]]);+ expect(mcpOpsIsError($create))->toBeTrue()+ ->and(LocalPersistentVolume::where('mount_path', '/evil')->exists())->toBeFalse();+});++test('manage_storage cannot reach storages of another team', function (string $action, bool $ownParent) {+ $foreignVolume = $this->other['volume'];+ $foreignVolume->scheduledBackups()->create(['team_id' => $this->otherTeam->id, 'frequency' => 'daily']);+ $parent = $ownParent ? $this->own['application'] : $this->other['application'];+- $response = mcpOpsCall(mcpOpsToken($this->user), 'manage_storage', [++ $response = mcpOpsCall(mcpOpsToken($this->user, ['read', 'write', 'deploy']), 'manage_storage', [+ 'action' => $action, 'resource' => 'application', 'uuid' => $parent->uuid, 'storage_uuid' => $foreignVolume->uuid, 'confirm' => true,+ 'data' => match ($action) {+ 'create' => ['type' => 'persistent', 'name' => 'evil', 'mount_path' => '/evil'],+ 'update' => ['type' => 'persistent', 'uuid' => $foreignVolume->uuid, 'mount_path' => '/hijacked'],+ 'set_backup' => ['frequency' => 'hourly'],+ default => [],+ },+ ]);++ expect(mcpOpsIsError($response))->toBeTrue()+ ->and($foreignVolume->fresh()?->mount_path)->toBe('/data')+ ->and($foreignVolume->scheduledBackups()->sole()->frequency)->toBe('daily')+ ->and(LocalPersistentVolume::where('mount_path', '/evil')->exists())->toBeFalse();+ Queue::assertNotPushed(VolumeBackupJob::class);+})->with([+ 'create on foreign app' => ['create', false],+ 'update via own app' => ['update', true],+ 'update via foreign app' => ['update', false],+ 'delete via own app' => ['delete', true],+ 'set backup via own app' => ['set_backup', true],+ 'run backup via own app' => ['run_backup', true],+ 'run backup via foreign app' => ['run_backup', false],+ 'remove backup via own app' => ['remove_backup', true],+]);++test('manage_storage needs confirm for delete, remove_backup, and run_backup and rejects read-only tokens', function () {+ $this->own['volume']->scheduledBackups()->create(['team_id' => $this->team->id, 'frequency' => 'daily']);+ $args = ['resource' => 'application', 'uuid' => $this->own['application']->uuid, 'storage_uuid' => $this->own['volume']->uuid];- $token = mcpOpsToken($this->user);++ $token = mcpOpsToken($this->user, ['read', 'write', 'deploy']);++ foreach (['delete', 'remove_backup', 'run_backup'] as $action) {+ $response = mcpOpsCall($token, 'manage_storage', [...$args, 'action' => $action]);+ expect(mcpOpsIsError($response))->toBeTrue()+ ->and(mcpOpsText($response))->toContain('confirm=true');+ }++ $readOnly = mcpOpsCall(mcpOpsToken($this->user, ['read']), 'manage_storage', [...$args, 'action' => 'delete', 'confirm' => true]);+ expect(mcpOpsIsError($readOnly))->toBeTrue()+ ->and($this->own['volume']->fresh())->not->toBeNull()+ ->and(ScheduledVolumeBackup::count())->toBe(1);+ Queue::assertNotPushed(VolumeBackupJob::class);+});++// ---------------------------------------------------------------- manage_tags++test('manage_tags creates, renames, attaches, detaches, and deletes tags of the token team', function () {+ $token = mcpOpsToken($this->user);++ $created = mcpOpsCall($token, 'manage_tags', ['action' => 'create', 'data' => ['name' => 'Web']]);+ expect(mcpOpsIsError($created))->toBeFalse();+ $tag = Tag::where('team_id', $this->team->id)->where('name', 'web')->sole();++ $renamed = mcpOpsCall($token, 'manage_tags', ['action' => 'update', 'tag_uuid' => $tag->uuid, 'data' => ['name' => 'frontend']]);+ expect(mcpOpsIsError($renamed))->toBeFalse()+ ->and($tag->fresh()->name)->toBe('frontend');++ foreach (['application', 'database', 'service'] as $resource) {+ $attached = mcpOpsCall($token, 'manage_tags', ['action' => 'attach', 'resource' => $resource, 'uuid' => $this->own[$resource]->uuid, 'data' => ['tag_name' => 'frontend']]);+ expect(mcpOpsIsError($attached))->toBeFalse()+ ->and($this->own[$resource]->tags()->whereKey($tag->id)->exists())->toBeTrue();+ }++ $detached = mcpOpsCall($token, 'manage_tags', ['action' => 'detach', 'resource' => 'application', 'uuid' => $this->own['application']->uuid, 'tag_uuid' => $tag->uuid]);+ expect(mcpOpsIsError($detached))->toBeFalse()+ ->and($this->own['application']->tags()->whereKey($tag->id)->exists())->toBeFalse();++ $deleted = mcpOpsCall($token, 'manage_tags', ['action' => 'delete', 'tag_uuid' => $tag->uuid, 'confirm' => true]);+ expect(mcpOpsIsError($deleted))->toBeFalse()+ ->and($tag->fresh())->toBeNull();+});++test('manage_tags attach never links a tag of another team', function () {+ $foreignTag = Tag::create(['name' => 'shared', 'team_id' => $this->otherTeam->id]);++ $response = mcpOpsCall(mcpOpsToken($this->user), 'manage_tags', ['action' => 'attach', 'resource' => 'application', 'uuid' => $this->own['application']->uuid, 'data' => ['tag_name' => 'shared']]);++ expect(mcpOpsIsError($response))->toBeFalse()+ ->and(mcpOpsText($response))->not->toContain($foreignTag->uuid)+ ->and($this->own['application']->tags()->whereKey($foreignTag->id)->exists())->toBeFalse()+ ->and($this->own['application']->tags()->sole()->team_id)->toBe($this->team->id);+});++test('manage_tags cannot change tags or resources of another team', function (string $action) {+ $foreignTag = Tag::create(['name' => 'theirs', 'team_id' => $this->otherTeam->id]);+ $this->other['application']->tags()->attach($foreignTag->id);+ $ownTag = Tag::create(['name' => 'mine', 'team_id' => $this->team->id]);+ $this->own['application']->tags()->attach($ownTag->id);++ $args = match ($action) {+ 'update' => ['tag_uuid' => $foreignTag->uuid, 'data' => ['name' => 'hijacked']],+ 'delete' => ['tag_uuid' => $foreignTag->uuid],+ 'attach to foreign app' => ['resource' => 'application', 'uuid' => $this->other['application']->uuid, 'data' => ['tag_name' => 'evil']],+ 'detach foreign tag from own app' => ['resource' => 'application', 'uuid' => $this->own['application']->uuid, 'tag_uuid' => $foreignTag->uuid],+ 'detach from foreign app' => ['resource' => 'application', 'uuid' => $this->other['application']->uuid, 'tag_uuid' => $foreignTag->uuid],+ };+ $toolAction = str_starts_with($action, 'attach') ? 'attach' : (str_starts_with($action, 'detach') ? 'detach' : $action);++ $response = mcpOpsCall(mcpOpsToken($this->user), 'manage_tags', ['action' => $toolAction, 'confirm' => true, ...$args]);++ expect(mcpOpsIsError($response))->toBeTrue()+ ->and($foreignTag->fresh()?->name)->toBe('theirs')+ ->and($this->other['application']->tags()->whereKey($foreignTag->id)->exists())->toBeTrue()+ ->and(Tag::where('name', 'evil')->exists())->toBeFalse();+})->with([+ 'update',+ 'delete',+ 'attach to foreign app',+ 'detach foreign tag from own app',+ 'detach from foreign app',+]);++test('manage_tags delete needs confirm and write actions reject read-only and member tokens', function () {+ $tag = Tag::create(['name' => 'mine', 'team_id' => $this->team->id]);++ $noConfirm = mcpOpsCall(mcpOpsToken($this->user), 'manage_tags', ['action' => 'delete', 'tag_uuid' => $tag->uuid]);+ expect(mcpOpsIsError($noConfirm))->toBeTrue()+ ->and(mcpOpsText($noConfirm))->toContain('confirm=true');++ $readOnly = mcpOpsCall(mcpOpsToken($this->user, ['read']), 'manage_tags', ['action' => 'create', 'data' => ['name' => 'nope']]);+ expect(mcpOpsIsError($readOnly))->toBeTrue();++ $member = mcpOpsCall(mcpOpsToken(mcpOpsMember($this->team), ['read', 'write']), 'manage_tags', ['action' => 'create', 'data' => ['name' => 'nope']]);+ expect(mcpOpsIsError($member))->toBeTrue();++ expect($tag->fresh())->not->toBeNull()+ ->and(Tag::where('name', 'nope')->exists())->toBeFalse();+});diff --cc tests/Feature/Mcp/McpServerToolsTest.phpindex ca962a5391,0000000000..36dafa8f07mode 100644,000000..100644--- a/tests/Feature/Mcp/McpServerToolsTest.php+++ b/tests/Feature/Mcp/McpServerToolsTest.php@@@ -1,863 -1,0 +1,883 @@@+<?php++use App\Actions\Destination\RemoveStandaloneDockerNetwork;+use App\Jobs\DockerCleanupJob;+use App\Jobs\RestartProxyJob;+use App\Models\AuditEvent;+use App\Models\CloudProviderToken;+use App\Models\DiscordNotificationSettings;+use App\Models\GithubApp;+use App\Models\GitlabApp;+use App\Models\InstanceSettings;+use App\Models\PrivateKey;+use App\Models\S3Storage;+use App\Models\Server;+use App\Models\StandaloneDocker;+use App\Models\Team;+use App\Models\TelegramNotificationSettings;+use App\Models\User;+use App\Services\SentinelMetricsClient;+use Illuminate\Foundation\Testing\RefreshDatabase;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Process;+use Illuminate\Support\Facades\Queue;+use Illuminate\Support\Facades\Storage;+use Illuminate\Support\Once;++uses(RefreshDatabase::class);++const MCP_SRV_NEW_PRIVATE_KEY = '-----BEGIN OPENSSH PRIVATE KEY-----+b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW+QyNTUxOQAAACAuIzppW7xQGiSHBiMiQxJlsTq+XfUhnrUCHwYbbaLF/QAAAJDAOcCswDnA+rAAAAAtzc2gtZWQyNTUxOQAAACAuIzppW7xQGiSHBiMiQxJlsTq+XfUhnrUCHwYbbaLF/Q+AAAECKtKd242pj0qdKWaOpXAQFI2ZGLQOg9vCP2+o+LPLMtS4jOmlbvFAaJIcGIyJDEmWx+Or5d9SGetQIfBhttosX9AAAACG1jcC10ZXN0AQIDBAU=+-----END OPENSSH PRIVATE KEY-----';++class McpSrvStubMetricsClient extends SentinelMetricsClient+{+ public static int $calls = 0;++ public function summary(): ?array+ {+ self::$calls++;++ return [+ 'online' => true, 'cpu' => 42.5, 'memUsed' => 1024, 'memTotal' => 4096,+ 'diskUsed' => 10, 'diskTotal' => 100, 'diskPercent' => 10.0,+ 'load1' => 0.5, 'netRx' => 5.0, 'netTx' => 1.0,+ ];+ }++ public function history(string $metric, string $range): array+ {+ self::$calls++;+ if ($metric === 'disk') {+ throw new RuntimeException('Disk endpoint unavailable.');+ }++ return [+ [now()->subHours(3)->getTimestampMs(), 1.0],+ [now()->subMinutes(10)->getTimestampMs(), $metric === 'cpu' ? 42.5 : 1024.0],+ ];+ }++ public function networkHistory(string $range): array+ {+ self::$calls++;++ return ['rx' => [[now()->subMinutes(5)->getTimestampMs(), 5.0]], 'tx' => [[now()->subMinutes(5)->getTimestampMs(), 1.0]]];+ }+}++beforeEach(function () {+ Server::flushIdentityMap();+ Queue::fake();+ Process::fake();+ Storage::fake('ssh-keys');+ Storage::fake('ssh-mux');+ Http::preventStrayRequests();+ config()->set('app.maintenance.store', 'array');+ config()->set('cache.default', 'array');+ config()->set('constants.ssh.mux_enabled', false);++ InstanceSettings::query()->delete();+ $settings = new InstanceSettings(['is_mcp_server_enabled' => true, 'is_api_enabled' => true]);+ $settings->id = 0;+ $settings->save();+ Once::flush();++ $this->team = Team::factory()->create();+ $this->user = User::factory()->create();+ $this->team->members()->attach($this->user->id, ['role' => 'owner']);++ $this->otherTeam = Team::factory()->create();+ $this->otherUser = User::factory()->create();+ $this->otherTeam->members()->attach($this->otherUser->id, ['role' => 'owner']);++ $this->key = PrivateKey::factory()->create(['team_id' => $this->team->id]);+ $this->otherKey = PrivateKey::factory()->create(['team_id' => $this->otherTeam->id]);++ $this->server = Server::factory()->create(['team_id' => $this->team->id, 'private_key_id' => $this->key->id]);+ $this->otherServer = Server::factory()->create(['team_id' => $this->otherTeam->id, 'private_key_id' => $this->otherKey->id, 'name' => 'Theirs']);++ session(['currentTeam' => $this->team]);+});++afterEach(function () {+ Server::flushIdentityMap();+});++function mcpSrvToken(User $user, array $abilities = ['read', 'write']): string+{+ return $user->createToken('mcp-srv', $abilities)->plainTextToken;+}++function mcpSrvCall(string $token, string $tool, array $arguments = [])+{+ return test()->withHeaders([+ 'Authorization' => 'Bearer '.$token,+ 'Accept' => 'application/json, text/event-stream',+ ])->postJson('/mcp', [+ 'jsonrpc' => '2.0',+ 'id' => 1,+ 'method' => 'tools/call',+ 'params' => ['name' => $tool, 'arguments' => (object) $arguments],+ ]);+}++function mcpSrvText($response): string+{+ return (string) ($response->json('result.content.0.text') ?? $response->json('error.message'));+}++function mcpSrvIsError($response): bool+{+ return $response->json('result.isError') === true || $response->json('error') !== null;+}++function mcpSrvData($response): mixed+{+ return json_decode(mcpSrvText($response), true)['data'] ?? null;+}++function mcpSrvMakeFunctional(Server $server): void+{+ $server->settings->update(['is_reachable' => true, 'is_usable' => true, 'force_disabled' => false]);+ Server::flushIdentityMap();+}++function mcpSrvGithubApp(Team $team, PrivateKey $key, array $overrides = []): GithubApp+{+ return GithubApp::create(array_merge([+ 'name' => 'gh-'.$team->id,+ 'api_url' => 'https://api.github.com',+ 'html_url' => 'https://github.com',+ 'app_id' => 1234,+ 'installation_id' => 5678,+ 'client_id' => 'client-id',+ 'client_secret' => 'GH_CLIENT_SECRET_VALUE',+ 'webhook_secret' => 'GH_WEBHOOK_SECRET_VALUE',+ 'private_key_id' => $key->id,+ 'team_id' => $team->id,+ 'is_system_wide' => false,+ ], $overrides));+}++function mcpSrvS3(Team $team, array $overrides = []): S3Storage+{+ return S3Storage::create(array_merge([+ 'team_id' => $team->id,+ 'name' => 'S3 '.$team->id,+ 'region' => 'us-east-1',+ 'key' => 'S3_ACCESS_KEY_VALUE',+ 'secret' => 'S3_SECRET_KEY_VALUE',+ 'bucket' => 'test-bucket',+ 'endpoint' => 'https://s3.amazonaws.com',+ 'is_usable' => false,+ ], $overrides));+}++// ---------------------------------------------------------------- shared checks++test('server group write actions reject read-only tokens', function (string $tool, array $arguments) {+ $response = mcpSrvCall(mcpSrvToken($this->user, ['read']), $tool, $arguments + ['confirm' => true]);++ expect(mcpSrvIsError($response))->toBeTrue()- ->and(mcpSrvText($response))->toMatch('/Missing required permissions: write|Tool \[\w+\] not found/');++ ->and(mcpSrvText($response))->toMatch('/Missing required permissions: (write|deploy)|Tool \[\w+\] not found/');+})->with([+ 'manage_server create' => ['manage_server', ['action' => 'create', 'data' => ['ip' => '203.0.113.50']]],+ 'manage_proxy restart' => ['manage_proxy', ['action' => 'restart', 'uuid' => 'x']],+ 'docker_cleanup run' => ['docker_cleanup', ['action' => 'run', 'uuid' => 'x']],+ 'manage_destination create' => ['manage_destination', ['action' => 'create', 'server_uuid' => 'x']],+ 'manage_registry create' => ['manage_registry', ['action' => 'create', 'uuid' => 'x']],+ 'manage_private_key create' => ['manage_private_key', ['action' => 'create']],+ 'manage_s3_storage create' => ['manage_s3_storage', ['action' => 'create']],+ 'manage_git_source create' => ['manage_git_source', ['action' => 'create', 'resource' => 'github']],+ 'cloud_provider provision_server' => ['cloud_provider', ['action' => 'provision_server', 'resource' => 'hetzner']],+ 'manage_notifications update' => ['manage_notifications', ['action' => 'update', 'resource' => 'discord']],+]);++test('server group write actions reject member tokens', function (string $tool, array $arguments) {+ $member = User::factory()->create();+ $this->team->members()->attach($member->id, ['role' => 'member']);++ $response = mcpSrvCall(mcpSrvToken($member, ['read', 'write']), $tool, $arguments + ['confirm' => true]);++ expect($response->json('result'))->toBeNull()+ ->and($response->json('error.message'))->toBe('Missing required team role.');+})->with([+ 'manage_server update' => ['manage_server', ['action' => 'update', 'data' => ['name' => 'x']]],+ 'manage_private_key create' => ['manage_private_key', ['action' => 'create']],+ 'manage_registry list' => ['manage_registry', ['action' => 'list']],+ 'cloud_provider create_token' => ['cloud_provider', ['action' => 'create_token']],+ 'manage_notifications update' => ['manage_notifications', ['action' => 'update', 'resource' => 'email']],+]);++test('server group destructive actions need confirm=true', function (string $tool, array $arguments) {- $response = mcpSrvCall(mcpSrvToken($this->user), $tool, $arguments);++ $response = mcpSrvCall(mcpSrvToken($this->user, ['read', 'write', 'deploy']), $tool, $arguments);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(mcpSrvText($response))->toContain('requires confirm=true');+ Queue::assertNothingPushed();+})->with([+ 'manage_server delete' => ['manage_server', ['action' => 'delete', 'uuid' => 'x']],+ 'manage_proxy update' => ['manage_proxy', ['action' => 'update', 'uuid' => 'x']],+ 'manage_proxy set_configuration' => ['manage_proxy', ['action' => 'set_configuration', 'uuid' => 'x']],+ 'manage_proxy restart' => ['manage_proxy', ['action' => 'restart', 'uuid' => 'x']],+ 'docker_cleanup run' => ['docker_cleanup', ['action' => 'run', 'uuid' => 'x']],+ 'manage_destination delete' => ['manage_destination', ['action' => 'delete', 'uuid' => 'x']],+ 'manage_registry delete' => ['manage_registry', ['action' => 'delete', 'uuid' => 'x', 'registry' => 'ghcr.io']],+ 'manage_private_key delete' => ['manage_private_key', ['action' => 'delete', 'uuid' => 'x']],+ 'manage_s3_storage delete' => ['manage_s3_storage', ['action' => 'delete', 'uuid' => 'x']],+ 'manage_git_source delete' => ['manage_git_source', ['action' => 'delete', 'resource' => 'github', 'source_id' => '1']],+ 'cloud_provider delete_token' => ['cloud_provider', ['action' => 'delete_token', 'uuid' => 'x']],+ 'cloud_provider provision_server' => ['cloud_provider', ['action' => 'provision_server', 'resource' => 'hetzner']],+]);++// ---------------------------------------------------------------- manage_server++test('manage_server creates a server in the token team with a team private key', function () {+ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_server', ['action' => 'create', 'data' => [+ 'name' => 'mcp-server', 'ip' => '203.0.113.50', 'private_key_uuid' => $this->key->uuid,+ ]]);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response));+ $server = Server::where('name', 'mcp-server')->sole();+ expect($server->team_id)->toBe($this->team->id)+ ->and($server->private_key_id)->toBe($this->key->id);+});++test('manage_server rejects a private key of another team', function () {+ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_server', ['action' => 'create', 'data' => [+ 'name' => 'stolen-key', 'ip' => '203.0.113.51', 'private_key_uuid' => $this->otherKey->uuid,+ ]]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(Server::where('name', 'stolen-key')->exists())->toBeFalse();++ $update = mcpSrvCall(mcpSrvToken($this->user), 'manage_server', ['action' => 'update', 'uuid' => $this->server->uuid, 'data' => ['private_key_uuid' => $this->otherKey->uuid]]);+ expect(mcpSrvIsError($update))->toBeTrue()+ ->and($this->server->fresh()->private_key_id)->toBe($this->key->id);+});++test('manage_server cannot change, validate, or delete a server of another team', function (string $action, array $data) {+ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_server', ['action' => $action, 'uuid' => $this->otherServer->uuid, 'confirm' => true, 'data' => $data]);++ expect(mcpSrvIsError($response))->toBeTrue();+ $fresh = Server::find($this->otherServer->id);+ expect($fresh)->not->toBeNull()->and($fresh->name)->toBe('Theirs');+ Queue::assertNothingPushed();+})->with([+ 'update' => ['update', ['name' => 'Hijacked']],+ 'validate' => ['validate', []],+ 'delete' => ['delete', []],+]);++test('manage_server updates, validates, and deletes its own server', function () {+ $token = mcpSrvToken($this->user);++ $update = mcpSrvCall($token, 'manage_server', ['action' => 'update', 'uuid' => $this->server->uuid, 'data' => ['name' => 'renamed']]);+ expect(mcpSrvIsError($update))->toBeFalse(mcpSrvText($update))+ ->and($this->server->fresh()->name)->toBe('renamed');++ $validate = mcpSrvCall($token, 'manage_server', ['action' => 'validate', 'uuid' => $this->server->uuid]);+ expect(mcpSrvIsError($validate))->toBeFalse(mcpSrvText($validate));++ $delete = mcpSrvCall($token, 'manage_server', ['action' => 'delete', 'uuid' => $this->server->uuid, 'confirm' => true]);+ expect(mcpSrvIsError($delete))->toBeFalse(mcpSrvText($delete))+ ->and(Server::find($this->server->id))->toBeNull();+});++// ---------------------------------------------------------------- manage_proxy++test('manage_proxy reads and updates the proxy of its own server and queues a restart', function () {- $token = mcpSrvToken($this->user);++ $token = mcpSrvToken($this->user, ['read', 'write', 'deploy']);++ $get = mcpSrvCall($token, 'manage_proxy', ['action' => 'get', 'uuid' => $this->server->uuid]);+ expect(mcpSrvIsError($get))->toBeFalse(mcpSrvText($get))+ ->and(mcpSrvData($get))->toHaveKey('proxy_type');++ $update = mcpSrvCall($token, 'manage_proxy', ['action' => 'update', 'uuid' => $this->server->uuid, 'confirm' => true, 'data' => ['generate_exact_labels' => true]]);+ expect(mcpSrvIsError($update))->toBeFalse(mcpSrvText($update))+ ->and((bool) $this->server->settings()->first()->generate_exact_labels)->toBeTrue();++ $restart = mcpSrvCall($token, 'manage_proxy', ['action' => 'restart', 'uuid' => $this->server->uuid, 'confirm' => true]);+ expect(mcpSrvIsError($restart))->toBeFalse(mcpSrvText($restart));+ Queue::assertPushed(RestartProxyJob::class);+});++test('manage_proxy cannot read or change the proxy of another team', function (string $action, array $data) {- $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_proxy', ['action' => $action, 'uuid' => $this->otherServer->uuid, 'confirm' => true, 'data' => $data]);++ $response = mcpSrvCall(mcpSrvToken($this->user, ['read', 'write', 'deploy']), 'manage_proxy', ['action' => $action, 'uuid' => $this->otherServer->uuid, 'confirm' => true, 'data' => $data]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and((bool) $this->otherServer->settings()->first()->generate_exact_labels)->toBeFalse();+ Queue::assertNothingPushed();+})->with([+ 'get' => ['get', []],+ 'update' => ['update', ['generate_exact_labels' => true]],+ 'set_configuration' => ['set_configuration', ['configuration' => "services:\n traefik:\n image: evil\n"]],+ 'restart' => ['restart', []],+]);++// ---------------------------------------------------------------- docker_cleanup++test('docker_cleanup reads, updates, lists, and runs cleanup on its own server', function () {- $token = mcpSrvToken($this->user);++ $token = mcpSrvToken($this->user, ['read', 'write', 'deploy']);++ $get = mcpSrvCall($token, 'docker_cleanup', ['action' => 'get', 'uuid' => $this->server->uuid]);+ expect(mcpSrvIsError($get))->toBeFalse(mcpSrvText($get))+ ->and(mcpSrvData($get))->toHaveKey('docker_cleanup_threshold');++ $update = mcpSrvCall($token, 'docker_cleanup', ['action' => 'update', 'uuid' => $this->server->uuid, 'data' => ['docker_cleanup_threshold' => 55]]);+ expect(mcpSrvIsError($update))->toBeFalse(mcpSrvText($update))+ ->and((int) $this->server->settings()->first()->docker_cleanup_threshold)->toBe(55);++ $executions = mcpSrvCall($token, 'docker_cleanup', ['action' => 'executions', 'uuid' => $this->server->uuid]);+ expect(mcpSrvIsError($executions))->toBeFalse(mcpSrvText($executions));++ $run = mcpSrvCall($token, 'docker_cleanup', ['action' => 'run', 'uuid' => $this->server->uuid, 'confirm' => true]);+ expect(mcpSrvIsError($run))->toBeFalse(mcpSrvText($run));+ Queue::assertPushed(DockerCleanupJob::class);+});++test('docker_cleanup cannot touch a server of another team', function (string $action, array $data) {+ $before = (int) $this->otherServer->settings()->first()->docker_cleanup_threshold;+- $response = mcpSrvCall(mcpSrvToken($this->user), 'docker_cleanup', ['action' => $action, 'uuid' => $this->otherServer->uuid, 'confirm' => true, 'data' => $data]);++ $response = mcpSrvCall(mcpSrvToken($this->user, ['read', 'write', 'deploy']), 'docker_cleanup', ['action' => $action, 'uuid' => $this->otherServer->uuid, 'confirm' => true, 'data' => $data]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and((int) $this->otherServer->settings()->first()->docker_cleanup_threshold)->toBe($before);+ Queue::assertNothingPushed();+})->with([+ 'get' => ['get', []],+ 'update' => ['update', ['docker_cleanup_threshold' => 12]],+ 'executions' => ['executions', []],+ 'run' => ['run', []],+]);++// ---------------------------------------------------------------- manage_destination++test('manage_destination creates, renames, and deletes a destination on its own server', function () {+ $cleanup = Mockery::mock(RemoveStandaloneDockerNetwork::class);+ $cleanup->shouldReceive('handle')->once();+ $this->app->instance(RemoveStandaloneDockerNetwork::class, $cleanup);+ $token = mcpSrvToken($this->user);++ $create = mcpSrvCall($token, 'manage_destination', ['action' => 'create', 'server_uuid' => $this->server->uuid, 'data' => ['network' => 'mcp-net', 'name' => 'mcp-dest']]);+ expect(mcpSrvIsError($create))->toBeFalse(mcpSrvText($create));+ $destination = StandaloneDocker::where('network', 'mcp-net')->sole();+ expect($destination->server_id)->toBe($this->server->id);++ $update = mcpSrvCall($token, 'manage_destination', ['action' => 'update', 'uuid' => $destination->uuid, 'data' => ['name' => 'renamed-dest']]);+ expect(mcpSrvIsError($update))->toBeFalse(mcpSrvText($update))+ ->and($destination->fresh()->name)->toBe('renamed-dest');++ $delete = mcpSrvCall($token, 'manage_destination', ['action' => 'delete', 'uuid' => $destination->uuid, 'confirm' => true]);+ expect(mcpSrvIsError($delete))->toBeFalse(mcpSrvText($delete))+ ->and($destination->fresh())->toBeNull();+});++test('manage_destination cannot create a destination on a server of another team', function () {+ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_destination', ['action' => 'create', 'server_uuid' => $this->otherServer->uuid, 'data' => ['network' => 'evil-net']]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(StandaloneDocker::where('network', 'evil-net')->exists())->toBeFalse();+});++test('manage_destination cannot rename or delete a destination of another team', function (string $action, array $data) {+ $cleanup = Mockery::mock(RemoveStandaloneDockerNetwork::class);+ $cleanup->shouldNotReceive('handle');+ $this->app->instance(RemoveStandaloneDockerNetwork::class, $cleanup);+ $foreign = StandaloneDocker::where('server_id', $this->otherServer->id)->firstOrFail();+ $name = $foreign->name;++ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_destination', ['action' => $action, 'uuid' => $foreign->uuid, 'confirm' => true, 'data' => $data]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and($foreign->fresh())->not->toBeNull()+ ->and($foreign->fresh()->name)->toBe($name);+})->with([+ 'update' => ['update', ['name' => 'Hijacked']],+ 'delete' => ['delete', []],+]);++// ---------------------------------------------------------------- manage_registry++test('manage_registry lists registry logins without passwords', function () {+ mcpSrvMakeFunctional($this->server);+ Process::fake(fn () => Process::result(output: json_encode([+ 'auths' => ['ghcr.io' => ['auth' => base64_encode('octocat:REGISTRY_PASSWORD_VALUE')]],+ ])));++ $response = mcpSrvCall(mcpSrvToken($this->user, ['root']), 'manage_registry', ['action' => 'list', 'uuid' => $this->server->uuid]);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response))+ ->and(mcpSrvText($response))->toContain('ghcr.io')+ ->and(mcpSrvText($response))->not->toContain('REGISTRY_PASSWORD_VALUE')+ ->and(mcpSrvText($response))->not->toContain(base64_encode('octocat:REGISTRY_PASSWORD_VALUE'));+});++test('manage_registry list needs read:sensitive', function () {+ $response = mcpSrvCall(mcpSrvToken($this->user, ['read', 'write']), 'manage_registry', ['action' => 'list', 'uuid' => $this->server->uuid]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(mcpSrvText($response))->toContain('read:sensitive');+});++test('manage_registry logs in on its own server without echoing the password', function () {+ mcpSrvMakeFunctional($this->server);+- $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_registry', ['action' => 'create', 'uuid' => $this->server->uuid, 'data' => [++ $response = mcpSrvCall(mcpSrvToken($this->user, ['read', 'write', 'deploy']), 'manage_registry', ['action' => 'create', 'uuid' => $this->server->uuid, 'data' => [+ 'registry' => 'ghcr.io', 'username' => 'octocat', 'password' => 'REGISTRY_PASSWORD_VALUE',+ ]]);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response))+ ->and(mcpSrvText($response))->not->toContain('REGISTRY_PASSWORD_VALUE');+ Process::assertRan(fn ($process) => str_contains(is_array($process->command) ? implode(' ', $process->command) : $process->command, 'docker'));+});++test('manage_registry cannot touch registries on a server of another team', function (string $action, string $ability, array $extra) {+ mcpSrvMakeFunctional($this->otherServer);++ $response = mcpSrvCall(mcpSrvToken($this->user, ['read', $ability]), 'manage_registry', ['action' => $action, 'uuid' => $this->otherServer->uuid, 'confirm' => true] + $extra);++ expect(mcpSrvIsError($response))->toBeTrue();+ Process::assertNothingRan();+})->with([+ 'list' => ['list', 'read:sensitive', []],+ 'create' => ['create', 'write', ['data' => ['registry' => 'ghcr.io', 'username' => 'evil', 'password' => 'x']]],+ 'check' => ['check', 'write', ['registry' => 'ghcr.io']],+ 'delete' => ['delete', 'write', ['registry' => 'ghcr.io']],+]);++// ---------------------------------------------------------------- manage_private_key++test('manage_private_key never returns key material, even to root and read:sensitive tokens', function (array $abilities) {+ $token = mcpSrvToken($this->user, $abilities);+ $keyBody = 'QyNTUxOQAAACBbhpqHhqv6aI67Mj9abM3DVbmcfYhZAhC7ca4d9UCevAAAAJi';++ $list = mcpSrvCall($token, 'manage_private_key', ['action' => 'list']);+ expect(mcpSrvIsError($list))->toBeFalse(mcpSrvText($list))+ ->and(mcpSrvText($list))->toContain($this->key->uuid)+ ->and(mcpSrvText($list))->not->toContain('PRIVATE KEY')+ ->and(mcpSrvText($list))->not->toContain($keyBody)+ ->and(mcpSrvText($list))->not->toContain($this->otherKey->uuid);++ $get = mcpSrvCall($token, 'manage_private_key', ['action' => 'get', 'uuid' => $this->key->uuid]);+ expect(mcpSrvIsError($get))->toBeFalse(mcpSrvText($get))+ ->and(mcpSrvText($get))->not->toContain('PRIVATE KEY')+ ->and(mcpSrvText($get))->not->toContain($keyBody);+})->with([+ 'root' => [['root']],+ 'read:sensitive' => [['read', 'read:sensitive']],+]);++test('manage_private_key create does not return or audit the key material', function () {+ $response = mcpSrvCall(mcpSrvToken($this->user, ['root']), 'manage_private_key', ['action' => 'create', 'data' => [+ 'name' => 'mcp-key', 'private_key' => MCP_SRV_NEW_PRIVATE_KEY,+ ]]);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response))+ ->and(mcpSrvText($response))->not->toContain('PRIVATE KEY')+ ->and(mcpSrvText($response))->not->toContain('AAAECKtKd242pj0qdKWaOpXAQFI2ZGLQOg9vCP2');+ expect(PrivateKey::where('name', 'mcp-key')->sole()->team_id)->toBe($this->team->id);++ $audit = AuditEvent::query()->get()->toJson();+ expect($audit)->not->toContain('PRIVATE KEY')+ ->and($audit)->not->toContain('AAAECKtKd242pj0qdKWaOpXAQFI2ZGLQOg9vCP2');+});++test('manage_private_key cannot read, change, or delete a key of another team', function (string $action, array $data) {+ $original = $this->otherKey->fresh()->name;++ $response = mcpSrvCall(mcpSrvToken($this->user, ['root']), 'manage_private_key', ['action' => $action, 'uuid' => $this->otherKey->uuid, 'confirm' => true, 'data' => $data]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(PrivateKey::find($this->otherKey->id))->not->toBeNull()+ ->and(PrivateKey::find($this->otherKey->id)->name)->toBe($original);+})->with([+ 'get' => ['get', []],+ 'update' => ['update', ['name' => 'Hijacked', 'private_key' => MCP_SRV_NEW_PRIVATE_KEY]],+ 'delete' => ['delete', []],+]);++test('manage_private_key deletes an unused key of its own team', function () {+ $unused = PrivateKey::create(['team_id' => $this->team->id, 'name' => 'unused', 'private_key' => MCP_SRV_NEW_PRIVATE_KEY]);++ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_private_key', ['action' => 'delete', 'uuid' => $unused->uuid, 'confirm' => true]);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response))+ ->and(PrivateKey::find($unused->id))->toBeNull();+});++// ---------------------------------------------------------------- manage_s3_storage++test('manage_s3_storage creates a storage and never returns the secret', function () {+ $token = mcpSrvToken($this->user, ['root']);++ $create = mcpSrvCall($token, 'manage_s3_storage', ['action' => 'create', 'data' => [+ 'name' => 'mcp-s3', 'endpoint' => 'https://s3.amazonaws.com', 'bucket' => 'mcp-bucket', 'region' => 'us-east-1',+ 'key' => 'S3_ACCESS_KEY_VALUE', 'secret' => 'S3_SECRET_KEY_VALUE',+ ]]);+ expect(mcpSrvIsError($create))->toBeFalse(mcpSrvText($create))+ ->and(mcpSrvText($create))->not->toContain('S3_SECRET_KEY_VALUE');+ $storage = S3Storage::where('name', 'mcp-s3')->sole();+ expect($storage->team_id)->toBe($this->team->id);++ foreach ([['action' => 'list'], ['action' => 'get', 'uuid' => $storage->uuid]] as $arguments) {+ $read = mcpSrvCall($token, 'manage_s3_storage', $arguments);+ expect(mcpSrvIsError($read))->toBeFalse(mcpSrvText($read))+ ->and(mcpSrvText($read))->toContain($storage->uuid)+ ->and(mcpSrvText($read))->not->toContain('S3_SECRET_KEY_VALUE');+ }+});++test('manage_s3_storage cannot read, change, test, or delete a storage of another team', function (string $action, array $data) {+ $foreign = mcpSrvS3($this->otherTeam, ['name' => 'Theirs']);++ $response = mcpSrvCall(mcpSrvToken($this->user, ['root']), 'manage_s3_storage', ['action' => $action, 'uuid' => $foreign->uuid, 'confirm' => true, 'data' => $data]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(mcpSrvText($response))->not->toContain('S3_SECRET_KEY_VALUE')+ ->and($foreign->fresh())->not->toBeNull()+ ->and($foreign->fresh()->name)->toBe('Theirs');+})->with([+ 'get' => ['get', []],+ 'update' => ['update', ['name' => 'Hijacked']],+ 'validate' => ['validate', []],+ 'delete' => ['delete', []],+]);++test('manage_s3_storage list does not include storages of another team', function () {+ $foreign = mcpSrvS3($this->otherTeam);++ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_s3_storage', ['action' => 'list']);++ expect(mcpSrvIsError($response))->toBeFalse()+ ->and(mcpSrvText($response))->not->toContain($foreign->uuid);+});++// ---------------------------------------------------------------- manage_git_source++test('manage_git_source lists apps without client or webhook secrets', function () {+ $own = mcpSrvGithubApp($this->team, $this->key);+ $shared = mcpSrvGithubApp($this->otherTeam, $this->otherKey, ['name' => 'shared', 'is_system_wide' => true]);++ $response = mcpSrvCall(mcpSrvToken($this->user, ['root']), 'manage_git_source', ['action' => 'list', 'resource' => 'github']);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response))+ ->and(mcpSrvText($response))->toContain($own->uuid)+ ->and(mcpSrvText($response))->not->toContain('GH_CLIENT_SECRET_VALUE')+ ->and(mcpSrvText($response))->not->toContain('GH_WEBHOOK_SECRET_VALUE')+ ->and(mcpSrvText($response))->not->toContain('PRIVATE KEY');+});++test('manage_git_source rejects a GitHub app with a private key of another team', function () {+ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_git_source', ['action' => 'create', 'resource' => 'github', 'data' => [+ 'name' => 'stolen', 'html_url' => 'https://github.com', 'app_id' => 1, 'installation_id' => 2,+ 'client_id' => 'id', 'client_secret' => 'secret', 'webhook_secret' => 'hook', 'private_key_uuid' => $this->otherKey->uuid,+ ]]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(GithubApp::where('name', 'stolen')->exists())->toBeFalse();++ $own = mcpSrvGithubApp($this->team, $this->key);+ $update = mcpSrvCall(mcpSrvToken($this->user), 'manage_git_source', ['action' => 'update', 'resource' => 'github', 'source_id' => (string) $own->id, 'data' => ['private_key_uuid' => $this->otherKey->uuid]]);+ expect(mcpSrvIsError($update))->toBeTrue()+ ->and($own->fresh()->private_key_id)->toBe($this->key->id);+});++test('manage_git_source cannot change or delete GitHub apps of another team, including system-wide ones', function (bool $systemWide, string $action) {+ $foreign = mcpSrvGithubApp($this->otherTeam, $this->otherKey, ['name' => 'Theirs', 'is_system_wide' => $systemWide]);++ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_git_source', ['action' => $action, 'resource' => 'github', 'source_id' => (string) $foreign->id, 'confirm' => true, 'data' => ['name' => 'Hijacked']]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and($foreign->fresh())->not->toBeNull()+ ->and($foreign->fresh()->name)->toBe('Theirs');+})->with([+ 'team app' => false,+ 'system-wide app' => true,+])->with(['update', 'delete']);++test('manage_git_source creates, updates, and deletes a GitLab app without returning secrets', function () {+ $token = mcpSrvToken($this->user, ['read', 'write']);++ $create = mcpSrvCall($token, 'manage_git_source', ['action' => 'create', 'resource' => 'gitlab', 'data' => [+ 'name' => 'mcp-gitlab', 'html_url' => 'https://gitlab.com', 'client_secret' => 'GL_CLIENT_SECRET_VALUE', 'webhook_token' => 'GL_WEBHOOK_TOKEN_VALUE',+ ]]);+ expect(mcpSrvIsError($create))->toBeFalse(mcpSrvText($create))+ ->and(mcpSrvText($create))->not->toContain('GL_CLIENT_SECRET_VALUE')+ ->and(mcpSrvText($create))->not->toContain('GL_WEBHOOK_TOKEN_VALUE');+ $app = GitlabApp::where('name', 'mcp-gitlab')->sole();+ expect($app->team_id)->toBe($this->team->id);++ $list = mcpSrvCall($token, 'manage_git_source', ['action' => 'list', 'resource' => 'gitlab']);+ expect(mcpSrvIsError($list))->toBeFalse()+ ->and(mcpSrvText($list))->not->toContain('GL_CLIENT_SECRET_VALUE')+ ->and(mcpSrvText($list))->not->toContain('GL_WEBHOOK_TOKEN_VALUE');+ $sourceId = collect(mcpSrvData($list))->firstWhere('name', 'mcp-gitlab')['id'];+ expect($sourceId)->not->toBeNull();++ $update = mcpSrvCall($token, 'manage_git_source', ['action' => 'update', 'resource' => 'gitlab', 'source_id' => (string) $sourceId, 'data' => ['name' => 'renamed-gitlab']]);+ expect(mcpSrvIsError($update))->toBeFalse(mcpSrvText($update))+ ->and(mcpSrvText($update))->not->toContain('GL_CLIENT_SECRET_VALUE')+ ->and(mcpSrvText($update))->not->toContain('GL_WEBHOOK_TOKEN_VALUE')+ ->and($app->fresh()->name)->toBe('renamed-gitlab');++ $delete = mcpSrvCall($token, 'manage_git_source', ['action' => 'delete', 'resource' => 'gitlab', 'source_id' => (string) $sourceId, 'confirm' => true]);+ expect(mcpSrvIsError($delete))->toBeFalse(mcpSrvText($delete))+ ->and(GitlabApp::find($app->id))->toBeNull();+});++test('manage_git_source cannot change or delete a GitLab app of another team', function (string $action) {+ $foreign = GitlabApp::create(['name' => 'Theirs', 'html_url' => 'https://gitlab.com', 'api_url' => 'https://gitlab.com/api/v4', 'team_id' => $this->otherTeam->id]);++ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_git_source', ['action' => $action, 'resource' => 'gitlab', 'source_id' => (string) $foreign->id, 'confirm' => true, 'data' => ['name' => 'Hijacked']]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and($foreign->fresh())->not->toBeNull()+ ->and($foreign->fresh()->name)->toBe('Theirs');+})->with(['update', 'delete']);++test('manage_git_source requires a known resource', function () {+ $response = mcpSrvCall(mcpSrvToken($this->user), 'manage_git_source', ['action' => 'list', 'resource' => 'bitbucket']);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(mcpSrvText($response))->toContain('resource must be one of: github, gitlab');+});++// ---------------------------------------------------------------- cloud_provider++test('cloud_provider adds and lists tokens without returning the token value', function () {+ Http::fake(['https://api.hetzner.cloud/v1/servers' => Http::response([], 200)]);+ $token = mcpSrvToken($this->user, ['root']);++ $create = mcpSrvCall($token, 'cloud_provider', ['action' => 'create_token', 'data' => ['provider' => 'hetzner', 'token' => 'HETZNER_TOKEN_VALUE', 'name' => 'mcp-hetzner']]);+ expect(mcpSrvIsError($create))->toBeFalse(mcpSrvText($create))+ ->and(mcpSrvText($create))->not->toContain('HETZNER_TOKEN_VALUE');+ $stored = CloudProviderToken::where('name', 'mcp-hetzner')->sole();+ expect($stored->team_id)->toBe($this->team->id);++ foreach ([['action' => 'list_tokens'], ['action' => 'get_token', 'uuid' => $stored->uuid]] as $arguments) {+ $read = mcpSrvCall($token, 'cloud_provider', $arguments);+ expect(mcpSrvIsError($read))->toBeFalse(mcpSrvText($read))+ ->and(mcpSrvText($read))->toContain($stored->uuid)+ ->and(mcpSrvText($read))->not->toContain('HETZNER_TOKEN_VALUE');+ }+});++test('cloud_provider cannot read, change, validate, or delete a token of another team', function (string $action, array $data) {+ Http::fake();+ $foreign = CloudProviderToken::create(['team_id' => $this->otherTeam->id, 'provider' => 'hetzner', 'token' => 'FOREIGN_TOKEN_VALUE', 'name' => 'Theirs']);++ $response = mcpSrvCall(mcpSrvToken($this->user, ['root']), 'cloud_provider', ['action' => $action, 'uuid' => $foreign->uuid, 'confirm' => true, 'data' => $data]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(mcpSrvText($response))->not->toContain('FOREIGN_TOKEN_VALUE')+ ->and($foreign->fresh())->not->toBeNull()+ ->and($foreign->fresh()->name)->toBe('Theirs');+ Http::assertNothingSent();+})->with([+ 'get_token' => ['get_token', []],+ 'update_token' => ['update_token', ['name' => 'Hijacked']],+ 'validate_token' => ['validate_token', []],+ 'delete_token' => ['delete_token', []],+]);++test('cloud_provider reads a catalog with a token of its own team', function () {+ Http::fake(['https://api.hetzner.cloud/v1/locations*' => Http::response([+ 'locations' => [['id' => 1, 'name' => 'nbg1', 'description' => 'Nuremberg', 'country' => 'DE', 'city' => 'Nuremberg']],+ 'meta' => ['pagination' => ['next_page' => null]],+ ], 200)]);+ $cloudToken = CloudProviderToken::create(['team_id' => $this->team->id, 'provider' => 'hetzner', 'token' => 'OWN_TOKEN_VALUE', 'name' => 'Mine']);++ $response = mcpSrvCall(mcpSrvToken($this->user), 'cloud_provider', ['action' => 'catalog', 'resource' => 'hetzner_locations', 'data' => ['cloud_provider_token_uuid' => $cloudToken->uuid]]);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response))+ ->and(mcpSrvText($response))->toContain('nbg1')+ ->and(mcpSrvText($response))->not->toContain('OWN_TOKEN_VALUE');+});++test('cloud_provider cannot use a token of another team for catalogs or provisioning', function (string $action, string $resource, array $data) {+ Http::fake();+ $foreign = CloudProviderToken::create(['team_id' => $this->otherTeam->id, 'provider' => 'hetzner', 'token' => 'FOREIGN_TOKEN_VALUE', 'name' => 'Theirs']);+ $serverCount = Server::count();++ $response = mcpSrvCall(mcpSrvToken($this->user), 'cloud_provider', ['action' => $action, 'resource' => $resource, 'confirm' => true, 'data' => ['cloud_provider_token_uuid' => $foreign->uuid] + $data]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(Server::count())->toBe($serverCount);+ Http::assertNothingSent();+})->with([+ 'catalog' => ['catalog', 'hetzner_server_types', []],+ 'provision' => ['provision_server', 'hetzner', ['location' => 'nbg1', 'server_type' => 'cx22', 'image' => 1, 'name' => 'evil']],+]);++test('cloud_provider provisioning rejects a private key of another team', function () {+ Http::fake();+ $cloudToken = CloudProviderToken::create(['team_id' => $this->team->id, 'provider' => 'hetzner', 'token' => 'OWN_TOKEN_VALUE', 'name' => 'Mine']);+ $serverCount = Server::count();++ $response = mcpSrvCall(mcpSrvToken($this->user), 'cloud_provider', ['action' => 'provision_server', 'resource' => 'hetzner', 'confirm' => true, 'data' => [+ 'cloud_provider_token_uuid' => $cloudToken->uuid, 'private_key_uuid' => $this->otherKey->uuid,+ 'location' => 'nbg1', 'server_type' => 'cx22', 'image' => 1, 'name' => 'evil',+ ]]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(Server::count())->toBe($serverCount);+ Http::assertNothingSent();+});+++test('cloud_provider provisioning a Hostinger VPS with a post-install script or extra SSH keys needs deploy', function (array $extra) {++ Http::fake();++ $cloudToken = CloudProviderToken::create(['team_id' => $this->team->id, 'provider' => 'hostinger', 'token' => 'OWN_TOKEN_VALUE', 'name' => 'Mine']);++ $serverCount = Server::count();++++ $response = mcpSrvCall(mcpSrvToken($this->user), 'cloud_provider', ['action' => 'provision_server', 'resource' => 'hostinger', 'confirm' => true, 'data' => [++ 'cloud_provider_token_uuid' => $cloudToken->uuid, 'private_key_uuid' => $this->key->uuid,++ 'item_id' => 'hostingercom-vps-kvm1-usd-1m', 'data_center_id' => 19, 'template_id' => 1130,++ ...$extra,++ ]]);++++ expect(mcpSrvIsError($response))->toBeTrue()++ ->and(mcpSrvText($response))->toContain('Missing required permissions: deploy')++ ->and(Server::count())->toBe($serverCount);++ Http::assertNothingSent();++})->with([++ 'post-install script' => [['post_install_script_id' => 73]],++ 'extra SSH keys' => [['public_key_ids' => [42]]],++]);+++// ---------------------------------------------------------------- manage_notifications++test('manage_notifications updates a channel of the token team and never returns webhook URLs or tokens', function () {+ $token = mcpSrvToken($this->user, ['root']);+ $otherSettings = DiscordNotificationSettings::query()->firstOrCreate(['team_id' => $this->otherTeam->id]);++ $update = mcpSrvCall($token, 'manage_notifications', ['action' => 'update', 'resource' => 'discord', 'data' => [+ 'discord_enabled' => true, 'discord_webhook_url' => 'https://discord.com/api/webhooks/123/DISCORD_WEBHOOK_SECRET',+ ]]);+ expect(mcpSrvIsError($update))->toBeFalse(mcpSrvText($update))+ ->and(mcpSrvText($update))->not->toContain('DISCORD_WEBHOOK_SECRET');++ expect(DiscordNotificationSettings::where('team_id', $this->team->id)->sole()->discord_webhook_url)->toContain('DISCORD_WEBHOOK_SECRET')+ ->and($otherSettings->fresh()->discord_webhook_url)->toBeNull();++ $get = mcpSrvCall($token, 'manage_notifications', ['action' => 'get', 'resource' => 'discord']);+ expect(mcpSrvIsError($get))->toBeFalse(mcpSrvText($get))+ ->and(mcpSrvText($get))->toContain('discord_enabled')+ ->and(mcpSrvText($get))->not->toContain('DISCORD_WEBHOOK_SECRET');+});++test('manage_notifications never returns channel secrets', function (string $channel, array $data, string $secret) {+ $token = mcpSrvToken($this->user, ['root']);++ $update = mcpSrvCall($token, 'manage_notifications', ['action' => 'update', 'resource' => $channel, 'data' => $data]);+ expect(mcpSrvIsError($update))->toBeFalse(mcpSrvText($update))+ ->and(mcpSrvText($update))->not->toContain($secret);++ $get = mcpSrvCall($token, 'manage_notifications', ['action' => 'get', 'resource' => $channel]);+ expect(mcpSrvIsError($get))->toBeFalse(mcpSrvText($get))+ ->and(mcpSrvText($get))->not->toContain($secret);+})->with([+ 'email smtp password' => ['email', ['smtp_password' => 'SMTP_PASSWORD_VALUE', 'resend_api_key' => 'RESEND_KEY_VALUE'], 'SMTP_PASSWORD_VALUE'],+ 'email resend key' => ['email', ['resend_api_key' => 'RESEND_KEY_VALUE'], 'RESEND_KEY_VALUE'],+ 'slack webhook' => ['slack', ['slack_webhook_url' => 'https://hooks.slack.com/services/SLACK_SECRET_PATH'], 'SLACK_SECRET_PATH'],+ 'telegram token' => ['telegram', ['telegram_token' => 'TELEGRAM_TOKEN_VALUE', 'telegram_chat_id' => '123'], 'TELEGRAM_TOKEN_VALUE'],+ 'pushover keys' => ['pushover', ['pushover_user_key' => 'PUSHOVER_USER_VALUE', 'pushover_api_token' => 'PUSHOVER_TOKEN_VALUE'], 'PUSHOVER_'],+ 'webhook url' => ['webhook', ['webhook_url' => 'https://example.com/hook/WEBHOOK_SECRET_PATH'], 'WEBHOOK_SECRET_PATH'],+]);++test('manage_notifications only changes the token team', function () {+ TelegramNotificationSettings::query()->firstOrCreate(['team_id' => $this->otherTeam->id]);+ $sessionSwitch = Team::factory()->create();+ $sessionSwitch->members()->attach($this->user->id, ['role' => 'owner']);+ $token = mcpSrvToken($this->user);+ session(['currentTeam' => $sessionSwitch]);++ $response = mcpSrvCall($token, 'manage_notifications', ['action' => 'update', 'resource' => 'telegram', 'data' => ['telegram_chat_id' => '999']]);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response))+ ->and(TelegramNotificationSettings::where('team_id', $this->team->id)->sole()->telegram_chat_id)->toBe('999')+ ->and(TelegramNotificationSettings::where('team_id', $this->otherTeam->id)->sole()->telegram_chat_id)->toBeNull()+ ->and(TelegramNotificationSettings::where('team_id', $sessionSwitch->id)->first()?->telegram_chat_id)->toBeNull();+});++// ---------------------------------------------------------------- list_audit_events++test('list_audit_events returns only events of the token team', function () {+ AuditEvent::factory()->create(['team_id' => $this->team->id, 'description' => 'own-team-event']);+ AuditEvent::factory()->create(['team_id' => $this->otherTeam->id, 'description' => 'other-team-event']);++ $response = mcpSrvCall(mcpSrvToken($this->user, ['read']), 'list_audit_events', ['action' => 'list', 'data' => ['per_page' => 50]]);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response))+ ->and(mcpSrvText($response))->toContain('own-team-event')+ ->and(mcpSrvText($response))->not->toContain('other-team-event');+});++test('list_audit_events is denied for team members', function () {+ $member = User::factory()->create();+ $this->team->members()->attach($member->id, ['role' => 'member']);+ AuditEvent::factory()->create(['team_id' => $this->team->id, 'description' => 'own-team-event']);++ $response = mcpSrvCall(mcpSrvToken($member, ['read']), 'list_audit_events', ['action' => 'list']);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(mcpSrvText($response))->not->toContain('own-team-event');+});++// ---------------------------------------------------------------- get_server_metrics++test('get_server_metrics returns recent metrics for a server of the token team', function () {+ McpSrvStubMetricsClient::$calls = 0;+ $this->app->bind(SentinelMetricsClient::class, fn ($app, array $parameters) => new McpSrvStubMetricsClient($parameters['server']));+ $this->server->settings->update(['is_metrics_enabled' => true]);+ Server::flushIdentityMap();++ $response = mcpSrvCall(mcpSrvToken($this->user, ['read']), 'get_server_metrics', ['server_uuid' => $this->server->uuid, 'minutes' => 60]);++ expect(mcpSrvIsError($response))->toBeFalse(mcpSrvText($response));+ $data = mcpSrvData($response);+ expect($data['online'])->toBeTrue()+ ->and($data['current']['cpu_percent'])->toBe(42.5)+ ->and($data['series']['cpu_percent'])->toHaveCount(1)+ ->and($data['series']['disk_used_percent'])->toBe([])+ ->and($data['series']['network_rx_bytes_per_sec'])->toHaveCount(1)+ ->and(mcpSrvText($response))->not->toContain('sentinel_token');+});++test('get_server_metrics caps minutes and rejects invalid values', function () {+ $this->app->bind(SentinelMetricsClient::class, fn ($app, array $parameters) => new McpSrvStubMetricsClient($parameters['server']));+ $this->server->settings->update(['is_metrics_enabled' => true]);+ Server::flushIdentityMap();+ $token = mcpSrvToken($this->user, ['read']);++ $capped = mcpSrvCall($token, 'get_server_metrics', ['server_uuid' => $this->server->uuid, 'minutes' => 999999]);+ expect(mcpSrvData($capped)['minutes'])->toBe(43200);++ $invalid = mcpSrvCall($token, 'get_server_metrics', ['server_uuid' => $this->server->uuid, 'minutes' => 0]);+ expect(mcpSrvIsError($invalid))->toBeTrue();+});++test('get_server_metrics does not read metrics of a server of another team', function () {+ McpSrvStubMetricsClient::$calls = 0;+ $this->app->bind(SentinelMetricsClient::class, fn ($app, array $parameters) => new McpSrvStubMetricsClient($parameters['server']));+ $this->otherServer->settings->update(['is_metrics_enabled' => true]);+ Server::flushIdentityMap();++ $response = mcpSrvCall(mcpSrvToken($this->user, ['read']), 'get_server_metrics', ['server_uuid' => $this->otherServer->uuid]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(mcpSrvText($response))->toContain('not found')+ ->and(McpSrvStubMetricsClient::$calls)->toBe(0);+});++test('get_server_metrics explains when metrics are disabled', function () {+ $response = mcpSrvCall(mcpSrvToken($this->user, ['read']), 'get_server_metrics', ['server_uuid' => $this->server->uuid]);++ expect(mcpSrvIsError($response))->toBeTrue()+ ->and(mcpSrvText($response))->toContain('Metrics are not enabled');+});