first commit

This commit is contained in:
Ariyutta
2026-08-07 10:47:09 +07:00
commit 1c094fbe7f
11630 changed files with 1580900 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost;
use Illuminate\Support\Facades\Facade;
/**
* @method static void registerCodeEnvironment(string $key, string $className)
* @method static array getCodeEnvironments()
*
* @see BoostManager
*/
class Boost extends Facade
{
protected static function getFacadeAccessor(): string
{
return BoostManager::class;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost;
use InvalidArgumentException;
use Laravel\Boost\Install\CodeEnvironment\ClaudeCode;
use Laravel\Boost\Install\CodeEnvironment\CodeEnvironment;
use Laravel\Boost\Install\CodeEnvironment\Codex;
use Laravel\Boost\Install\CodeEnvironment\Copilot;
use Laravel\Boost\Install\CodeEnvironment\Cursor;
use Laravel\Boost\Install\CodeEnvironment\Gemini;
use Laravel\Boost\Install\CodeEnvironment\OpenCode;
use Laravel\Boost\Install\CodeEnvironment\PhpStorm;
use Laravel\Boost\Install\CodeEnvironment\VSCode;
class BoostManager
{
/** @var array<string, class-string<CodeEnvironment>> */
private array $codeEnvironments = [
'phpstorm' => PhpStorm::class,
'vscode' => VSCode::class,
'cursor' => Cursor::class,
'claudecode' => ClaudeCode::class,
'codex' => Codex::class,
'copilot' => Copilot::class,
'opencode' => OpenCode::class,
'gemini' => Gemini::class,
];
/**
* @param class-string<CodeEnvironment> $className
*/
public function registerCodeEnvironment(string $key, string $className): void
{
if (array_key_exists($key, $this->codeEnvironments)) {
throw new InvalidArgumentException("Code environment '{$key}' is already registered");
}
$this->codeEnvironments[$key] = $className;
}
/**
* @return array<string, class-string<CodeEnvironment>>
*/
public function getCodeEnvironments(): array
{
return $this->codeEnvironments;
}
}
+218
View File
@@ -0,0 +1,218 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken;
use Illuminate\Http\Request;
use Illuminate\Log\Logger;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\Compilers\BladeCompiler;
use Laravel\Boost\Install\GuidelineAssist;
use Laravel\Boost\Install\GuidelineConfig;
use Laravel\Boost\Mcp\Boost;
use Laravel\Boost\Middleware\InjectBoost;
use Laravel\Boost\Services\BrowserLogger;
use Laravel\Mcp\Facades\Mcp;
use Laravel\Roster\Roster;
class BoostServiceProvider extends ServiceProvider
{
public function register(): void
{
$this->mergeConfigFrom(
__DIR__.'/../config/boost.php',
'boost'
);
if (! $this->shouldRun()) {
return;
}
$this->app->singleton(BoostManager::class, fn (): BoostManager => new BoostManager);
$this->app->singleton(Roster::class, function () {
$lockFiles = [
base_path('composer.lock'),
base_path('package-lock.json'),
base_path('bun.lock'),
base_path('bun.lockb'),
base_path('pnpm-lock.yaml'),
base_path('yarn.lock'),
];
$cacheKey = 'boost.roster.scan';
$lastModified = max(array_map(fn (string $path): int|false => file_exists($path) ? filemtime($path) : 0, $lockFiles));
$cached = cache()->get($cacheKey);
if ($cached && isset($cached['timestamp']) && $cached['timestamp'] >= $lastModified) {
return $cached['roster'];
}
$roster = Roster::scan(base_path());
cache()->put($cacheKey, [
'roster' => $roster,
'timestamp' => time(),
], now()->addHours(24));
return $roster;
});
$this->app->singleton(GuidelineConfig::class, fn (): GuidelineConfig => new GuidelineConfig);
$this->app->singleton(GuidelineAssist::class, fn ($app): GuidelineAssist => new GuidelineAssist(
$app->make(Roster::class),
$app->make(GuidelineConfig::class)
));
}
public function boot(Router $router): void
{
if (! $this->shouldRun()) {
return;
}
Mcp::local('laravel-boost', Boost::class);
$this->registerPublishing();
$this->registerCommands();
$this->registerRoutes();
if (config('boost.browser_logs_watcher', true)) {
$this->registerBrowserLogger();
$this->callAfterResolving('blade.compiler', $this->registerBladeDirectives(...));
$this->hookIntoResponses($router);
}
}
protected function registerPublishing(): void
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/../config/boost.php' => config_path('boost.php'),
], 'boost-config');
}
}
protected function registerCommands(): void
{
if ($this->app->runningInConsole()) {
$this->commands([
Console\StartCommand::class,
Console\InstallCommand::class,
Console\UpdateCommand::class,
Console\ExecuteToolCommand::class,
]);
}
}
protected function registerRoutes(): void
{
Route::post('/_boost/browser-logs', function (Request $request) {
$logs = $request->input('logs', []);
/** @var Logger $logger */
$logger = Log::channel('browser');
/**
* @var array{
* type: 'error'|'warn'|'info'|'log'|'table'|'window_error'|'uncaught_error'|'unhandled_rejection',
* timestamp: string,
* data: array,
* url:string,
* userAgent:string
* } $log */
foreach ($logs as $log) {
$logger->write(
level: match ($log['type']) {
'warn' => 'warning',
'log', 'table' => 'debug',
'window_error', 'uncaught_error', 'unhandled_rejection' => 'error',
default => $log['type']
},
message: self::buildLogMessageFromData($log['data']),
context: [
'url' => $log['url'],
'user_agent' => $log['userAgent'] ?: null,
'timestamp' => $log['timestamp'] ?: now()->toIso8601String(),
]
);
}
return response()->json(['status' => 'logged']);
})
->name('boost.browser-logs')
->withoutMiddleware(VerifyCsrfToken::class);
}
/**
* Build a string message for the log based on various input types. Single-dimensional, and multi:
* "data": {"message":"Unhandled Promise Rejection","reason":{"name":"TypeError","message":"NetworkError when attempting to fetch resource.","stack":""}}]
*/
private static function buildLogMessageFromData(array $data): string
{
$messages = [];
foreach ($data as $value) {
$messages[] = match (true) {
is_array($value) => self::buildLogMessageFromData($value),
is_string($value), is_numeric($value) => (string) $value,
is_bool($value) => $value ? 'true' : 'false',
is_null($value) => 'null',
is_object($value) => json_encode($value),
default => $value,
};
}
return implode(' ', $messages);
}
protected function registerBrowserLogger(): void
{
if (config('logging.channels.browser') !== null) {
return;
}
config([
'logging.channels.browser' => [
'driver' => 'single',
'path' => storage_path('logs/browser.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => 14,
],
]);
}
protected function registerBladeDirectives(BladeCompiler $bladeCompiler): void
{
$bladeCompiler->directive('boostJs', fn (): string => '<?php echo '.BrowserLogger::class.'::getScript(); ?>');
}
protected function hookIntoResponses(Router $router): void
{
$this->app->booted(function () use ($router): void {
$router->pushMiddlewareToGroup('web', InjectBoost::class);
});
}
protected function shouldRun(): bool
{
if (! config('boost.enabled', true)) {
return false;
}
if (app()->runningUnitTests()) {
return false;
}
// Only enable Boost on local environments or when debug is true
if (! app()->environment('local') && config('app.debug', false) !== true) {
return false;
}
return true;
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Concerns;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
trait MakesHttpRequests
{
public function client(): PendingRequest
{
$client = Http::withHeaders([
'User-Agent' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:140.0) Gecko/20100101 Firefox/140.0 Laravel Boost',
]);
// Disable SSL verification for local development URLs and testing
if (app()->environment(['local', 'testing']) || str_contains((string) config('boost.hosted.api_url', ''), '.test')) {
return $client->withoutVerifying();
}
return $client;
}
public function get(string $url): Response
{
return $this->client()->get($url);
}
/**
* @param array<string, mixed> $json
*/
public function json(string $url, array $json): Response
{
return $this->client()->asJson()->post($url, $json);
}
}
+208
View File
@@ -0,0 +1,208 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Concerns;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
trait ReadsLogs
{
/**
* Regular expression fragments and default chunk-window sizes used when
* scanning log files. Declaring them once keeps every consumer in sync.
*/
protected function getTimestampRegex(): string
{
return '\\[\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}\\]';
}
protected function getEntrySplitRegex(): string
{
return '/(?='.$this->getTimestampRegex().')/';
}
protected function getErrorEntryRegex(): string
{
return '/^'.$this->getTimestampRegex().'.*\\.ERROR:/';
}
protected function getChunkSizeStart(): int
{
return 64 * 1024; // 64 kB
}
protected function getChunkSizeMax(): int
{
return 1024 * 1024; // 1 MB
}
/**
* Resolve the current log file path based on Laravel's logging configuration.
*/
protected function resolveLogFilePath(): string
{
$channel = Config::get('logging.default');
$channelConfig = Config::get("logging.channels.{$channel}");
$channelConfig = $this->resolveChannelWithPath($channelConfig);
$baseLogPath = Arr::get($channelConfig, 'path', storage_path('logs/laravel.log'));
if (Arr::get($channelConfig, 'driver') === 'daily') {
return $this->resolveDailyLogFilePath($baseLogPath);
}
return $baseLogPath;
}
/**
* @param array<string, mixed>|null $channelConfig
* @return array<string, mixed>|null
*/
protected function resolveChannelWithPath(?array $channelConfig, int $depth = 0): ?array
{
if ($channelConfig === null || $depth > 2) {
return $channelConfig;
}
if (isset($channelConfig['path'])) {
return $channelConfig;
}
if (($channelConfig['driver'] ?? null) !== 'stack') {
return $channelConfig;
}
$firstValidLoggerConfig = collect($channelConfig['channels'] ?? [])
->map(fn (string $name) => Config::get("logging.channels.{$name}"))
->filter(fn ($config): bool => is_array($config))
->map(fn (array $config) => $this->resolveChannelWithPath($config, $depth + 1))
->first(fn (?array $config): bool => isset($config['path']));
return $firstValidLoggerConfig ?? $channelConfig;
}
protected function resolveDailyLogFilePath(string $basePath): string
{
$pathInfo = pathinfo($basePath);
$directory = $pathInfo['dirname'];
$filename = $pathInfo['filename'];
$extension = isset($pathInfo['extension']) ? '.'.$pathInfo['extension'] : '';
$todayLogFile = $directory.DIRECTORY_SEPARATOR.$filename.'-'.date('Y-m-d').$extension;
if (file_exists($todayLogFile)) {
return $todayLogFile;
}
$pattern = $directory.DIRECTORY_SEPARATOR.$filename.'-*'.$extension;
$files = glob($pattern) ?: [];
$datePattern = '/^'.preg_quote($filename, '/').'-\d{4}-\d{2}-\d{2}'.preg_quote($extension, '/').'$/';
$latestFile = collect($files)
->filter(fn ($file): int|false => preg_match($datePattern, basename($file)))
->sortDesc()
->first();
return $latestFile ?? $todayLogFile;
}
/**
* Determine if the given line (or entry) is an ERROR log entry.
*/
protected function isErrorEntry(string $line): bool
{
return preg_match($this->getErrorEntryRegex(), $line) === 1;
}
/**
* Retrieve the last $count complete PSR-3 log entries from the log file using
* chunked reading instead of character-by-character reverse scanning.
*
* @return string[]
*/
protected function readLastLogEntries(string $logFile, int $count): array
{
$chunkSize = $this->getChunkSizeStart();
do {
$entries = $this->scanLogChunkForEntries($logFile, $chunkSize);
if (count($entries) >= $count || $chunkSize >= $this->getChunkSizeMax()) {
break;
}
$chunkSize *= 2;
} while (true);
return array_slice($entries, -$count);
}
/**
* Return the most recent ERROR log entry, or null if none exists within the
* inspected window.
*/
protected function readLastErrorEntry(string $logFile): ?string
{
$chunkSize = $this->getChunkSizeStart();
do {
$entries = $this->scanLogChunkForEntries($logFile, $chunkSize);
for ($i = count($entries) - 1; $i >= 0; $i--) {
if ($this->isErrorEntry($entries[$i])) {
return trim((string) $entries[$i]);
}
}
if ($chunkSize >= $this->getChunkSizeMax()) {
return null;
}
$chunkSize *= 2;
} while (true);
}
/**
* Scan the last $chunkSize bytes of the log file and return an array of
* complete log entries (oldest ➜ newest).
*
* @return string[]
*/
protected function scanLogChunkForEntries(string $logFile, int $chunkSize): array
{
$fileSize = filesize($logFile);
if ($fileSize === false) {
return [];
}
$handle = fopen($logFile, 'r');
if (! $handle) {
return [];
}
try {
$offset = max($fileSize - $chunkSize, 0);
fseek($handle, $offset);
// If we started mid-line, discard the partial line to align to the next newline.
if ($offset > 0) {
fgets($handle);
}
$content = stream_get_contents($handle);
// Split by beginning-of-entry look-ahead (PSR-3 timestamp pattern).
$entries = preg_split($this->getEntrySplitRegex(), $content, -1, PREG_SPLIT_NO_EMPTY);
if (! $entries) {
return [];
}
return $entries; // already in chronological order relative to chunk
} finally {
fclose($handle);
}
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Console;
use Illuminate\Console\Command;
use Laravel\Boost\Mcp\ToolRegistry;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Throwable;
class ExecuteToolCommand extends Command
{
protected $signature = 'boost:execute-tool {tool} {arguments}';
protected $description = 'Execute a Boost MCP tool in isolation (internal command)';
protected $hidden = true;
public function handle(): int
{
$toolClass = $this->argument('tool');
$argumentsEncoded = $this->argument('arguments');
// Validate the tool is registered
if (! ToolRegistry::isToolAllowed($toolClass)) {
$this->error("Tool not registered or not allowed: {$toolClass}");
return 1;
}
// Decode arguments
$arguments = json_decode(base64_decode($argumentsEncoded, true), true);
if (json_last_error() !== JSON_ERROR_NONE) {
$this->error('Invalid arguments format: '.json_last_error_msg());
return 1;
}
/** @var Tool $tool */
$tool = app($toolClass);
$request = new Request($arguments ?? []);
try {
/** @var Response $response */
$response = $tool->handle($request); // @phpstan-ignore-line
} catch (Throwable $throwable) {
$errorResult = Response::error("Tool execution failed (E_THROWABLE): {$throwable->getMessage()}");
$this->error(json_encode([
'isError' => true,
'content' => [
$errorResult->content()->toTool($tool),
],
]));
return static::FAILURE;
}
echo json_encode([
'isError' => $response->isError(),
'content' => [
$response->content()->toTool($tool),
],
]);
return static::SUCCESS;
}
}
+680
View File
@@ -0,0 +1,680 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Console;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use InvalidArgumentException;
use Laravel\Boost\Contracts\Agent;
use Laravel\Boost\Contracts\McpClient;
use Laravel\Boost\Install\Cli\DisplayHelper;
use Laravel\Boost\Install\CodeEnvironment\CodeEnvironment;
use Laravel\Boost\Install\CodeEnvironmentsDetector;
use Laravel\Boost\Install\GuidelineComposer;
use Laravel\Boost\Install\GuidelineConfig;
use Laravel\Boost\Install\GuidelineWriter;
use Laravel\Boost\Install\Herd;
use Laravel\Boost\Install\Sail;
use Laravel\Boost\Support\Config;
use Laravel\Prompts\Concerns\Colors;
use Laravel\Prompts\Terminal;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Process\Process;
use function Laravel\Prompts\confirm;
use function Laravel\Prompts\intro;
use function Laravel\Prompts\multiselect;
use function Laravel\Prompts\note;
class InstallCommand extends Command
{
use Colors;
protected $signature = 'boost:install {--ignore-guidelines : Skip installing AI guidelines} {--ignore-mcp : Skip installing MCP server configuration}';
private CodeEnvironmentsDetector $codeEnvironmentsDetector;
private Herd $herd;
private Sail $sail;
private Terminal $terminal;
/** @var Collection<int, Agent> */
private Collection $selectedTargetAgents;
/** @var Collection<int, McpClient> */
private Collection $selectedTargetMcpClient;
/** @var Collection<int, string> */
private Collection $selectedBoostFeatures;
/** @var Collection<int, string> */
private Collection $selectedAiGuidelines;
private string $projectName;
/** @var array<non-empty-string> */
private array $systemInstalledCodeEnvironments = [];
private array $projectInstalledCodeEnvironments = [];
private bool $enforceTests = true;
const MIN_TEST_COUNT = 6;
private string $greenTick;
private string $redCross;
private bool $installGuidelines;
private bool $installMcpConfig;
public function __construct(protected Config $config)
{
parent::__construct();
}
public function handle(
CodeEnvironmentsDetector $codeEnvironmentsDetector,
Herd $herd,
Sail $sail,
Terminal $terminal,
): int {
$this->installGuidelines = ! $this->option('ignore-guidelines');
$this->installMcpConfig = ! $this->option('ignore-mcp');
if (! $this->installGuidelines && ! $this->installMcpConfig) {
$this->error('You cannot ignore both guidelines and MCP config. Please select at least one option to proceed.');
return self::FAILURE;
}
$this->bootstrap($codeEnvironmentsDetector, $herd, $sail, $terminal);
$this->displayBoostHeader();
$this->discoverEnvironment();
$this->collectInstallationPreferences();
$this->performInstallation();
$this->outro();
return self::SUCCESS;
}
protected function bootstrap(CodeEnvironmentsDetector $codeEnvironmentsDetector, Herd $herd, Sail $sail, Terminal $terminal): void
{
$this->codeEnvironmentsDetector = $codeEnvironmentsDetector;
$this->herd = $herd;
$this->sail = $sail;
$this->terminal = $terminal;
$this->terminal->initDimensions();
$this->greenTick = $this->green('✓');
$this->redCross = $this->red('✗');
$this->selectedTargetAgents = collect();
$this->selectedTargetMcpClient = collect();
$this->projectName = config('app.name');
}
protected function displayBoostHeader(): void
{
note($this->boostLogo());
intro('✦ Laravel Boost :: Install :: We Must Ship ✦');
note("Let's give {$this->bgYellow($this->black($this->bold($this->projectName)))} a Boost");
}
protected function boostLogo(): string
{
return
<<<'HEADER'
██████╗ ██████╗ ██████╗ ███████╗ ████████╗
██╔══██╗ ██╔═══██╗ ██╔═══██╗ ██╔════╝ ╚══██╔══╝
██████╔╝ ██║ ██║ ██║ ██║ ███████╗ ██║
██╔══██╗ ██║ ██║ ██║ ██║ ╚════██║ ██║
██████╔╝ ╚██████╔╝ ╚██████╔╝ ███████║ ██║
╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝ ╚═╝
HEADER;
}
protected function discoverEnvironment(): void
{
$this->systemInstalledCodeEnvironments = $this->codeEnvironmentsDetector->discoverSystemInstalledCodeEnvironments();
$this->projectInstalledCodeEnvironments = $this->codeEnvironmentsDetector->discoverProjectInstalledCodeEnvironments(base_path());
}
protected function collectInstallationPreferences(): void
{
$this->selectedBoostFeatures = $this->selectBoostFeatures();
$this->selectedAiGuidelines = $this->selectAiGuidelines();
$this->selectedTargetMcpClient = $this->selectTargetMcpClients();
$this->selectedTargetAgents = $this->selectTargetAgents();
$this->enforceTests = $this->determineTestEnforcement();
}
protected function performInstallation(): void
{
if ($this->installGuidelines) {
$this->installGuidelines();
}
usleep(750000);
if ($this->installMcpConfig && $this->selectedTargetMcpClient->isNotEmpty()) {
$this->installMcpServerConfig();
}
}
protected function discoverTools(): array
{
$tools = [];
$toolDir = implode(DIRECTORY_SEPARATOR, [__DIR__, '..', 'Mcp', 'Tools']);
$finder = Finder::create()
->in($toolDir)
->files()
->name('*.php');
foreach ($finder as $toolFile) {
$fullyClassifiedClassName = 'Laravel\\Boost\\Mcp\\Tools\\'.$toolFile->getBasename('.php');
if (class_exists($fullyClassifiedClassName, false)) {
$tools[$fullyClassifiedClassName] = Str::headline($toolFile->getBasename('.php'));
}
}
ksort($tools);
return $tools;
}
protected function outro(): void
{
$label = 'https://boost.laravel.com/installed';
$ideNames = $this->selectedTargetMcpClient->map(fn (McpClient $mcpClient): string => 'i:'.$mcpClient->mcpClientName())
->toArray();
$agentNames = $this->selectedTargetAgents->map(fn (Agent $agent): string => 'a:'.$agent->agentName())->toArray();
$boostFeatures = $this->selectedBoostFeatures->map(fn ($feature): string => 'b:'.$feature)->toArray();
$guidelines = [];
$guidelines[] = 'g:ai';
if ($this->shouldInstallStyleGuidelines()) {
$guidelines[] = 'g:style';
}
$allData = array_merge($ideNames, $agentNames, $boostFeatures, $guidelines);
$installData = base64_encode(implode(',', $allData));
$link = $this->hyperlink($label, 'https://boost.laravel.com/installed/?d='.$installData);
$text = 'Enjoy the boost 🚀 Next steps: ';
$paddingLength = (int) (floor(($this->terminal->cols() - mb_strlen($text.$label)) / 2)) - 2;
$this->output->write([
"\033[42m\033[2K".str_repeat(' ', max(0, $paddingLength)),
$this->black($this->bold($text.$link)).$this->reset(PHP_EOL).$this->reset(PHP_EOL),
]);
}
protected function hyperlink(string $label, string $url): string
{
return "\033]8;;{$url}\007{$label}\033]8;;\033\\";
}
/**
* We shouldn't add an AI guideline enforcing tests if they don't have a basic test setup.
* This would likely just create headaches for them or be a waste of time as they
* won't have the CI setup to make use of them anyway, so we're just wasting their
* tokens/money by enforcing them.
*/
protected function determineTestEnforcement(): bool
{
if (! $this->installGuidelines) {
return false;
}
$hasMinimumTests = false;
if (file_exists(base_path('vendor/bin/phpunit'))) {
$process = new Process([PHP_BINARY, 'artisan', 'test', '--list-tests'], base_path());
$process->run();
/** Count the number of tests - they'll always have :: between the filename and test name */
$hasMinimumTests = Str::of($process->getOutput())
->trim()
->explode("\n")
->filter(fn ($line): bool => str_contains($line, '::'))
->count() >= self::MIN_TEST_COUNT;
}
return $hasMinimumTests;
}
/**
* @return Collection<int, string>
*/
protected function selectBoostFeatures(): Collection
{
if (! $this->installMcpConfig) {
return collect();
}
$features = collect(['mcp_server', 'ai_guidelines']);
if ($this->herd->isMcpAvailable() && $this->shouldConfigureHerdMcp()) {
$features->push('herd_mcp');
}
if ($this->sail->isInstalled() && ($this->sail->isActive() || $this->shouldConfigureSail())) {
$features->push('sail');
}
return $features;
}
protected function shouldConfigureSail(): bool
{
return confirm(
label: 'Laravel Sail detected. Configure Boost MCP to use Sail?',
default: $this->config->getSail(),
hint: 'This will configure the MCP server to run through Sail. Note: Sail must be running to use Boost MCP',
);
}
protected function shouldConfigureHerdMcp(): bool
{
return confirm(
label: 'Would you like to install Herd MCP alongside Boost MCP?',
default: $this->config->getHerdMcp(),
hint: 'The Herd MCP provides additional tools like browser logs, which can help AI understand issues better',
);
}
/**
* @return Collection<int, string>
*/
protected function selectAiGuidelines(): Collection
{
if (! $this->installGuidelines) {
return collect();
}
$options = app(GuidelineComposer::class)->guidelines()
->reject(fn (array $guideline): bool => $guideline['third_party'] === false);
if ($options->isEmpty()) {
return collect();
}
return collect(multiselect(
label: 'Which third-party AI guidelines do you want to install?',
// @phpstan-ignore-next-line
options: $options->mapWithKeys(function (array $guideline, string $name): array {
$humanName = str_replace('/core', '', $name);
return [$name => "{$humanName} (~{$guideline['tokens']} tokens) {$guideline['description']}"];
}),
default: collect($this->config->getGuidelines()),
scroll: 10,
hint: 'You can add or remove them later by running this command again',
));
}
/**
* @return Collection<int, CodeEnvironment>
*/
protected function selectTargetMcpClients(): Collection
{
if (! $this->installMcpConfig) {
return collect();
}
return $this->selectCodeEnvironments(
McpClient::class,
sprintf('Which code editors do you use to work on %s?', $this->projectName),
$this->config->getEditors(),
);
}
/**
* @return Collection<int, CodeEnvironment>
*/
protected function selectTargetAgents(): Collection
{
if (! $this->installGuidelines) {
return collect();
}
$defaults = $this->config->getAgents();
if ($this->selectedTargetMcpClient->isNotEmpty()) {
$defaults = $this->selectedTargetMcpClient
->filter(fn (McpClient $client): bool => $client instanceof Agent)
->map(fn (McpClient $client): string => $client->name())
->values()
->toArray();
}
return $this->selectCodeEnvironments(
Agent::class,
sprintf('Which agents need AI guidelines for %s?', $this->projectName),
$defaults,
);
}
/**
* Get configuration settings for contract-specific selection behavior.
*
* @return array{required: bool, displayMethod: string}
*/
protected function getSelectionConfig(string $contractClass): array
{
return match ($contractClass) {
Agent::class => ['required' => false, 'displayMethod' => 'agentName'],
McpClient::class => ['required' => true, 'displayMethod' => 'displayName'],
default => throw new InvalidArgumentException("Unsupported contract class: {$contractClass}"),
};
}
/**
* @param array<int, string> $defaults
* @return Collection<int, CodeEnvironment>
*/
protected function selectCodeEnvironments(string $contractClass, string $label, array $defaults): Collection
{
$allEnvironments = $this->codeEnvironmentsDetector->getCodeEnvironments();
$config = $this->getSelectionConfig($contractClass);
$availableEnvironments = $allEnvironments->filter(fn (CodeEnvironment $environment): bool => $environment instanceof $contractClass);
if ($availableEnvironments->isEmpty()) {
return collect();
}
$options = $availableEnvironments->mapWithKeys(function (CodeEnvironment $environment) use ($config): array {
$displayMethod = $config['displayMethod'];
$displayText = $environment->{$displayMethod}();
return [$environment->name() => $displayText];
})->sort();
$installedEnvNames = array_unique(array_merge(
$this->projectInstalledCodeEnvironments,
$this->systemInstalledCodeEnvironments
));
$detectedDefaults = [];
if ($defaults === []) {
foreach ($installedEnvNames as $envKey) {
$matchingEnv = $availableEnvironments->first(fn (CodeEnvironment $env): bool => strtolower((string) $envKey) === strtolower($env->name()));
if ($matchingEnv) {
$detectedDefaults[] = $matchingEnv->name();
}
}
}
$selectedCodeEnvironments = collect(multiselect(
label: $label,
options: $options->toArray(),
default: $defaults === [] ? $detectedDefaults : $defaults,
scroll: $options->count(),
required: $config['required'],
hint: $defaults === [] || $detectedDefaults === [] ? '' : sprintf('Auto-detected %s for you',
Arr::join(array_map(function ($className) use ($availableEnvironments, $config) {
$env = $availableEnvironments->first(fn ($env): bool => $env->name() === $className);
$displayMethod = $config['displayMethod'];
return $env->{$displayMethod}();
}, $detectedDefaults), ', ', ' & ')
)
))->sort();
return $selectedCodeEnvironments->map(
fn (string $name) => $availableEnvironments->first(fn ($env): bool => $env->name() === $name),
)->filter()->values();
}
protected function installGuidelines(): void
{
if ($this->selectedTargetAgents->isEmpty()) {
$this->info(' No agents selected for guideline installation.');
return;
}
$guidelineConfig = new GuidelineConfig;
$guidelineConfig->enforceTests = $this->enforceTests;
$guidelineConfig->laravelStyle = $this->shouldInstallStyleGuidelines();
$guidelineConfig->caresAboutLocalization = $this->detectLocalization();
$guidelineConfig->hasAnApi = false;
$guidelineConfig->aiGuidelines = $this->selectedAiGuidelines->values()->toArray();
$guidelineConfig->usesSail = $this->shouldUseSail();
$composer = app(GuidelineComposer::class)->config($guidelineConfig);
$guidelines = $composer->guidelines();
$this->newLine();
$this->info(sprintf(' Adding %d guidelines to your selected agents', $guidelines->count()));
DisplayHelper::grid(
$guidelines
->map(fn ($guideline, string $key): string => $key.($guideline['custom'] ? '*' : ''))
->values()
->sort()
->toArray(),
$this->terminal->cols()
);
$this->newLine();
usleep(750000);
$failed = [];
$composedAiGuidelines = $composer->compose();
$longestAgentName = max(1, ...$this->selectedTargetAgents->map(fn ($agent) => Str::length($agent->agentName()))->toArray());
/** @var CodeEnvironment $agent */
foreach ($this->selectedTargetAgents as $agent) {
$agentName = $agent->agentName();
$displayAgentName = str_pad((string) $agentName, $longestAgentName);
$this->output->write(" {$displayAgentName}... ");
/** @var Agent $agent */
try {
(new GuidelineWriter($agent))
->write($composedAiGuidelines);
$this->line($this->greenTick);
} catch (Exception $e) {
$failed[$agentName] = $e->getMessage();
$this->line($this->redCross);
}
}
$this->newLine();
if ($failed !== []) {
$this->error(sprintf('✗ Failed to install guidelines to %d agent%s:',
count($failed),
count($failed) === 1 ? '' : 's'
));
foreach ($failed as $agentName => $error) {
$this->line(" - {$agentName}: {$error}");
}
}
if ($this->installMcpConfig) {
$this->config->setSail(
$this->shouldUseSail()
);
$this->config->setHerdMcp(
$this->shouldInstallHerdMcp()
);
$this->config->setEditors(
$this->selectedTargetMcpClient->map(fn (McpClient $mcpClient): string => $mcpClient->name())->values()->toArray()
);
}
$this->config->setAgents(
$this->selectedTargetAgents->map(fn (Agent $agent): string => $agent->name())->values()->toArray()
);
$this->config->setGuidelines(
$this->selectedAiGuidelines->values()->toArray()
);
}
protected function shouldInstallStyleGuidelines(): bool
{
return false;
}
protected function shouldInstallHerdMcp(): bool
{
return $this->selectedBoostFeatures->contains('herd_mcp');
}
protected function shouldUseSail(): bool
{
if ($this->selectedBoostFeatures->isEmpty()) {
return $this->config->getSail();
}
return $this->selectedBoostFeatures->contains('sail');
}
protected function buildMcpCommand(McpClient $mcpClient): array
{
$serverName = 'laravel-boost';
if ($this->shouldUseSail()) {
return $this->sail->buildMcpCommand($serverName);
}
$inWsl = $this->isRunningInWsl();
return array_filter([
$serverName,
$inWsl ? 'wsl.exe' : false,
$mcpClient->getPhpPath($inWsl),
$mcpClient->getArtisanPath($inWsl),
'boost:mcp',
]);
}
protected function installMcpServerConfig(): void
{
if ($this->selectedTargetMcpClient->isEmpty()) {
$this->info('No agents selected for guideline installation.');
return;
}
$this->newLine();
$this->info(' Installing MCP servers to your selected IDEs');
$this->newLine();
usleep(750000);
$failed = [];
$longestIdeName = max(
1,
...$this->selectedTargetMcpClient->map(
fn (McpClient $mcpClient) => Str::length($mcpClient->mcpClientName())
)->toArray()
);
foreach ($this->selectedTargetMcpClient as $mcpClient) {
$ideName = $mcpClient->mcpClientName();
$ideDisplay = str_pad((string) $ideName, $longestIdeName);
$this->output->write(" {$ideDisplay}... ");
$results = [];
$mcp = $this->buildMcpCommand($mcpClient);
try {
$result = $mcpClient->installMcp(
array_shift($mcp),
array_shift($mcp),
$mcp
);
if ($result) {
$results[] = $this->greenTick.' Boost';
} else {
$results[] = $this->redCross.' Boost';
$failed[$ideName]['boost'] = 'Failed to write configuration';
}
} catch (Exception $e) {
$results[] = $this->redCross.' Boost';
$failed[$ideName]['boost'] = $e->getMessage();
}
// Install Herd MCP if enabled
if ($this->shouldInstallHerdMcp()) {
$php = $mcpClient->getPhpPath();
try {
$result = $mcpClient->installMcp(
key: 'herd',
command: $php,
args: [$this->herd->mcpPath()],
env: ['SITE_PATH' => base_path()]
);
if ($result) {
$results[] = $this->greenTick.' Herd';
} else {
$results[] = $this->redCross.' Herd';
$failed[$ideName]['herd'] = 'Failed to write configuration';
}
} catch (Exception $e) {
$results[] = $this->redCross.' Herd';
$failed[$ideName]['herd'] = $e->getMessage();
}
}
$this->line(implode(' ', $results));
}
$this->newLine();
if ($failed !== []) {
$this->error(sprintf('%s Some MCP servers failed to install:', $this->redCross));
foreach ($failed as $ideName => $errors) {
foreach ($errors as $server => $error) {
$this->line(" - {$ideName} ({$server}): {$error}");
}
}
}
}
/**
* Is the project actually using localization for their new features?
*/
protected function detectLocalization(): bool
{
$actuallyUsing = false;
/** @phpstan-ignore-next-line */
return $actuallyUsing && is_dir(base_path('lang'));
}
/**
* Are we running inside a Windows Subsystem for Linux (WSL) environment?
* This differentiates between a regular Linux installation and a WSL.
*/
private function isRunningInWsl(): bool
{
// Check for WSL-specific environment variables.
return ! empty(getenv('WSL_DISTRO_NAME')) || ! empty(getenv('IS_WSL'));
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Console;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand('boost:mcp', 'Starts Laravel Boost (usually from mcp.json)')]
class StartCommand extends Command
{
public function handle(): int
{
return Artisan::call('mcp:start laravel-boost');
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Console;
use Illuminate\Console\Command;
use Symfony\Component\Console\Attribute\AsCommand;
#[AsCommand('boost:update', 'Update the Laravel Boost guidelines to the latest guidance')]
class UpdateCommand extends Command
{
public function handle(): void
{
$this->callSilently(InstallCommand::class, [
'--no-interaction' => true,
'--ignore-mcp' => true,
]);
$this->components->info('Boost guidelines updated successfully.');
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Contracts;
/**
* Agent contract for AI coding assistants that receive guidelines.
*/
interface Agent
{
public function name(): string;
/**
* Get the display name of the Agent.
*/
public function agentName(): ?string;
/**
* Get the file path where AI guidelines should be written.
*
* @return string The relative or absolute path to the guideline file
*/
public function guidelinesPath(): string;
/**
* Determine if the guideline file requires frontmatter.
*/
public function frontmatter(): bool;
}
+44
View File
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Contracts;
/**
* Contract for code editors that support MCP (Model Context Protocol).
*/
interface McpClient
{
public function name(): string;
/**
* Get the display name of the MCP (Model Context Protocol) client.
*/
public function mcpClientName(): ?string;
/**
* Whether to use absolute paths for MCP commands.
*/
public function useAbsolutePathForMcp(): bool;
/**
* Get the PHP executable path for this MCP client.
*/
public function getPhpPath(bool $forceAbsolutePath = false): string;
/**
* Get the artisan path for this MCP client.
*/
public function getArtisanPath(bool $forceAbsolutePath = false): string;
/**
* Install an MCP server configuration in this IDE.
*
* @param string $key Server identifier/name
* @param string $command Executable command to run the MCP server
* @param array<int, string> $args Command line arguments
* @param array<string, string> $env Environment variables
* @return bool True if installation succeeded, false otherwise
*/
public function installMcp(string $key, string $command, array $args = [], array $env = []): bool;
}
+55
View File
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Assists;
use Laravel\Roster\Enums\Packages;
use Laravel\Roster\Roster;
class Inertia
{
public function __construct(private Roster $roster) {}
public function gte(string $version): bool
{
if ($this->roster->usesVersion(Packages::INERTIA_LARAVEL, $version, '>=')) {
return true;
}
if ($this->roster->usesVersion(Packages::INERTIA_REACT, $version, '>=')) {
return true;
}
if ($this->roster->usesVersion(Packages::INERTIA_SVELTE, $version, '>=')) {
return true;
}
return $this->roster->usesVersion(Packages::INERTIA_VUE, $version, '>=');
}
public function hasFormComponent(): bool
{
return $this->gte('2.1.0');
}
public function hasFormComponentResets(): bool
{
return $this->gte('2.1.2');
}
public function pagesDirectory(): string
{
$jsPath = base_path('resources/js');
if (is_dir($jsPath)) {
$entries = @scandir($jsPath);
if ($entries !== false && in_array('pages', $entries, true)) {
return 'resources/js/pages';
}
}
return 'resources/js/Pages';
}
}
+202
View File
@@ -0,0 +1,202 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Cli;
use InvalidArgumentException;
class DisplayHelper
{
private const UNICODE_TOP_LEFT = '╭';
private const UNICODE_TOP_RIGHT = '╮';
private const UNICODE_BOTTOM_LEFT = '╰';
private const UNICODE_BOTTOM_RIGHT = '╯';
private const UNICODE_HORIZONTAL = '─';
private const UNICODE_VERTICAL = '│';
private const UNICODE_CROSS = '┼';
private const UNICODE_TOP_T = '┬';
private const UNICODE_BOTTOM_T = '┴';
private const UNICODE_LEFT_T = '├';
private const UNICODE_RIGHT_T = '┤';
private const BORDER_TOP = 'top';
private const BORDER_MIDDLE = 'middle';
private const BORDER_BOTTOM = 'bottom';
private const CELL_PADDING = 2;
private const GRID_CELL_PADDING = 4;
private const ANSI_BOLD = "\e[1m";
private const ANSI_RESET = "\e[0m";
private const SPACE = ' ';
/**
* @param array<int, array<int|string, mixed>> $data
*/
public static function datatable(array $data, int $maxWidth = 80): void
{
if ($data === []) {
return;
}
$columnWidths = self::calculateColumnWidths($data);
$columnWidths = array_map(fn (int $width): int => $width + self::CELL_PADDING, $columnWidths);
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_TOP);
echo self::buildBorder($columnWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
$rowCount = 0;
foreach ($data as $row) {
echo self::buildDataRow($row, $columnWidths).PHP_EOL;
if ($rowCount < count($data) - 1) {
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_MIDDLE);
echo self::buildBorder($columnWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
}
$rowCount++;
}
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_BOTTOM);
echo self::buildBorder($columnWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
}
/**
* @param array<int, string> $items
*/
public static function grid(array $items, int $maxWidth = 80): void
{
if ($items === []) {
return;
}
$maxWidth -= 2; // account for grid margins
$maxItemLength = max(array_map(mb_strlen(...), $items));
$cellWidth = $maxItemLength + self::GRID_CELL_PADDING;
$cellsPerRow = max(1, (int) floor(($maxWidth - 1) / ($cellWidth + 1)));
$rows = array_chunk($items, $cellsPerRow);
$cellWidths = array_fill(0, $cellsPerRow, $cellWidth);
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_TOP);
echo self::SPACE.self::buildBorder($cellWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
$rowCount = 0;
foreach ($rows as $row) {
echo self::SPACE.self::buildGridRow($row, $cellWidth, $cellsPerRow).PHP_EOL;
if ($rowCount < count($rows) - 1) {
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_MIDDLE);
echo self::SPACE.self::buildBorder($cellWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
}
$rowCount++;
}
[$leftChar, $rightChar, $joinChar] = self::getBorderChars(self::BORDER_BOTTOM);
echo self::SPACE.self::buildBorder($cellWidths, $leftChar, $rightChar, $joinChar).PHP_EOL;
}
private static function getBorderChars(string $type): array
{
return match ($type) {
self::BORDER_TOP => [self::UNICODE_TOP_LEFT, self::UNICODE_TOP_RIGHT, self::UNICODE_TOP_T],
self::BORDER_MIDDLE => [self::UNICODE_LEFT_T, self::UNICODE_RIGHT_T, self::UNICODE_CROSS],
self::BORDER_BOTTOM => [self::UNICODE_BOTTOM_LEFT, self::UNICODE_BOTTOM_RIGHT, self::UNICODE_BOTTOM_T],
default => throw new InvalidArgumentException('Border type should be valid'),
};
}
/**
* @param array<int, array<int|string, mixed>> $data
* @return array<int, int>
*/
private static function calculateColumnWidths(array $data): array
{
$columnWidths = [];
foreach ($data as $row) {
foreach ($row as $colIndex => $cell) {
$length = mb_strlen((string) $cell);
$columnWidths[$colIndex] = max($columnWidths[$colIndex] ?? 0, $length);
}
}
return $columnWidths;
}
/**
* @param array<int, int> $widths
*/
private static function buildBorder(array $widths, string $leftChar, string $rightChar, string $joinChar): string
{
$border = $leftChar;
foreach ($widths as $index => $width) {
$border .= str_repeat(self::UNICODE_HORIZONTAL, $width);
if ($index < count($widths) - 1) {
$border .= $joinChar;
}
}
return $border.$rightChar;
}
/**
* @param array<int|string, mixed> $row
* @param array<int, int> $columnWidths
*/
private static function buildDataRow(array $row, array $columnWidths): string
{
$line = self::UNICODE_VERTICAL;
$colIndex = 0;
foreach ($row as $cell) {
$cellStr = ($colIndex === 0) ? self::ANSI_BOLD.$cell.self::ANSI_RESET : $cell;
$padding = $columnWidths[$colIndex] - mb_strlen((string) $cell);
$line .= self::SPACE.$cellStr.str_repeat(self::SPACE, $padding - 1).self::UNICODE_VERTICAL;
$colIndex++;
}
return $line;
}
/**
* @param array<int, string> $row
*/
private static function buildGridRow(array $row, int $cellWidth, int $cellsPerRow): string
{
$line = self::UNICODE_VERTICAL;
$cells = array_map(
fn (int $index): string => self::formatGridCell($row[$index] ?? '', $cellWidth),
range(0, $cellsPerRow - 1)
);
return $line.(implode(self::UNICODE_VERTICAL, $cells).self::UNICODE_VERTICAL);
}
private static function formatGridCell(string $item, int $cellWidth): string
{
if ($item === '' || $item === '0') {
return str_repeat(self::SPACE, $cellWidth);
}
$padding = $cellWidth - mb_strlen($item) - 2;
return self::SPACE.$item.str_repeat(self::SPACE, $padding + 1);
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\CodeEnvironment;
use Laravel\Boost\Contracts\Agent;
use Laravel\Boost\Contracts\McpClient;
use Laravel\Boost\Install\Enums\McpInstallationStrategy;
use Laravel\Boost\Install\Enums\Platform;
class ClaudeCode extends CodeEnvironment implements Agent, McpClient
{
public function name(): string
{
return 'claude_code';
}
public function displayName(): string
{
return 'Claude Code';
}
public function systemDetectionConfig(Platform $platform): array
{
return match ($platform) {
Platform::Darwin, Platform::Linux => [
'command' => 'command -v claude',
],
Platform::Windows => [
'command' => 'where claude 2>nul',
],
};
}
public function projectDetectionConfig(): array
{
return [
'paths' => ['.claude'],
'files' => ['CLAUDE.md'],
];
}
public function mcpInstallationStrategy(): McpInstallationStrategy
{
return McpInstallationStrategy::FILE;
}
public function mcpConfigPath(): string
{
return '.mcp.json';
}
public function guidelinesPath(): string
{
return config('boost.code_environments.claude_code.guidelines_path', 'CLAUDE.md');
}
}
@@ -0,0 +1,264 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\CodeEnvironment;
use Illuminate\Support\Facades\Process;
use Laravel\Boost\BoostManager;
use Laravel\Boost\Contracts\Agent;
use Laravel\Boost\Contracts\McpClient;
use Laravel\Boost\Install\Detection\DetectionStrategyFactory;
use Laravel\Boost\Install\Enums\McpInstallationStrategy;
use Laravel\Boost\Install\Enums\Platform;
use Laravel\Boost\Install\Mcp\FileWriter;
abstract class CodeEnvironment
{
public bool $useAbsolutePathForMcp = false;
public function __construct(protected readonly DetectionStrategyFactory $strategyFactory) {}
abstract public function name(): string;
abstract public function displayName(): string;
public function agentName(): ?string
{
return $this->displayName();
}
public function mcpClientName(): ?string
{
return $this->displayName();
}
public function useAbsolutePathForMcp(): bool
{
return $this->useAbsolutePathForMcp;
}
public function getPhpPath(bool $forceAbsolutePath = false): string
{
$phpBinaryPath = config('boost.executable_paths.php') ?? 'php';
if ($phpBinaryPath === 'php' && ($this->useAbsolutePathForMcp() || $forceAbsolutePath)) {
return PHP_BINARY;
}
return $phpBinaryPath;
}
public function getArtisanPath(bool $forceAbsolutePath = false): string
{
return ($this->useAbsolutePathForMcp() || $forceAbsolutePath) ? base_path('artisan') : 'artisan';
}
/**
* Get the detection configuration for system-wide installation detection.
*
* @return array{paths?: string[], command?: string, files?: string[]}
*/
abstract public function systemDetectionConfig(Platform $platform): array;
/**
* Get the detection configuration for project-specific detection.
*
* @return array{paths?: string[], files?: string[]}
*/
abstract public function projectDetectionConfig(): array;
public function detectOnSystem(Platform $platform): bool
{
$config = $this->systemDetectionConfig($platform);
$strategy = $this->strategyFactory->makeFromConfig($config);
return $strategy->detect($config, $platform);
}
public function detectInProject(string $basePath): bool
{
$config = array_merge($this->projectDetectionConfig(), ['basePath' => $basePath]);
$strategy = $this->strategyFactory->makeFromConfig($config);
return $strategy->detect($config);
}
public function isAgent(): bool
{
return $this->agentName() && $this instanceof Agent;
}
public function isMcpClient(): bool
{
return $this->mcpClientName() && $this instanceof McpClient;
}
public function mcpInstallationStrategy(): McpInstallationStrategy
{
return McpInstallationStrategy::FILE;
}
public static function fromName(string $name): ?CodeEnvironment
{
$detectionFactory = app(DetectionStrategyFactory::class);
$boostManager = app(BoostManager::class);
foreach ($boostManager->getCodeEnvironments() as $class) {
/** @var class-string<CodeEnvironment> $class */
$instance = new $class($detectionFactory);
if ($instance->name() === $name) {
return $instance;
}
}
return null;
}
public function shellMcpCommand(): ?string
{
return null;
}
public function mcpConfigPath(): ?string
{
return null;
}
public function frontmatter(): bool
{
return false;
}
public function mcpConfigKey(): string
{
return 'mcpServers';
}
/** @return array<string, mixed> */
public function defaultMcpConfig(): array
{
return [];
}
/**
* Install MCP server using the appropriate strategy.
*
* @param array<int, string> $args
* @param array<string, string> $env
*/
public function installMcp(string $key, string $command, array $args = [], array $env = []): bool
{
return match ($this->mcpInstallationStrategy()) {
McpInstallationStrategy::SHELL => $this->installShellMcp($key, $command, $args, $env),
McpInstallationStrategy::FILE => $this->installFileMcp($key, $command, $args, $env),
McpInstallationStrategy::NONE => false
};
}
/**
* Build the MCP server configuration payload for file-based installation.
*
* @param array<int, string> $args
* @param array<string, string> $env
* @return array<string, mixed>
*/
public function mcpServerConfig(string $command, array $args = [], array $env = []): array
{
return [
'command' => $command,
'args' => $args,
'env' => $env,
];
}
/**
* Install MCP server using a shell command strategy.
*
* @param array<int, string> $args
* @param array<string, string> $env
*/
protected function installShellMcp(string $key, string $command, array $args = [], array $env = []): bool
{
$shellCommand = $this->shellMcpCommand();
if ($shellCommand === null) {
return false;
}
$normalized = $this->normalizeCommand($command, $args);
// Build environment string
$envString = '';
foreach ($env as $envKey => $value) {
$envKey = strtoupper($envKey);
$envString .= "-e {$envKey}=\"{$value}\" ";
}
// Replace placeholders in shell command
$command = str_replace([
'{key}',
'{command}',
'{args}',
'{env}',
], [
$key,
$normalized['command'],
implode(' ', array_map(fn (string $arg): string => '"'.$arg.'"', $normalized['args'])),
trim($envString),
], $shellCommand);
$result = Process::run($command);
if ($result->successful()) {
return true;
}
return str_contains($result->errorOutput(), 'already exists');
}
/**
* Install MCP server using a file-based configuration strategy.
*
* @param array<int, string> $args
* @param array<string, string> $env
*/
protected function installFileMcp(string $key, string $command, array $args = [], array $env = []): bool
{
$path = $this->mcpConfigPath();
if (! $path) {
return false;
}
$normalized = $this->normalizeCommand($command, $args);
return (new FileWriter($path, $this->defaultMcpConfig()))
->configKey($this->mcpConfigKey())
->addServerConfig($key, $this->mcpServerConfig($normalized['command'], $normalized['args'], $env))
->save();
}
/**
* Normalize command by splitting space-separated commands into command + args.
*
* Absolute paths (starting with / on Unix or a drive letter on Windows)
* are never split, as they may contain spaces (e.g. macOS "Application Support").
*
* @param array<int, string> $args
* @return array{command: string, args: array<int, string>}
*/
protected function normalizeCommand(string $command, array $args = []): array
{
if (str_starts_with($command, '/') || preg_match('#^[a-zA-Z]:[/\\\\]#', $command)) {
return [
'command' => $command,
'args' => $args,
];
}
$parts = str($command)->explode(' ');
return [
'command' => $parts->first(),
'args' => $parts->skip(1)->values()->merge($args)->all(),
];
}
}
@@ -0,0 +1,58 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\CodeEnvironment;
use Laravel\Boost\Contracts\Agent;
use Laravel\Boost\Contracts\McpClient;
use Laravel\Boost\Install\Enums\McpInstallationStrategy;
use Laravel\Boost\Install\Enums\Platform;
class Codex extends CodeEnvironment implements Agent, McpClient
{
public function name(): string
{
return 'codex';
}
public function displayName(): string
{
return 'Codex';
}
public function systemDetectionConfig(Platform $platform): array
{
return match ($platform) {
Platform::Darwin, Platform::Linux => [
'command' => 'which codex',
],
Platform::Windows => [
'command' => 'where codex 2>nul',
],
};
}
public function projectDetectionConfig(): array
{
return [
'paths' => ['.codex'],
'files' => ['AGENTS.md'],
];
}
public function guidelinesPath(): string
{
return config('boost.code_environments.codex.guidelines_path', 'AGENTS.md');
}
public function mcpInstallationStrategy(): McpInstallationStrategy
{
return McpInstallationStrategy::SHELL;
}
public function shellMcpCommand(): string
{
return 'codex mcp add {key} -- {command} {args}';
}
}
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\CodeEnvironment;
use Laravel\Boost\Contracts\Agent;
use Laravel\Boost\Install\Enums\Platform;
class Copilot extends CodeEnvironment implements Agent
{
public function name(): string
{
return 'copilot';
}
public function displayName(): string
{
return 'GitHub Copilot';
}
public function systemDetectionConfig(Platform $platform): array
{
// Copilot doesn't have system-wide detection as it's an extension/feature
return [
'files' => [],
];
}
public function projectDetectionConfig(): array
{
return [
'files' => ['.github/copilot-instructions.md'],
];
}
public function detectOnSystem(Platform $platform): bool
{
return false;
}
public function mcpClientName(): ?string
{
return null;
}
public function guidelinesPath(): string
{
return config('boost.code_environments.copilot.guidelines_path', '.github/copilot-instructions.md');
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\CodeEnvironment;
use Laravel\Boost\Contracts\Agent;
use Laravel\Boost\Contracts\McpClient;
use Laravel\Boost\Install\Enums\Platform;
class Cursor extends CodeEnvironment implements Agent, McpClient
{
public function name(): string
{
return 'cursor';
}
public function displayName(): string
{
return 'Cursor';
}
public function systemDetectionConfig(Platform $platform): array
{
return match ($platform) {
Platform::Darwin => [
'paths' => ['/Applications/Cursor.app'],
],
Platform::Linux => [
'paths' => [
'/opt/cursor',
'/usr/local/bin/cursor',
'~/.local/bin/cursor',
],
],
Platform::Windows => [
'paths' => [
'%ProgramFiles%\\Cursor',
'%LOCALAPPDATA%\\Programs\\Cursor',
],
],
};
}
public function projectDetectionConfig(): array
{
return [
'paths' => ['.cursor'],
];
}
public function mcpConfigPath(): string
{
return '.cursor/mcp.json';
}
public function guidelinesPath(): string
{
return config('boost.code_environments.cursor.guidelines_path', '.cursor/rules/laravel-boost.mdc');
}
public function frontmatter(): bool
{
return true;
}
}
@@ -0,0 +1,52 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\CodeEnvironment;
use Laravel\Boost\Contracts\Agent;
use Laravel\Boost\Contracts\McpClient;
use Laravel\Boost\Install\Enums\Platform;
class Gemini extends CodeEnvironment implements Agent, McpClient
{
public function name(): string
{
return 'gemini';
}
public function displayName(): string
{
return 'Gemini';
}
public function systemDetectionConfig(Platform $platform): array
{
return match ($platform) {
Platform::Darwin, Platform::Linux => [
'command' => 'command -v gemini',
],
Platform::Windows => [
'command' => 'where gemini 2>nul',
],
};
}
public function projectDetectionConfig(): array
{
return [
'paths' => ['.gemini'],
'files' => ['GEMINI.md'],
];
}
public function mcpConfigPath(): string
{
return '.gemini/settings.json';
}
public function guidelinesPath(): string
{
return config('boost.code_environments.gemini.guidelines_path', 'GEMINI.md');
}
}
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\CodeEnvironment;
use Laravel\Boost\Contracts\Agent;
use Laravel\Boost\Contracts\McpClient;
use Laravel\Boost\Install\Enums\McpInstallationStrategy;
use Laravel\Boost\Install\Enums\Platform;
class OpenCode extends CodeEnvironment implements Agent, McpClient
{
public function name(): string
{
return 'opencode';
}
public function displayName(): string
{
return 'OpenCode';
}
public function systemDetectionConfig(Platform $platform): array
{
return match ($platform) {
Platform::Darwin, Platform::Linux => [
'command' => 'command -v opencode',
],
Platform::Windows => [
'command' => 'where opencode 2>nul',
],
};
}
public function projectDetectionConfig(): array
{
return [
'files' => ['AGENTS.md', 'opencode.json'],
];
}
public function mcpInstallationStrategy(): McpInstallationStrategy
{
return McpInstallationStrategy::FILE;
}
public function mcpConfigPath(): string
{
return 'opencode.json';
}
public function guidelinesPath(): string
{
return config('boost.code_environments.opencode.guidelines_path', 'AGENTS.md');
}
public function mcpConfigKey(): string
{
return 'mcp';
}
/** {@inheritDoc} */
public function defaultMcpConfig(): array
{
return [
'$schema' => 'https://opencode.ai/config.json',
];
}
/** {@inheritDoc} */
public function mcpServerConfig(string $command, array $args = [], array $env = []): array
{
return [
'type' => 'local',
'enabled' => true,
'command' => [$command, ...$args],
'environment' => $env,
];
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\CodeEnvironment;
use Laravel\Boost\Contracts\Agent;
use Laravel\Boost\Contracts\McpClient;
use Laravel\Boost\Install\Enums\Platform;
class PhpStorm extends CodeEnvironment implements Agent, McpClient
{
public bool $useAbsolutePathForMcp = true;
public function name(): string
{
return 'phpstorm';
}
public function displayName(): string
{
return 'PhpStorm';
}
public function systemDetectionConfig(Platform $platform): array
{
return match ($platform) {
Platform::Darwin => [
'paths' => ['/Applications/PhpStorm.app'],
],
Platform::Linux => [
'paths' => [
'/opt/phpstorm',
'/opt/PhpStorm*',
'/usr/local/bin/phpstorm',
'~/.local/share/JetBrains/Toolbox/apps/PhpStorm/ch-*',
],
],
Platform::Windows => [
'paths' => [
'%ProgramFiles%\\JetBrains\\PhpStorm*',
'%LOCALAPPDATA%\\JetBrains\\Toolbox\\apps\\PhpStorm\\ch-*',
'%LOCALAPPDATA%\\Programs\\PhpStorm',
],
],
};
}
public function projectDetectionConfig(): array
{
return [
'paths' => ['.idea', '.junie'],
];
}
public function agentName(): string
{
return 'Junie';
}
public function mcpConfigPath(): string
{
return '.junie/mcp/mcp.json';
}
public function guidelinesPath(): string
{
return config('boost.code_environments.phpstorm.guidelines_path', '.junie/guidelines.md');
}
}
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\CodeEnvironment;
use Laravel\Boost\Contracts\McpClient;
use Laravel\Boost\Install\Enums\Platform;
class VSCode extends CodeEnvironment implements McpClient
{
public function name(): string
{
return 'vscode';
}
public function displayName(): string
{
return 'VS Code';
}
public function systemDetectionConfig(Platform $platform): array
{
return match ($platform) {
Platform::Darwin => [
'paths' => ['/Applications/Visual Studio Code.app'],
],
Platform::Linux => [
'command' => 'command -v code',
],
Platform::Windows => [
'paths' => [
'%ProgramFiles%\\Microsoft VS Code',
'%LOCALAPPDATA%\\Programs\\Microsoft VS Code',
],
],
};
}
public function projectDetectionConfig(): array
{
return [
'paths' => ['.vscode'],
];
}
public function mcpConfigPath(): string
{
return '.vscode/mcp.json';
}
public function mcpConfigKey(): string
{
return 'servers';
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install;
use Illuminate\Container\Container;
use Illuminate\Support\Collection;
use Laravel\Boost\BoostManager;
use Laravel\Boost\Install\CodeEnvironment\CodeEnvironment;
use Laravel\Boost\Install\Enums\Platform;
class CodeEnvironmentsDetector
{
public function __construct(
private readonly Container $container,
private readonly BoostManager $boostManager
) {}
/**
* Detect installed applications on the current platform.
*
* @return array<string>
*/
public function discoverSystemInstalledCodeEnvironments(): array
{
$platform = Platform::current();
return $this->getCodeEnvironments()
->filter(fn (CodeEnvironment $program): bool => $program->detectOnSystem($platform))
->map(fn (CodeEnvironment $program): string => $program->name())
->values()
->toArray();
}
/**
* Detect applications used in the current project.
*
* @return array<string>
*/
public function discoverProjectInstalledCodeEnvironments(string $basePath): array
{
return $this->getCodeEnvironments()
->filter(fn (CodeEnvironment $program): bool => $program->detectInProject($basePath))
->map(fn (CodeEnvironment $program): string => $program->name())
->values()
->toArray();
}
/**
* Get all registered code environments.
*
* @return Collection<string, CodeEnvironment>
*/
public function getCodeEnvironments(): Collection
{
return collect($this->boostManager->getCodeEnvironments())
->map(fn (string $className) => $this->container->make($className));
}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Contracts;
use Laravel\Boost\Install\Enums\Platform;
interface DetectionStrategy
{
/**
* Detect if the application is installed on the machine.
*
* @param array{command?:string, basePath?:string, files?:array<string>, paths?:array<string>} $config
*/
public function detect(array $config, ?Platform $platform = null): bool;
}
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Detection;
use Illuminate\Support\Facades\Process;
use Laravel\Boost\Install\Contracts\DetectionStrategy;
use Laravel\Boost\Install\Enums\Platform;
class CommandDetectionStrategy implements DetectionStrategy
{
public function detect(array $config, ?Platform $platform = null): bool
{
if (! isset($config['command'])) {
return false;
}
return Process::run($config['command'])->successful();
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Detection;
use Laravel\Boost\Install\Contracts\DetectionStrategy;
use Laravel\Boost\Install\Enums\Platform;
class CompositeDetectionStrategy implements DetectionStrategy
{
/**
* @param DetectionStrategy[] $strategies
*/
public function __construct(private readonly array $strategies) {}
public function detect(array $config, ?Platform $platform = null): bool
{
foreach ($this->strategies as $strategy) {
if ($strategy->detect($config, $platform)) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,65 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Detection;
use Illuminate\Container\Container;
use InvalidArgumentException;
use Laravel\Boost\Install\Contracts\DetectionStrategy;
class DetectionStrategyFactory
{
private const TYPE_DIRECTORY = 'directory';
private const TYPE_COMMAND = 'command';
private const TYPE_FILE = 'file';
public function __construct(private readonly Container $container) {}
public function make(string|array $type, array $config = []): DetectionStrategy
{
if (is_array($type)) {
return new CompositeDetectionStrategy(
array_map(fn (string|array $singleType): DetectionStrategy => $this->make($singleType, $config), $type)
);
}
return match ($type) {
self::TYPE_DIRECTORY => $this->container->make(DirectoryDetectionStrategy::class),
self::TYPE_COMMAND => $this->container->make(CommandDetectionStrategy::class),
self::TYPE_FILE => $this->container->make(FileDetectionStrategy::class),
default => throw new InvalidArgumentException("Unknown detection type: {$type}"),
};
}
public function makeFromConfig(array $config): DetectionStrategy
{
$type = $this->inferTypeFromConfig($config);
return $this->make($type, $config);
}
protected function inferTypeFromConfig(array $config): string|array
{
$typeMap = [
'files' => self::TYPE_FILE,
'paths' => self::TYPE_DIRECTORY,
'command' => self::TYPE_COMMAND,
];
$types = collect($typeMap)
->only(array_keys($config))
->values()
->all();
if (empty($types)) {
throw new InvalidArgumentException(
'Cannot infer detection type from config keys. Expected one of: '.collect($typeMap)->keys()->join(', ')
);
}
return count($types) > 1 ? $types : reset($types);
}
}
@@ -0,0 +1,63 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Detection;
use Laravel\Boost\Install\Contracts\DetectionStrategy;
use Laravel\Boost\Install\Enums\Platform;
class DirectoryDetectionStrategy implements DetectionStrategy
{
public function detect(array $config, ?Platform $platform = null): bool
{
if (! isset($config['paths'])) {
return false;
}
$basePath = $config['basePath'] ?? '';
foreach ($config['paths'] as $path) {
$expandedPath = $this->expandPath($path, $platform);
// If basePath is provided, prepend it to relative paths
if ($basePath && ! $this->isAbsolutePath($expandedPath)) {
$expandedPath = $basePath.DIRECTORY_SEPARATOR.$expandedPath;
}
if (str_contains($expandedPath, '*')) {
$matches = glob($expandedPath, GLOB_ONLYDIR);
if (! empty($matches)) {
return true;
}
} elseif (is_dir($expandedPath)) {
return true;
}
}
return false;
}
protected function expandPath(string $path, ?Platform $platform = null): string
{
if ($platform === Platform::Windows) {
return preg_replace_callback('/%([^%]+)%/', fn (array $matches) => getenv($matches[1]) ?: $matches[0], $path);
}
if (str_starts_with($path, '~')) {
$home = getenv('HOME');
if ($home) {
return str_replace('~', $home, $path);
}
}
return $path;
}
protected function isAbsolutePath(string $path): bool
{
return str_starts_with($path, '/') ||
str_starts_with($path, '\\') ||
(strlen($path) > 1 && $path[1] === ':'); // Windows C:
}
}
@@ -0,0 +1,26 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Detection;
use Laravel\Boost\Install\Contracts\DetectionStrategy;
use Laravel\Boost\Install\Enums\Platform;
class FileDetectionStrategy implements DetectionStrategy
{
public function detect(array $config, ?Platform $platform = null): bool
{
$basePath = $config['basePath'] ?? getcwd();
if (isset($config['files'])) {
foreach ($config['files'] as $file) {
if (file_exists($basePath.DIRECTORY_SEPARATOR.$file)) {
return true;
}
}
}
return false;
}
}
@@ -0,0 +1,12 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Enums;
enum McpInstallationStrategy: string
{
case SHELL = 'shell';
case FILE = 'file';
case NONE = 'none';
}
+21
View File
@@ -0,0 +1,21 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Enums;
enum Platform: string
{
case Darwin = 'darwin';
case Linux = 'linux';
case Windows = 'windows';
public static function current(): self
{
return match (PHP_OS_FAMILY) {
'Windows' => self::Windows,
'Darwin' => self::Darwin,
default => self::Linux,
};
}
}
+252
View File
@@ -0,0 +1,252 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install;
use Illuminate\Database\Eloquent\Model;
use Laravel\Boost\Install\Assists\Inertia;
use Laravel\Roster\Enums\NodePackageManager;
use Laravel\Roster\Enums\Packages;
use Laravel\Roster\Roster;
use ReflectionClass;
use Symfony\Component\Finder\Finder;
use Throwable;
class GuidelineAssist
{
/** @var array<string, string> */
protected array $modelPaths = [];
protected array $controllerPaths = [];
protected array $enumPaths = [];
protected static array $classes = [];
public function __construct(public Roster $roster, public GuidelineConfig $config)
{
$this->modelPaths = $this->discover(fn ($reflection): bool => ($reflection->isSubclassOf(Model::class) && ! $reflection->isAbstract()));
$this->controllerPaths = $this->discover(fn (ReflectionClass $reflection): bool => (stripos($reflection->getName(), 'controller') !== false || stripos($reflection->getNamespaceName(), 'controller') !== false));
$this->enumPaths = $this->discover(fn ($reflection) => $reflection->isEnum());
}
/**
* @return array<string, string> - className, absolutePath
*/
public function models(): array
{
return $this->modelPaths;
}
/**
* @return array<string, string> - className, absolutePath
*/
public function controllers(): array
{
return $this->controllerPaths;
}
/**
* @return array<string, string> - className, absolutePath
*/
public function enums(): array
{
return $this->enumPaths;
}
/**
* Discover all Eloquent models in the application.
*
* @return array<string, string>
*/
protected function discover(callable $cb): array
{
$classes = [];
$appPath = app_path();
if (! is_dir($appPath)) {
return ['app-path-isnt-a-directory' => $appPath];
}
if (self::$classes === []) {
$finder = Finder::create()
->in($appPath)
->files()
->name('/[A-Z].*\.php$/');
foreach ($finder as $file) {
$relativePath = $file->getRelativePathname();
$namespace = app()->getNamespace();
$className = $namespace.str_replace(
['/', '.php'],
['\\', ''],
$relativePath
);
try {
$path = $appPath.DIRECTORY_SEPARATOR.$relativePath;
if (! $this->fileHasClassLike($path)) {
continue;
}
if (class_exists($className, false)) {
self::$classes[$className] = $path;
}
} catch (Throwable) {
// Ignore exceptions and errors from class loading/reflection
}
}
}
foreach (self::$classes as $className => $path) {
if ($cb(new ReflectionClass($className))) {
$classes[$className] = $path;
}
}
return $classes;
}
public function fileHasClassLike(string $path): bool
{
static $cache = [];
if (isset($cache[$path])) {
return $cache[$path];
}
$code = file_get_contents($path);
if ($code === false) {
return $cache[$path] = false;
}
if (stripos($code, 'class') === false
&& stripos($code, 'interface') === false
&& stripos($code, 'trait') === false
&& stripos($code, 'enum') === false) {
return $cache[$path] = false;
}
$tokens = token_get_all($code);
foreach ($tokens as $token) {
if (is_array($token) && in_array($token[0], [T_CLASS, T_INTERFACE, T_TRAIT, T_ENUM], true)) {
return $cache[$path] = true;
}
}
return $cache[$path] = false;
}
public function shouldEnforceStrictTypes(): bool
{
if ($this->modelPaths === []) {
return false;
}
return str_contains(
file_get_contents(current($this->modelPaths)),
'strict_types=1'
);
}
public function enumContents(): string
{
if ($this->enumPaths === []) {
return '';
}
return file_get_contents(current($this->enumPaths));
}
public function inertia(): Inertia
{
return new Inertia($this->roster);
}
public function supportsPintAgentFormatter(): bool
{
return $this->roster->usesVersion(Packages::PINT, '1.27.0', '>=');
}
protected function detectedNodePackageManager(): string
{
return ($this->roster->nodePackageManager() ?? NodePackageManager::NPM)->value;
}
public function nodePackageManagerCommand(string $command): string
{
$npmExecutable = config('boost.executable_paths.npm');
if ($npmExecutable !== null) {
return "{$npmExecutable} {$command}";
}
if ($this->config->usesSail) {
return Sail::nodePackageManagerCommand($this->detectedNodePackageManager())." {$command}";
}
return "{$this->detectedNodePackageManager()} {$command}";
}
public function artisanCommand(string $command): string
{
return "{$this->artisan()} {$command}";
}
public function composerCommand(string $command): string
{
$composerExecutable = config('boost.executable_paths.composer');
if ($composerExecutable !== null) {
return "{$composerExecutable} {$command}";
}
if ($this->config->usesSail) {
return Sail::composerCommand()." {$command}";
}
return "composer {$command}";
}
public function binCommand(string $command): string
{
$vendorBinPrefix = config('boost.executable_paths.vendor_bin');
if ($vendorBinPrefix !== null) {
return "{$vendorBinPrefix}{$command}";
}
if ($this->config->usesSail) {
return Sail::binCommand().$command;
}
return "vendor/bin/{$command}";
}
public function artisan(): string
{
$phpExecutable = config('boost.executable_paths.php');
if ($phpExecutable !== null) {
return "{$phpExecutable} artisan";
}
return $this->config->usesSail
? Sail::artisanCommand()
: 'php artisan';
}
public function sailBinaryPath(): string
{
return Sail::BINARY_PATH;
}
public function hasPackage(Packages $package): bool
{
return $this->roster->packages()->contains(
fn ($pkg): bool => $pkg->package() === $package
);
}
}
+378
View File
@@ -0,0 +1,378 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
use Laravel\Boost\Support\Composer;
use Laravel\Roster\Enums\Packages;
use Laravel\Roster\Package;
use Laravel\Roster\PackageCollection;
use Laravel\Roster\Roster;
use Symfony\Component\Finder\Exception\DirectoryNotFoundException;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
class GuidelineComposer
{
use RendersBladeGuidelines;
protected string $userGuidelineDir = '.ai/guidelines';
/** @var Collection<string, array> */
protected Collection $guidelines;
protected GuidelineConfig $config;
/**
* Package priority system to handle conflicts between packages.
* When a higher-priority package is present, lower-priority packages are excluded from guidelines.
*
* @var array<string, string[]>
*/
protected array $packagePriorities;
/**
* Only include guidelines for these package names if they're a direct requirement.
* This fixes every Boost user getting the MCP guidelines due to indirect import.
*
* @var array<int, Packages>
* */
protected array $mustBeDirect = [
Packages::MCP,
];
/**
* Packages that should be excluded from automatic guideline inclusion.
* These packages require explicit configuration to be included.
*
* @var array<int, Packages>
*/
protected array $optInPackages = [
Packages::SAIL,
];
public function __construct(protected Roster $roster, protected Herd $herd)
{
$this->packagePriorities = [
Packages::PEST->value => [Packages::PHPUNIT->value],
Packages::FLUXUI_PRO->value => [Packages::FLUXUI_FREE->value],
];
$this->config = new GuidelineConfig;
}
public function config(GuidelineConfig $config): self
{
$this->config = $config;
return $this;
}
/**
* Auto discovers the guideline files and composes them into one string.
*/
public function compose(): string
{
return self::composeGuidelines($this->guidelines());
}
public function customGuidelinePath(string $path = ''): string
{
return base_path($this->userGuidelineDir.'/'.ltrim($path, '/'));
}
/**
* Static method to compose guidelines from a collection.
* Can be used without Laravel dependencies.
*
* @param Collection<string, array{content: string, name: string, path: ?string, custom: bool}> $guidelines
*/
public static function composeGuidelines(Collection $guidelines): string
{
return str_replace("\n\n\n\n", "\n\n", trim($guidelines
->filter(fn ($guideline): bool => ! empty(trim($guideline['content'])))
->map(fn ($guideline, $key): string => "\n=== {$key} rules ===\n\n".trim($guideline['content']))
->join("\n\n"))
);
}
/**
* @return string[]
*/
public function used(): array
{
return $this->guidelines()->keys()->toArray();
}
/**
* @return Collection<string, array>
*/
public function guidelines(): Collection
{
if (! empty($this->guidelines)) {
return $this->guidelines;
}
$base = collect()
->merge($this->getCoreGuidelines())
->merge($this->getConditionalGuidelines())
->merge($this->getPackageGuidelines())
->merge($this->getThirdPartyGuidelines());
$basePaths = $base->pluck('path')->filter()->values();
$customGuidelines = $this->getUserGuidelines()
->reject(fn ($guideline): bool => $basePaths->contains($guideline['path']));
return $this->guidelines = $customGuidelines
->merge($base)
->filter(fn ($guideline): bool => filled($guideline['content']));
}
/**
* @return Collection<string, array>
*/
protected function getUserGuidelines(): Collection
{
return collect($this->guidelinesDir($this->customGuidelinePath()))
->mapWithKeys(fn ($guideline): array => ['.ai/'.$guideline['name'] => $guideline]);
}
/**
* @return Collection<string, array>
*/
protected function getCoreGuidelines(): Collection
{
return collect([
'foundation' => $this->guideline('foundation'),
'boost' => $this->guideline('boost/core'),
'php' => $this->guideline('php/core'),
]);
}
/**
* @return Collection<string, array>
*/
protected function getConditionalGuidelines(): Collection
{
return collect([
'herd' => [
'condition' => str_contains((string) config('app.url'), '.test') && $this->herd->isInstalled() && ! $this->config->usesSail,
'path' => 'herd/core',
],
'sail' => [
'condition' => $this->config->usesSail,
'path' => 'sail/core',
],
'laravel/style' => [
'condition' => $this->config->laravelStyle,
'path' => 'laravel/style',
],
'laravel/api' => [
'condition' => $this->config->hasAnApi,
'path' => 'laravel/api',
],
'laravel/localization' => [
'condition' => $this->config->caresAboutLocalization,
'path' => 'laravel/localization',
],
'tests' => [
'condition' => $this->config->enforceTests,
'path' => 'enforce-tests',
],
])
->filter(fn ($config): bool => $config['condition'])
->mapWithKeys(fn ($config, $key): array => [$key => $this->guideline($config['path'])]);
}
protected function getPackageGuidelines(): PackageCollection
{
return $this->roster->packages()
->reject(fn (Package $package): bool => $this->shouldExcludePackage($package))
->flatMap(function ($package): Collection {
$guidelineDir = str_replace('_', '-', strtolower($package->name()));
$guidelines = collect([$guidelineDir.'/core' => $this->guideline($guidelineDir.'/core')]);
$packageGuidelines = $this->guidelinesDir($guidelineDir.'/'.$package->majorVersion());
foreach ($packageGuidelines as $guideline) {
$suffix = $guideline['name'] === 'core' ? '' : '/'.$guideline['name'];
$guidelines->put(
$guidelineDir.'/v'.$package->majorVersion().$suffix,
$guideline
);
}
return $guidelines;
});
}
/**
* @return Collection<string, array>
*/
protected function getThirdPartyGuidelines(): Collection
{
$guidelines = collect();
collect(Composer::packagesDirectoriesWithBoostGuidelines())
->each(function (string $path, string $package) use ($guidelines): void {
$packageGuidelines = $this->guidelinesDir($path, true);
foreach ($packageGuidelines as $guideline) {
$guidelines->put($package, $guideline);
}
});
return $guidelines->when(
isset($this->config->aiGuidelines),
fn (Collection $collection): Collection => $collection->filter(
fn (mixed $guideline, string $name): bool => in_array($name, $this->config->aiGuidelines, true),
)
);
}
/**
* Determines if a package should be excluded from guidelines based on priority rules.
*/
protected function shouldExcludePackage(Package $package): bool
{
if (in_array($package->package(), $this->optInPackages, true)) {
return true;
}
foreach ($this->packagePriorities as $priorityPackage => $excludedPackages) {
$packageIsInExclusionList = in_array($package->package()->value, $excludedPackages, true);
if ($packageIsInExclusionList && $this->roster->uses(Packages::from($priorityPackage))) {
return true;
}
}
return $package->indirect() && in_array($package->package(), $this->mustBeDirect, true);
}
/**
* @return array<array{content: string, name: string, description: string, path: ?string, custom: bool, third_party: bool}>
*/
protected function guidelinesDir(string $dirPath, bool $thirdParty = false): array
{
if (! is_dir($dirPath)) {
$dirPath = str_replace('/', DIRECTORY_SEPARATOR, __DIR__.'/../../.ai/'.$dirPath);
}
try {
$finder = Finder::create()
->files()
->in($dirPath)
->name('*.blade.php')
->name('*.md');
} catch (DirectoryNotFoundException) {
return [];
}
return collect($finder)
->map(fn (SplFileInfo $file): array => $this->guideline($file->getRealPath(), $thirdParty))
->all();
}
/**
* @return array{content: string, name: string, description: string, path: ?string, custom: bool, third_party: bool}
*/
protected function guideline(string $path, bool $thirdParty = false): array
{
$path = $this->guidelinePath($path);
if (is_null($path)) {
return [
'content' => '',
'description' => '',
'name' => '',
'path' => null,
'custom' => false,
'third_party' => $thirdParty,
];
}
$content = file_get_contents($path);
$content = $this->processBoostSnippets($content);
$rendered = $this->renderContent($content, $path);
$rendered = str_replace(array_keys($this->storedSnippets), array_values($this->storedSnippets), $rendered);
$this->storedSnippets = []; // Clear for next use
$description = Str::of($rendered)
->after('# ')
->before("\n")
->trim()
->limit(50)
->whenEmpty(fn () => Str::of('No description provided'))
->value();
return [
'content' => trim($rendered),
'name' => str_replace(['.blade.php', '.md'], '', basename($path)),
'description' => $description,
'path' => $path,
'custom' => str_contains($path, $this->customGuidelinePath()),
'third_party' => $thirdParty,
'tokens' => round(str_word_count($rendered) * 1.3),
];
}
protected function getGuidelineAssist(): GuidelineAssist
{
return new GuidelineAssist($this->roster, $this->config);
}
protected function prependPackageGuidelinePath(string $path): string
{
return $this->prependGuidelinePath($path, __DIR__.'/../../.ai/');
}
protected function prependUserGuidelinePath(string $path): string
{
return $this->prependGuidelinePath($path, $this->customGuidelinePath());
}
private function prependGuidelinePath(string $path, string $basePath): string
{
if (! str_ends_with($path, '.md') && ! str_ends_with($path, '.blade.php')) {
$path .= '.blade.php';
}
return str_replace('/', DIRECTORY_SEPARATOR, $basePath.$path);
}
protected function guidelinePath(string $path): ?string
{
// Relative path, prepend our package path to it
if (! file_exists($path)) {
$path = $this->prependPackageGuidelinePath($path);
if (! file_exists($path)) {
return null;
}
}
$path = realpath($path);
// If this is a custom guideline, return it unchanged
if (str_contains($path, $this->customGuidelinePath())) {
return $path;
}
// The path is not a custom guideline, check if the user has an override for this
$basePath = realpath(__DIR__.'/../../');
$relativePath = Str::of($path)
->replace([$basePath, '.ai'.DIRECTORY_SEPARATOR, '.ai/'], '')
->ltrim('/\\')
->toString();
$customPath = $this->prependUserGuidelinePath($relativePath);
return file_exists($customPath) ? $customPath : $path;
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install;
class GuidelineConfig
{
public bool $enforceTests = false;
public bool $laravelStyle = false;
public bool $usesSail = false;
public bool $caresAboutLocalization = false;
public bool $hasAnApi = false;
/**
* @var array<int, string>
*/
public array $aiGuidelines;
}
+117
View File
@@ -0,0 +1,117 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install;
use Laravel\Boost\Contracts\Agent;
use RuntimeException;
class GuidelineWriter
{
public const NEW = 0;
public const REPLACED = 1;
public const FAILED = 2;
public const NOOP = 3;
public function __construct(protected Agent $agent) {}
/**
* @return GuidelineWriter::NEW|GuidelineWriter::REPLACED|GuidelineWriter::FAILED|GuidelineWriter::NOOP
*/
public function write(string $guidelines): int
{
if (empty($guidelines)) {
return self::NOOP;
}
$filePath = $this->agent->guidelinesPath();
$directory = dirname($filePath);
if (! is_dir($directory) && ! @mkdir($directory, 0755, true)) {
throw new RuntimeException("Failed to create directory: {$directory}");
}
$handle = @fopen($filePath, 'c+');
if (! $handle) {
throw new RuntimeException("Failed to open file: {$filePath}");
}
try {
$this->acquireLockWithRetry($handle, $filePath);
$content = stream_get_contents($handle);
// Check if guidelines already exist
$pattern = '/<laravel-boost-guidelines>.*?<\/laravel-boost-guidelines>/s';
$replacement = "<laravel-boost-guidelines>\n".$guidelines."\n</laravel-boost-guidelines>";
$replaced = false;
if (preg_match($pattern, $content)) {
// Replace ALL existing boost guidelines blocks in-place
// If the user added guidelines after ours then let's
// make sure we keep the flow.
$newContent = preg_replace($pattern, $replacement, $content, 1);
$replaced = true;
} else {
// No existing Boost guidelines found, append to end of existing file
$frontMatter = '';
if ($this->agent->frontmatter() && ! str_contains($content, "\n---\n")) {
$frontMatter = "---\nalwaysApply: true\n---\n";
}
$existingContent = rtrim($content);
$separatingNewlines = empty($existingContent) ? '' : "\n\n===\n\n";
$newContent = $frontMatter.$existingContent.$separatingNewlines.$replacement;
}
// Normalize multiple blank lines to single blank lines
$newContent = preg_replace("/\n{3,}/", "\n\n", (string) $newContent);
// Ensure file content ends with a newline
if (! str_ends_with((string) $newContent, "\n")) {
$newContent .= "\n";
}
if (ftruncate($handle, 0) === false || fseek($handle, 0) === -1) {
throw new RuntimeException("Failed to reset file pointer: {$filePath}");
}
if (fwrite($handle, (string) $newContent) === false) {
throw new RuntimeException("Failed to write to file: {$filePath}");
}
flock($handle, LOCK_UN);
} finally {
fclose($handle);
}
return $replaced ? self::REPLACED : self::NEW;
}
protected function acquireLockWithRetry(mixed $handle, string $filePath, int $maxRetries = 3): void
{
$attempts = 0;
$delay = 100000; // Start with 100ms in microseconds
while ($attempts < $maxRetries) {
if (flock($handle, LOCK_EX | LOCK_NB)) {
return;
}
$attempts++;
if ($attempts >= $maxRetries) {
throw new RuntimeException("Failed to acquire lock on file after {$maxRetries} attempts: {$filePath}");
}
// Exponential backoff with jitter
$jitter = random_int(0, (int) ($delay * 0.1));
usleep($delay + $jitter);
$delay *= 2;
}
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install;
use Laravel\Boost\Install\Enums\Platform;
class Herd
{
public function isInstalled(): bool
{
if (! $this->isWindowsPlatform()) {
return file_exists('/Applications/Herd.app/Contents/MacOS/Herd');
}
return is_dir($this->getHomePath().'/.config/herd');
}
public function isMcpAvailable(): bool
{
return file_exists($this->mcpPath());
}
public function getHomePath(): string
{
if ($this->isWindowsPlatform()) {
if (! isset($_SERVER['HOME'])) {
$_SERVER['HOME'] = $_SERVER['USERPROFILE'];
}
$_SERVER['HOME'] = str_replace('\\', '/', $_SERVER['HOME']);
}
return $_SERVER['HOME'];
}
public function mcpPath(): string
{
if ($this->isWindowsPlatform()) {
return $this->getHomePath().'/.config/herd/bin/herd-mcp.phar';
}
return '/Applications/Herd.app/Contents/Resources/herd-mcp.phar';
}
public function isWindowsPlatform(): bool
{
return Platform::current() === Platform::Windows;
}
}
+426
View File
@@ -0,0 +1,426 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install\Mcp;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Str;
class FileWriter
{
protected string $configKey = 'mcpServers';
protected array $serversToAdd = [];
protected int $defaultIndentation = 8;
public function __construct(protected string $filePath, protected array $baseConfig = []) {}
public function configKey(string $key): self
{
$this->configKey = $key;
return $this;
}
/**
* @deprecated Use addServerConfig() for array-based configuration.
*
* @param array<int, string> $args
* @param array<string, string> $env
*/
public function addServer(string $key, string $command, array $args = [], array $env = []): self
{
return $this->addServerConfig($key, collect([
'command' => $command,
'args' => $args,
'env' => $env,
])->filter(fn ($value): bool => ! in_array($value, [[], null, ''], true))->toArray());
}
/**
* @param array<string, mixed> $config
*/
public function addServerConfig(string $key, array $config): self
{
$this->serversToAdd[$key] = collect($config)
->filter(fn ($value): bool => ! in_array($value, [[], null, ''], true))
->toArray();
return $this;
}
public function save(): bool
{
$this->ensureDirectoryExists();
if ($this->shouldWriteNew()) {
return $this->createNewFile();
}
$content = $this->readFile();
if ($this->isPlainJson($content)) {
return $this->updatePlainJsonFile($content);
}
return $this->updateJson5File($content);
}
protected function updatePlainJsonFile(string $content): bool
{
$config = json_decode($content, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return false;
}
$this->addServersToConfig($config);
return $this->writeJsonConfig($config);
}
protected function updateJson5File(string $content): bool
{
$configKeyPattern = '/["\']'.preg_quote($this->configKey, '/').'["\']\\s*:\\s*\\{/';
if (preg_match($configKeyPattern, $content, $matches, PREG_OFFSET_CAPTURE)) {
return $this->injectIntoExistingConfigKey($content, $matches);
}
return $this->injectNewConfigKey($content);
}
protected function injectIntoExistingConfigKey(string $content, array $matches): bool
{
// $matches[0][1] contains the position of the configKey pattern match
$configKeyStart = $matches[0][1];
// Find the opening brace of the configKey object
$openBracePos = strpos($content, '{', $configKeyStart);
if ($openBracePos === false) {
return false;
}
// Find the matching closing brace for this configKey object
$closeBracePos = $this->findMatchingClosingBrace($content, $openBracePos);
if ($closeBracePos === false) {
return false;
}
// Filter out servers that already exist
$serversToAdd = $this->filterExistingServers($content, $openBracePos, $closeBracePos);
if ($serversToAdd === []) {
return true;
}
// Detect indentation from surrounding content
$indentLength = $this->detectIndentation($content, $closeBracePos);
$serverJsonParts = [];
foreach ($serversToAdd as $key => $serverConfig) {
$serverJsonParts[] = $this->generateServerJson($key, $serverConfig, $indentLength);
}
$serversJson = implode(','."\n", $serverJsonParts);
// Check if we need a comma and add it to the preceding content
$needsComma = $this->needsCommaBeforeClosingBrace($content, $openBracePos, $closeBracePos);
if (! $needsComma) {
$newContent = substr_replace($content, $serversJson, $closeBracePos, 0);
return $this->writeFile($newContent);
}
// Find the position to add comma (after the last meaningful character)
$commaPosition = $this->findCommaInsertionPoint($content, $openBracePos, $closeBracePos);
if ($commaPosition !== -1) {
$newContent = substr_replace($content, ',', $commaPosition, 0);
$newContent = substr_replace($newContent, $serversJson, $commaPosition + 1, 0);
} else {
$newContent = substr_replace($content, $serversJson, $closeBracePos, 0);
}
return $this->writeFile($newContent);
}
protected function filterExistingServers(string $content, int $openBracePos, int $closeBracePos): array
{
$configContent = substr($content, $openBracePos + 1, $closeBracePos - $openBracePos - 1);
$filteredServers = [];
foreach ($this->serversToAdd as $key => $serverConfig) {
if (! $this->serverExistsInContent($configContent, $key)) {
$filteredServers[$key] = $serverConfig;
}
}
return $filteredServers;
}
protected function serverExistsInContent(string $content, string $serverKey): bool
{
$quotedPattern = '/["\']'.preg_quote($serverKey, '/').'["\']\\s*:/';
$unquotedPattern = '/(?<=^|\\s|,|{)'.preg_quote($serverKey, '/').'\\s*:/m';
return preg_match($quotedPattern, $content) || preg_match($unquotedPattern, $content);
}
protected function injectNewConfigKey(string $content): bool
{
$openBracePos = strpos($content, '{');
if ($openBracePos === false) {
return false;
}
$serverJsonParts = [];
foreach ($this->serversToAdd as $key => $serverConfig) {
$serverJsonParts[] = $this->generateServerJson($key, $serverConfig);
}
$serversJson = implode(',', $serverJsonParts);
$configKeySection = '"'.$this->configKey.'": {'.$serversJson.'}';
$needsComma = $this->needsCommaAfterBrace($content, $openBracePos);
$injection = $configKeySection.($needsComma ? ',' : '');
$newContent = substr_replace($content, $injection, $openBracePos + 1, 0);
return $this->writeFile($newContent);
}
protected function generateServerJson(string $key, array $serverConfig, int $baseIndent = 0): string
{
$json = json_encode($serverConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
// Normalize line endings to Unix style
$json = str_replace("\r\n", "\n", $json);
// If no indentation needed, return as-is
if (empty($baseIndent)) {
return '"'.$key.'": '.$json;
}
// Apply indentation to each line of the JSON
$baseIndent = str_repeat(' ', $baseIndent);
$lines = explode("\n", $json);
$firstLine = array_shift($lines);
$indentedLines = [
"{$baseIndent}\"{$key}\": {$firstLine}",
...array_map(fn (string $line): string => $baseIndent.$line, $lines),
];
return "\n".implode("\n", $indentedLines);
}
protected function needsCommaAfterBrace(string $content, int $bracePosition): bool
{
$afterBrace = substr($content, $bracePosition + 1);
$trimmed = preg_replace('/^\s*(?:\/\/.*$)?/m', '', $afterBrace);
return filled($trimmed) && ! Str::startsWith($trimmed, '}');
}
protected function findMatchingClosingBrace(string $content, int $openBracePos): int|false
{
$braceCount = 1;
$length = strlen($content);
$inString = false;
$escaped = false;
for ($i = $openBracePos + 1; $i < $length; $i++) {
$char = $content[$i];
if (! $inString) {
if ($char === '{') {
$braceCount++;
} elseif ($char === '}') {
$braceCount--;
if ($braceCount === 0) {
return $i;
}
}
}
// Handle string detection (similar to hasUnquotedComments logic)
if ($char === '"' && ! $escaped) {
$inString = ! $inString;
}
$escaped = ($char === '\\' && ! $escaped);
}
return false;
}
protected function needsCommaBeforeClosingBrace(string $content, int $openBracePos, int $closeBracePos): bool
{
// Get content between opening and closing braces
$innerContent = substr($content, $openBracePos + 1, $closeBracePos - $openBracePos - 1);
// Skip whitespace and comments to find last meaningful character
$trimmed = preg_replace('/\s+|\/\/.*$/m', '', $innerContent);
// If empty or ends with opening brace, no comma needed
if (blank($trimmed) || Str::endsWith($trimmed, '{')) {
return false;
}
// If ends with comma, no additional comma needed
return ! Str::endsWith($trimmed, ',');
}
protected function findCommaInsertionPoint(string $content, int $openBracePos, int $closeBracePos): int
{
// Work backwards from closing brace to find last meaningful character
for ($i = $closeBracePos - 1; $i > $openBracePos; $i--) {
$char = $content[$i];
// Skip whitespace and newlines
if (in_array($char, [' ', "\t", "\n", "\r"], true)) {
continue;
}
// Skip comments (simple approach - if we hit //, skip to start of line)
if ($i > 0 && $content[$i - 1] === '/' && $char === '/') {
// Find start of this line
$lineStart = strrpos($content, "\n", $i - strlen($content)) ?: 0;
$i = $lineStart;
continue;
}
// Found last meaningful character, comma goes after it
if ($char !== ',') {
return $i + 1;
}
// Already has comma, no insertion needed
return -1;
}
// Fallback - insert right after opening brace
return $openBracePos + 1;
}
public function detectIndentation(string $content, int $nearPosition): int
{
// Look backwards from the position to find server-level indentation
// We want to find lines that look like: "server-name": {
$lines = explode("\n", substr($content, 0, $nearPosition));
// Look for the most recent server definition to match its indentation
for ($i = count($lines) - 1; $i >= 0; $i--) {
$line = $lines[$i];
// Match server definitions: any amount of whitespace + "key": {
if (preg_match('/^(\s*)"[^"]+"\s*:\s*\{/', $line, $matches)) {
return strlen($matches[1]);
}
}
// Fallback: assume 8 spaces (2 levels of 4-space indentation typical for JSON)
return $this->defaultIndentation;
}
/**
* Is the file content plain JSON, without JSON5 features?
*/
protected function isPlainJson(string $content): bool
{
if ($this->hasUnquotedComments($content)) {
return false;
}
// Trailing commas (,] or ,}) - supported in JSON 5
if (preg_match('/,\s*[\]}]/', $content)) {
return false;
}
// Unquoted keys - supported in JSON 5
if (preg_match('/^\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*:/m', $content)) {
return false;
}
json_decode($content);
return json_last_error() === JSON_ERROR_NONE;
}
protected function hasUnquotedComments(string $content): bool
{
// Regex that matches both quoted strings and comments
// Group 1: Double-quoted strings with escaped characters
// Group 2: Line comments starting with //
$pattern = '/"(\\\\.|[^"\\\\])*"|(\/\/.*)/';
if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
// If group 2 is set, we found a // comment outside strings
if (! empty($match[2])) {
return true;
}
}
}
return false;
}
protected function createNewFile(): bool
{
$config = $this->baseConfig;
$this->addServersToConfig($config);
return $this->writeJsonConfig($config);
}
protected function addServersToConfig(array &$config): void
{
foreach ($this->serversToAdd as $key => $serverConfig) {
data_set($config, $this->configKey.'.'.$key, $serverConfig);
}
}
protected function writeJsonConfig(array $config): bool
{
$json = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
// Normalize line endings to Unix style
if ($json) {
$json = str_replace("\r\n", "\n", $json);
}
return $json && $this->writeFile($json);
}
protected function ensureDirectoryExists(): void
{
File::ensureDirectoryExists(dirname($this->filePath));
}
protected function fileExists(): bool
{
return File::exists($this->filePath);
}
protected function shouldWriteNew(): bool
{
if (! $this->fileExists()) {
return true;
}
return File::size($this->filePath) < 3;
// To account for files that are just `{}`
}
protected function readFile(): string
{
return File::get($this->filePath);
}
protected function writeFile(string $content): bool
{
return File::put($this->filePath, $content) !== false;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Install;
use const DIRECTORY_SEPARATOR;
class Sail
{
public const BINARY_PATH = 'vendor'.DIRECTORY_SEPARATOR.'bin'.DIRECTORY_SEPARATOR.'sail';
public static function artisanCommand(): string
{
return self::command('artisan');
}
public static function binCommand(): string
{
return self::command('bin ');
}
public static function composerCommand(): string
{
return self::command('composer');
}
public static function nodePackageManagerCommand(string $manager): string
{
return self::command($manager);
}
public static function command(string $command): string
{
return self::BINARY_PATH.' '.$command;
}
public function isInstalled(): bool
{
return file_exists(base_path(self::BINARY_PATH)) &&
(file_exists(base_path('docker-compose.yml')) || file_exists(base_path('compose.yaml')));
}
public function isActive(): bool
{
return get_current_user() === 'sail' || getenv('LARAVEL_SAIL') === '1';
}
/**
* @return array<int, string>
*/
public function buildMcpCommand(string $serverName): array
{
return [$serverName, self::BINARY_PATH, 'artisan', 'boost:mcp'];
}
}
+188
View File
@@ -0,0 +1,188 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp;
use InvalidArgumentException;
use Laravel\Boost\Mcp\Methods\CallToolWithExecutor;
use Laravel\Boost\Mcp\Prompts\LaravelCodeSimplifier\LaravelCodeSimplifier;
use Laravel\Boost\Mcp\Prompts\PackageGuidelinePrompt;
use Laravel\Boost\Mcp\Prompts\UpgradeLivewirev4\UpgradeLivewireV4;
use Laravel\Boost\Mcp\Resources\PackageGuidelineResource;
use Laravel\Boost\Mcp\Tools\ApplicationInfo;
use Laravel\Boost\Mcp\Tools\BrowserLogs;
use Laravel\Boost\Mcp\Tools\DatabaseConnections;
use Laravel\Boost\Mcp\Tools\DatabaseQuery;
use Laravel\Boost\Mcp\Tools\DatabaseSchema;
use Laravel\Boost\Mcp\Tools\GetAbsoluteUrl;
use Laravel\Boost\Mcp\Tools\GetConfig;
use Laravel\Boost\Mcp\Tools\LastError;
use Laravel\Boost\Mcp\Tools\ListArtisanCommands;
use Laravel\Boost\Mcp\Tools\ListAvailableConfigKeys;
use Laravel\Boost\Mcp\Tools\ListAvailableEnvVars;
use Laravel\Boost\Mcp\Tools\ListRoutes;
use Laravel\Boost\Mcp\Tools\ReadLogEntries;
use Laravel\Boost\Mcp\Tools\SearchDocs;
use Laravel\Boost\Mcp\Tools\Tinker;
use Laravel\Boost\Support\Composer;
use Laravel\Mcp\Server;
use Laravel\Mcp\Server\Prompt;
use Laravel\Mcp\Server\Resource;
use Laravel\Mcp\Server\Tool;
class Boost extends Server
{
/**
* The MCP server's name.
*/
protected string $name = 'Laravel Boost';
/**
* The MCP server's version.
*/
protected string $version = '0.0.1';
/**
* The MCP server's instructions for the LLM.
*/
protected string $instructions = 'Laravel ecosystem MCP server offering database schema access, Artisan commands, error logs, Tinker execution, semantic documentation search and more. Boost helps with code generation.';
/**
* The default pagination length for resources that support pagination.
*/
public int $defaultPaginationLength = 50;
/**
* The tools registered with this MCP server.
*
* @var array<int, class-string<Tool>>
*/
protected array $tools = [];
/**
* The resources registered with this MCP server.
*
* @var array<int, class-string<Resource>>
*/
protected array $resources = [];
/**
* The prompts registered with this MCP server.
*
* @var array<int, class-string<Prompt>>
*/
protected array $prompts = [];
protected function boot(): void
{
$this->tools = $this->discoverTools();
$this->resources = $this->discoverResources();
$this->prompts = $this->discoverPrompts();
// Override the tools/call method to use our ToolExecutor
$this->methods['tools/call'] = CallToolWithExecutor::class;
}
/**
* @return array<int, class-string<Tool>>
*/
protected function discoverTools(): array
{
return $this->filterPrimitives([
ApplicationInfo::class,
BrowserLogs::class,
DatabaseConnections::class,
DatabaseQuery::class,
DatabaseSchema::class,
GetAbsoluteUrl::class,
GetConfig::class,
LastError::class,
ListArtisanCommands::class,
ListAvailableConfigKeys::class,
ListAvailableEnvVars::class,
ListRoutes::class,
ReadLogEntries::class,
SearchDocs::class,
Tinker::class,
], 'tools');
}
/**
* @return array<int, class-string<Resource>>
*/
protected function discoverResources(): array
{
$availableResources = [
Resources\ApplicationInfo::class,
...$this->discoverThirdPartyPrimitives(Resource::class),
];
return $this->filterPrimitives($availableResources, 'resources');
}
/**
* @return array<int, class-string<Prompt>>
*/
protected function discoverPrompts(): array
{
$availablePrompts = [
LaravelCodeSimplifier::class,
UpgradeLivewireV4::class,
...$this->discoverThirdPartyPrimitives(Prompt::class),
];
return $this->filterPrimitives($availablePrompts, 'prompts');
}
/**
* @template T of Prompt|Resource
*
* @param class-string<T> $primitiveType
* @return array<int, T>
*/
private function discoverThirdPartyPrimitives(string $primitiveType): array
{
$primitiveClass = match ($primitiveType) {
Prompt::class => PackageGuidelinePrompt::class,
Resource::class => PackageGuidelineResource::class,
default => throw new InvalidArgumentException('Invalid Primitive Type'),
};
$primitives = [];
foreach (Composer::packagesDirectoriesWithBoostGuidelines() as $package => $path) {
$corePath = $path.DIRECTORY_SEPARATOR.'core.blade.php';
if (file_exists($corePath)) {
$primitives[] = new $primitiveClass($package, $corePath);
}
}
return $primitives;
}
/**
* @param array<int, Tool|Resource|Prompt|class-string> $availablePrimitives
* @return array<int, Tool|Resource|Prompt|class-string>
*/
private function filterPrimitives(array $availablePrimitives, string $type): array
{
$excludeList = config("boost.mcp.{$type}.exclude", []);
$includeList = config("boost.mcp.{$type}.include", []);
$filtered = collect($availablePrimitives)->reject(function (string|object $item) use ($excludeList): bool {
$className = is_string($item) ? $item : $item::class;
return in_array($className, $excludeList, true);
});
$explicitlyIncluded = collect($includeList)
->filter(fn (string $class): bool => class_exists($class));
return $filtered
->merge($explicitlyIncluded)
->values()
->all();
}
}
@@ -0,0 +1,66 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Methods;
use Laravel\Boost\Mcp\ToolExecutor;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Contracts\Errable;
use Laravel\Mcp\Server\Contracts\Method;
use Laravel\Mcp\Server\Exceptions\JsonRpcException;
use Laravel\Mcp\Server\Methods\Concerns\InteractsWithResponses;
use Laravel\Mcp\Server\ServerContext;
use Laravel\Mcp\Server\Transport\JsonRpcRequest;
use Laravel\Mcp\Server\Transport\JsonRpcResponse;
use Throwable;
class CallToolWithExecutor implements Errable, Method
{
use InteractsWithResponses;
public function __construct(protected ToolExecutor $executor)
{
//
}
/**
* Handle the JSON-RPC tool/call request with process isolation.
*/
public function handle(JsonRpcRequest $request, ServerContext $context): JsonRpcResponse
{
if (is_null($request->get('name'))) {
throw new JsonRpcException(
'Missing [name] parameter.',
-32602,
$request->id,
);
}
$tool = $context
->tools()
->first(
fn ($tool): bool => $tool->name() === $request->params['name'],
fn () => throw new JsonRpcException(
"Tool [{$request->params['name']}] not found.",
-32602,
$request->id,
));
$arguments = [];
if (isset($request->params['arguments']) && is_array($request->params['arguments'])) {
$arguments = $request->params['arguments'];
}
try {
$response = $this->executor->execute($tool::class, $arguments);
} catch (Throwable $throwable) {
$response = Response::error('Tool execution error: '.$throwable->getMessage());
}
return $this->toJsonRpcResponse($request, $response, fn ($responseFactory): array => [
'content' => $responseFactory->responses()->map(fn ($response) => $response->content()->toTool($tool))->all(),
'isError' => $responseFactory->responses()->contains(fn ($response) => $response->isError()),
]);
}
}
View File
@@ -0,0 +1,76 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Prompts\Concerns;
use Illuminate\Support\Facades\Blade;
use Laravel\Boost\Install\GuidelineAssist;
trait RendersBladeGuidelines
{
private array $storedSnippets = [];
protected function renderContent(string $content, string $path): string
{
$isBladeTemplate = str_ends_with($path, '.blade.php');
if (! $isBladeTemplate) {
return $content;
}
// Temporarily replace backticks and PHP opening tags with placeholders before Blade processing
// This prevents Blade from trying to execute PHP code examples and supports inline code
$placeholders = [
'`' => '___SINGLE_BACKTICK___',
'<?php' => '___OPEN_PHP_TAG___',
'@volt' => '___VOLT_DIRECTIVE___',
'@endvolt' => '___ENDVOLT_DIRECTIVE___',
];
$content = str_replace(array_keys($placeholders), array_values($placeholders), $content);
$rendered = Blade::render($content, [
'assist' => $this->getGuidelineAssist(),
]);
return str_replace(array_values($placeholders), array_keys($placeholders), $rendered);
}
protected function processBoostSnippets(string $content): string
{
return preg_replace_callback('/(?<!@)@boostsnippet\(\s*(?P<nameQuote>[\'"])(?P<name>[^\1]*?)\1(?:\s*,\s*(?P<langQuote>[\'"])(?P<lang>[^\3]*?)\3)?\s*\)(?P<content>.*?)@endboostsnippet/s', function (array $matches): string {
$name = $matches['name'];
$lang = empty($matches['lang']) ? 'html' : $matches['lang'];
$snippetContent = $matches['content'];
$placeholder = '___BOOST_SNIPPET_'.count($this->storedSnippets).'___';
$this->storedSnippets[$placeholder] = '<code-snippet name="'.$name.'" lang="'.$lang.'">'."\n".$snippetContent."\n".'</code-snippet>'."\n\n";
return $placeholder;
}, $content);
}
protected function renderGuidelineFile(string $bladePath): string
{
if (! file_exists($bladePath)) {
return '';
}
$content = file_get_contents($bladePath);
$content = $this->processBoostSnippets($content);
$rendered = $this->renderContent($content, $bladePath);
$rendered = str_replace(array_keys($this->storedSnippets), array_values($this->storedSnippets), $rendered);
$this->storedSnippets = [];
return $rendered;
}
protected function getGuidelineAssist(): GuidelineAssist
{
return app(GuidelineAssist::class);
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Prompts\LaravelCodeSimplifier;
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;
class LaravelCodeSimplifier extends Prompt
{
use RendersBladeGuidelines;
protected string $name = 'laravel-code-simplifier';
protected string $title = 'laravel_code_simplifier';
protected string $description = 'Simplifies and refines PHP/Laravel code for clarity, consistency, and maintainability while preserving all functionality. Focuses on recently modified code unless instructed otherwise.';
public function handle(): Response
{
$content = $this->renderGuidelineFile(__DIR__.'/laravel-code-simplifier.blade.php');
return Response::text($content);
}
}
@@ -0,0 +1,66 @@
# Laravel Code Simplifier
You are an expert PHP/Laravel code simplification specialist focused on enhancing code clarity, consistency, and maintainability while preserving exact functionality. Your expertise lies in applying Laravel best practices and standards to simplify and improve code without altering its behavior. You prioritize readable, explicit code over overly compact solutions. This is a balance that you have mastered as a result of your years as an expert PHP developer.
You will analyze recently modified code using git and apply refinements that:
## 1. Preserve Functionality
Never change what the code does - only how it does it. All original features, outputs, and behaviors must remain intact.
## 2. Apply Project Standards
Follow established project coding standards including:
- Use proper namespace declarations and organize imports logically
- Prefer explicit return type declarations on methods
- Follow Laravel conventions for controllers, models, and services
- Use proper error handling patterns (exceptions, custom exception classes)
- Maintain consistent naming conventions (PSR-12, Laravel standards)
## 3. Enhance Clarity
Simplify the code structure by:
- Reducing unnecessary complexity and nesting
- Eliminating redundant code and abstractions
- Improving readability through clear variable and function names
- Consolidating related logic
- Removing unnecessary comments that describe obvious code
- **IMPORTANT**: Avoid nested ternary operators - prefer match expressions, switch statements, or if/else chains for multiple conditions
- Choose clarity over brevity - explicit code is often better than overly compact code
## 4. Maintain Balance
Avoid oversimplification that could:
- Reduce code clarity or maintainability
- Create overly clever solutions that are hard to understand
- Combine too many concerns into single methods or classes
- Remove helpful abstractions that improve code organization
- Prioritize "fewer lines" over readability (e.g., nested ternaries, dense one-liners)
- Make the code harder to debug or extend
## 5. Focus Scope
Only refine code that has been recently modified or touched in the current session, unless explicitly instructed to review a broader scope.
## Refinement Process
1. Identify the recently modified code sections
2. Analyze for opportunities to improve elegance and consistency
3. Apply project-specific best practices and coding standards
4. Ensure all functionality remains unchanged
5. Verify the refined code is simpler and more maintainable
6. Document only significant changes that affect understanding
## Execution Strategy
When multiple files need refinement, maximize efficiency by:
- **Spin up background agents in parallel** to process independent files simultaneously
- Each agent should handle a separate file or logical unit of work
- Coordinate results to ensure consistency across related files
- Use as many concurrent agents as possible when files don't have dependencies on each other
You operate autonomously and proactively, refining code immediately after it's written or modified without requiring explicit requests. Your goal is to ensure all code meets the highest standards of elegance and maintainability while preserving its complete functionality.
@@ -0,0 +1,30 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Prompts;
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;
class PackageGuidelinePrompt extends Prompt
{
use RendersBladeGuidelines;
public function __construct(
protected string $packageName,
protected string $bladePath,
) {
$this->name = $this->packageName;
$this->title = $this->packageName;
$this->description = "Guidelines for {$packageName}";
}
public function handle(): Response
{
$content = $this->renderGuidelineFile($this->bladePath);
return Response::text($content);
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Prompts\UpgradeLivewirev4;
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Prompt;
use Laravel\Roster\Enums\Packages;
use Laravel\Roster\Roster;
class UpgradeLivewireV4 extends Prompt
{
use RendersBladeGuidelines;
protected string $name = 'upgrade-livewire-v4';
protected string $title = 'upgrade_livewire_v4';
protected string $description = 'Provides step-by-step guidance for upgrading from Livewire v3 to v4.';
public function shouldRegister(Roster $roster): bool
{
return $roster->uses(Packages::LIVEWIRE);
}
public function handle(): Response
{
$content = $this->renderGuidelineFile(__DIR__.'/upgrade-livewire-v4.blade.php');
return Response::text($content);
}
}
@@ -0,0 +1,825 @@
# Livewire v3 to v4 Upgrade Specialist
You are an expert Livewire upgrade specialist with deep knowledge of both Livewire v3 and v4. Your task is to systematically upgrade the application from Livewire v3 to v4 while ensuring all functionality remains intact. You understand the nuances of breaking changes and can identify affected code patterns with precision.
## Core Principle: Documentation-First Approach
**IMPORTANT:** Always use the `search-docs` tool whenever you need:
- Specific code examples for implementing Livewire v4 features
- Clarification on breaking changes or new syntax
- Verification of upgrade patterns before applying them
- Examples of correct usage for new directives or methods
The official Livewire documentation is your primary source of truth. Consult it before making assumptions or implementing changes.
## Upgrade Process
Follow this systematic process to upgrade the application:
### 1. Assess Current State
Before making any changes:
- Check `composer.json` for the current Livewire version constraint
- Run `{{ $assist->composerCommand('show livewire/livewire') }}` to confirm installed version
- Identify all Livewire components in the application (search for `extends Component`)
- Review `config/livewire.php` for current configuration
### 2. Create Safety Net
- Ensure you're working on a dedicated branch
- Run the existing test suite to establish baseline
- Note any components with complex JavaScript interactions
### 3. Analyze Codebase for Breaking Changes
Search the codebase for patterns affected by v4 changes:
**High Priority Searches:**
- `config/livewire.php` - Configuration key renames needed
- `Route::get` with Livewire components - May need `Route::livewire()`
- `wire:model` on container elements (divs, modals) - Check for bubbling behavior
- `wire:scroll` - Needs rename to `wire:navigate:scroll`
- `<livewire:` tags - Must be properly closed (self-closing or with closing tag)
**Medium Priority Searches:**
- `wire:transition` with modifiers (`.opacity`, `.scale`, `.duration`) - Modifiers removed
- `$this->stream(` - Parameter order changed
- Array property replacements from JavaScript - Hook behavior changed
**Low Priority Searches:**
- `$wire.$js(` or `$js(` - Deprecated syntax
- `Livewire.hook('commit'` or `Livewire.hook('request'` - Deprecated hooks
### 4. Apply Changes Systematically
For each category of changes:
1. **Search** for affected patterns using grep/search tools
2. **Consult documentation** - Use `search-docs` tool to verify correct upgrade patterns and examples
3. **List** all files that need modification
4. **Apply** the fix consistently across all occurrences
5. **Verify** each change doesn't break functionality
### 5. Update Dependencies
After code changes are complete:
```bash
{{ $assist->composerCommand('require livewire/livewire:^4.0') }}
{{ $assist->artisanCommand('optimize:clear') }}
```
### 6. Test and Verify
- Run the full test suite
- Manually test critical user flows
- Check browser console for JavaScript errors
- Verify all components render correctly
## Execution Strategy
When upgrading, maximize efficiency by:
- **Batch similar changes** - Group all config updates, then all routing updates, etc.
- **Use parallel agents** for independent file modifications
- **Prioritize high-impact changes** that could cause immediate failures
- **Test incrementally** - Verify after each category of changes
## Important Notes
- Most applications can upgrade with minimal changes
- The old syntax for deprecated features still works but should be migrated
---
# Upgrading from v3 to v4
Livewire v4 introduces several improvements and optimizations while maintaining backward compatibility wherever possible. This guide will help you upgrade from Livewire v3 to v4.
> [!tip] Smooth upgrade path
> Most applications can upgrade to v4 with minimal changes. The breaking changes are primarily configuration updates and method signature changes that only affect advanced usage.
## Installation
Update your `composer.json` to require Livewire v4:
@boostsnippet('Installation', 'bash')
composer require livewire/livewire:^4.0
@endboostsnippet
After updating, clear your application's cache:
@boostsnippet('Clear Cache', 'bash')
php artisan optimize:clear
@endboostsnippet
> [!info] View all changes on GitHub
> For a complete overview of all code changes between v3 and v4, you can review the full diff on GitHub: [Compare 3.x to main →](https://github.com/livewire/livewire/compare/3.x...main)
## High-impact changes
These changes are most likely to affect your application and should be reviewed carefully.
### Config file updates
Several configuration keys have been renamed, reorganized, or have new defaults. Update your `config/livewire.php` file:
> [!tip] View the full config file
> For reference, you can view the complete v4 config file on GitHub: [livewire.php →](https://github.com/livewire/livewire/blob/main/config/livewire.php)
#### Renamed configuration keys
**Layout configuration:**
@boostsnippet('Layout Configuration', 'php')
// Before (v3)
'layout' => 'components.layouts.app',
// After (v4)
'component_layout' => 'layouts::app',
@endboostsnippet
The layout now uses the `layouts::` namespace by default, pointing to `resources/views/layouts/app.blade.php`.
**Placeholder configuration:**
@boostsnippet('Placeholder Configuration', 'php')
// Before (v3)
'lazy_placeholder' => 'livewire.placeholder',
// After (v4)
'component_placeholder' => 'livewire.placeholder',
@endboostsnippet
#### Changed defaults
**Smart wire:key behavior:**
@boostsnippet('Smart Wire Key', 'php')
// Now defaults to true (was false in v3)
'smart_wire_keys' => true,
@endboostsnippet
This helps prevent wire:key issues on deeply nested components. Note: You still need to add `wire:key` manually in loops—this setting doesn't eliminate that requirement.
[Learn more about wire:key →](/docs/4.x/nesting#rendering-children-in-a-loop)
#### New configuration options
**Component locations:**
@boostsnippet('Component Locations', 'php')
'component_locations' => [
resource_path('views/components'),
resource_path('views/livewire'),
],
@endboostsnippet
Defines where Livewire looks for single-file and multi-file (view-based) components.
**Component namespaces:**
@boostsnippet('Component Namespaces', 'php')
'component_namespaces' => [
'layouts' => resource_path('views/layouts'),
'pages' => resource_path('views/pages'),
],
@endboostsnippet
Creates custom namespaces for organizing view-based components (e.g., `<livewire:pages::dashboard />`).
**Make command defaults:**
@boostsnippet('Make Command Defaults', 'php')
'make_command' => [
'type' => 'sfc', // Options: 'sfc', 'mfc', or 'class'
'emoji' => true, // Whether to use ⚡ emoji prefix
],
@endboostsnippet
Configure default component format and emoji usage. Set `type` to `'class'` to match v3 behavior.
**CSP-safe mode:**
@boostsnippet('CSP Safe Mode', 'php')
'csp_safe' => false,
@endboostsnippet
Enable Content Security Policy mode to avoid `unsafe-eval` violations. When enabled, Livewire uses the [Alpine CSP build](https://alpinejs.dev/advanced/csp). Note: This mode restricts complex JavaScript expressions in directives like `wire:click="addToCart($event.detail.productId)"` or global references like `window.location`.
### Routing changes
For full-page components, the recommended routing approach has changed:
@boostsnippet('Routing Changes', 'php')
// Before (v3) - still works but not recommended
Route::get('/dashboard', Dashboard::class);
// After (v4) - recommended for all component types
Route::livewire('/dashboard', Dashboard::class);
// For view-based components, you can use the component name
Route::livewire('/dashboard', 'pages::dashboard');
@endboostsnippet
Using `Route::livewire()` is now the preferred method and is required for single-file and multi-file components to work correctly as full-page components.
[Learn more about routing →](/docs/4.x/components#page-components)
### `wire:model` now ignores child events by default
In v3, `wire:model` would respond to input/change events that bubbled up from child elements. This caused unexpected behavior when using `wire:model` on container elements (like modals or accordions) that contained form inputs—clearing an input inside would bubble up and potentially close the modal.
In v4, `wire:model` now only listens for events originating directly on the element itself (equivalent to the `.self` modifier behavior).
If you have code that relies on capturing events from child elements, add the `.deep` modifier:
@boostsnippet('Wire Model Deep', 'blade')
<!-- Before (v3) - listened to child events by default -->
<div wire:model="value">
<input type="text">
</div>
<!-- After (v4) - add .deep to restore old behavior -->
<div wire:model.deep="value">
<input type="text">
</div>
@endboostsnippet
> [!tip] Most apps won't need changes
> This change primarily affects non-standard uses of `wire:model` on container elements. Standard form input bindings (inputs, selects, textareas) are unaffected.
### Use `wire:navigate:scroll`
When using `wire:scroll` to preserve scroll in a scrollable container across `wire:navigate` requests in v3, you will need to instead use `wire:navigate:scroll` in v4:
@boostsnippet('Wire Navigate Scroll', 'blade')
@@persist('sidebar')
<div class="overflow-y-scroll" wire:scroll> <!-- [tl! remove] -->
<div class="overflow-y-scroll" wire:navigate:scroll> <!-- [tl! add] -->
<!-- ... -->
</div>
@@endpersist
@endboostsnippet
### Component tags must be closed
In v3, Livewire component tags would render even without being properly closed. In v4, with the addition of slot support, component tags must be properly closed—otherwise Livewire interprets subsequent content as slot content and the component won't render:
@boostsnippet('Component Tags Closed', 'blade')
<!-- Before (v3) - unclosed tag -->
<livewire:component-name>
<!-- After (v4) - Self-closing tag -->
<livewire:component-name />
@endboostsnippet
[Learn more about rendering components →](/docs/4.x/components#rendering-components)
[Learn more about slots →](/docs/4.x/nesting#slots)
## Medium-impact changes
These changes may affect certain parts of your application depending on which features you use.
### `wire:transition` now uses View Transitions API
In v3, `wire:transition` was a wrapper around Alpine's `x-transition` directive, supporting modifiers like `.opacity`, `.scale`, `.duration.200ms`, and `.origin.top`.
In v4, `wire:transition` uses the browser's native [View Transitions API](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) instead. Basic usage still works—elements will fade in and out smoothly—but all modifiers have been removed.
@boostsnippet('Wire Transition', 'blade')
<!-- This still works in v4 -->
<div wire:transition>...</div>
<!-- These modifiers are no longer supported -->
<div wire:transition.opacity>...</div> <!-- [tl! remove] -->
<div wire:transition.scale.origin.top>...</div> <!-- [tl! remove] -->
<div wire:transition.duration.500ms>...</div> <!-- [tl! remove] -->
@endboostsnippet
[Learn more about wire:transition →](/docs/4.x/wire-transition)
### Performance improvements
Livewire v4 includes significant performance improvements to the request handling system:
- **Non-blocking polling**: `wire:poll` no longer blocks other requests or is blocked by them
- **Parallel live updates**: `wire:model.live` requests now run in parallel, allowing faster typing and quicker results
These improvements happen automatically—no changes needed to your code.
### Update hooks consolidate array/object changes
When replacing an entire array or object from the frontend (e.g., `$wire.items = ['new', 'values']`), Livewire now sends a single consolidated update instead of granular updates for each index.
**Before:** Setting `$wire.items = ['a', 'b']` on an array of 4 items would fire `updatingItems`/`updatedItems` hooks multiple times—once for each index change plus `__rm__` removals.
**After:** The same operation fires the hooks once with the full new array value, matching v2 behavior.
If your code relies on individual index hooks firing when replacing entire arrays, you may need to adjust. Single-item changes (like `wire:model="items.0"`) still fire granular hooks as expected.
### Method signature changes
If you're extending Livewire's core functionality or using these methods directly, note these signature changes:
**Streaming:**
The `stream()` method parameter order has changed:
@boostsnippet('Stream Method Signature', 'php')
// Before (v3)
$this->stream(to: '#container', content: 'Hello', replace: true);
// After (v4)
$this->stream(content: 'Hello', replace: true, el: '#container');
@endboostsnippet
If you're using named parameters (as shown above), note that `to:` has been renamed to `el:`. If you're using positional parameters, you'll need to update to the following:
@boostsnippet('Stream Positional Parameters', 'php')
// Before (v3) - positional parameters
$this->stream('#container', 'Hello');
// After (v4) - positional/named parameters
$this->stream('Hello', el: '#container');
@endboostsnippet
[Learn more about streaming →](/docs/4.x/wire-stream)
**Component mounting (internal):**
If you're extending `LivewireManager` or calling the `mount()` method directly:
@boostsnippet('Mount Method Signature', 'php')
// Before (v3)
public function mount($name, $params = [], $key = null)
// After (v4)
public function mount($name, $params = [], $key = null, $slots = [])
@endboostsnippet
This change adds support for passing slots when mounting components and generally won't affect most applications.
## Low-impact changes
These changes only affect applications using advanced features or customization.
### JavaScript deprecations
#### Deprecated: `$wire.$js()` method
The `$wire.$js()` method for defining JavaScript actions has been deprecated:
@boostsnippet('Wire JS Deprecation', 'js')
// Deprecated (v3)
$wire.$js('bookmark', () => {
// Toggle bookmark...
})
// New (v4)
$wire.$js.bookmark = () => {
// Toggle bookmark...
}
@endboostsnippet
The new syntax is cleaner and more intuitive.
#### Deprecated: `$js` without prefix
The use of `$js` in scripts without `$wire.$js` or `this.$js` prefix has been deprecated:
@boostsnippet('JS Without Prefix Deprecation', 'js')
// Deprecated (v3)
$js('bookmark', () => {
// Toggle bookmark...
})
// New (v4)
$wire.$js.bookmark = () => {
// Toggle bookmark...
}
// Or
this.$js.bookmark = () => {
// Toggle bookmark...
}
@endboostsnippet
> [!tip] Old syntax still works
> Both `$wire.$js('bookmark', ...)` and `$js('bookmark', ...)` will continue to work in v4 for backward compatibility, but you should migrate to the new syntax when convenient.
#### Deprecated: `commit` and `request` hooks
The `commit` and `request` hooks have been deprecated in favor of a new interceptor system that provides more granular control and better performance.
> [!tip] Old hooks still work
> The deprecated hooks will continue to work in v4 for backward compatibility, but you should migrate to the new system when convenient.
#### Migrating from `commit` hook
The old `commit` hook:
@boostsnippet('Old Commit Hook', 'js')
// OLD - Deprecated
Livewire.hook('commit', ({ component, commit, respond, succeed, fail }) => {
respond(() => {
// Runs after response received but before processing
})
succeed(({ snapshot, effects }) => {
// Runs after successful response
})
fail(() => {
// Runs if request failed
})
})
@endboostsnippet
Should be replaced with the new `interceptMessage`:
@boostsnippet('New Intercept Message', 'js')
// NEW - Recommended
Livewire.interceptMessage(({ component, message, onFinish, onSuccess, onError, onFailure }) => {
onFinish(() => {
// Equivalent to respond()
})
onSuccess(({ payload }) => {
// Equivalent to succeed()
// Access snapshot via payload.snapshot
// Access effects via payload.effects
})
onError(() => {
// Equivalent to fail() for server errors
})
onFailure(() => {
// Equivalent to fail() for network errors
})
})
@endboostsnippet
#### Migrating from `request` hook
The old `request` hook:
@boostsnippet('Old Request Hook', 'js')
// OLD - Deprecated
Livewire.hook('request', ({ url, options, payload, respond, succeed, fail }) => {
respond(({ status, response }) => {
// Runs when response received
})
succeed(({ status, json }) => {
// Runs on successful response
})
fail(({ status, content, preventDefault }) => {
// Runs on failed response
})
})
@endboostsnippet
Should be replaced with the new `interceptRequest`:
@boostsnippet('New Intercept Request', 'js')
// NEW - Recommended
Livewire.interceptRequest(({ request, onResponse, onSuccess, onError, onFailure }) => {
// Access url via request.uri
// Access options via request.options
// Access payload via request.payload
onResponse(({ response }) => {
// Equivalent to respond()
// Access status via response.status
})
onSuccess(({ response, responseJson }) => {
// Equivalent to succeed()
// Access status via response.status
// Access json via responseJson
})
onError(({ response, responseBody, preventDefault }) => {
// Equivalent to fail() for server errors
// Access status via response.status
// Access content via responseBody
})
onFailure(({ error }) => {
// Equivalent to fail() for network errors
})
})
@endboostsnippet
#### Key differences
1. **More granular error handling**: The new system separates network failures (`onFailure`) from server errors (`onError`)
2. **Better lifecycle hooks**: Message interceptors provide additional hooks like `onSync`, `onMorph`, and `onRender`
3. **Cancellation support**: Both messages and requests can be cancelled/aborted
4. **Component scoping**: Message interceptors can be scoped to specific components using `$wire.intercept(...)`
For complete documentation on the new interceptor system, see the [JavaScript Interceptors documentation](/docs/4.x/javascript#interceptors).
## Upgrading Volt
Livewire v4 now supports single-file components, which use the same syntax as Volt class-based components. This means you can migrate from Volt to Livewire's built-in single-file components.
### Update component imports
Replace all instances of `Livewire\Volt\Component` with `Livewire\Component`:
@boostsnippet('Volt Import Update', 'php')
// Before (Volt)
use Livewire\Volt\Component;
new class extends Component { ... }
// After (Livewire v4)
use Livewire\Component;
new class extends Component { ... }
@endboostsnippet
### Remove Volt service provider
Delete the Volt service provider file:
@boostsnippet('Remove Volt Provider', 'bash')
rm app/Providers/VoltServiceProvider.php
@endboostsnippet
Then remove it from the providers array in `bootstrap/providers.php`:
@boostsnippet('Update Providers Array', 'php')
// Before
return [
App\Providers\AppServiceProvider::class,
App\Providers\VoltServiceProvider::class,
];
// After
return [
App\Providers\AppServiceProvider::class,
];
@endboostsnippet
### Remove Volt package
Uninstall the Volt package:
@boostsnippet('Uninstall Volt', 'bash')
composer remove livewire/volt
@endboostsnippet
### Install Livewire v4
After completing the above changes, install Livewire v4. Your existing Volt class-based components will work without modification since they use the same syntax as Livewire's single-file components.
## New features in v4
Livewire v4 introduces several powerful new features you can start using immediately:
### Component features
**Single-file and multi-file components**
v4 introduces new component formats alongside the traditional class-based approach. Single-file components combine PHP and Blade in one file, while multi-file components organize PHP, Blade, JavaScript, and tests in a directory.
By default, view-based component files are prefixed with a ⚡ emoji to distinguish them from regular Blade files in your editor and searches. This can be disabled via the `make_command.emoji` config.
@boostsnippet('Make Livewire Commands', 'bash')
php artisan make:livewire create-post # Single-file (default)
php artisan make:livewire create-post --mfc # Multi-file
php artisan livewire:convert create-post # Convert between formats
@endboostsnippet
[Learn more about component formats →](/docs/4.x/components)
**Slots and attribute forwarding**
Components now support slots and automatic attribute bag forwarding using `@{{ $attributes }}`, making component composition more flexible.
[Learn more about nesting components →](/docs/4.x/nesting)
**JavaScript in view-based components**
View-based components can now include `<script>` tags without the `@@script` wrapper. These scripts are served as separate cached files for better performance and automatic `$wire` binding:
@boostsnippet('JavaScript in Components', 'blade')
<div>
<!-- Your component template -->
</div>
<script>
// $wire is automatically bound as 'this'
this.count++ // Same as $wire.count++
// $wire is still available if preferred
$wire.save()
</script>
@endboostsnippet
[Learn more about JavaScript in components →](/docs/4.x/javascript)
### Islands
Islands allow you to create isolated regions within a component that update independently, dramatically improving performance without creating separate child components.
@boostsnippet('Islands Example', 'blade')
@@island(name: 'stats', lazy: true)
<div>@{{ $this->expensiveStats }}</div>
@@endisland
@endboostsnippet
[Learn more about islands →](/docs/4.x/islands)
### Loading improvements
**Deferred loading**
In addition to lazy loading (viewport-based), components can now be deferred to load immediately after the initial page load:
@boostsnippet('Deferred Loading Blade', 'blade')
<livewire:revenue defer />
@endboostsnippet
@boostsnippet('Deferred Loading PHP', 'php')
#[Defer]
class Revenue extends Component { ... }
@endboostsnippet
**Bundled loading**
Control whether multiple lazy/deferred components load in parallel or bundled together:
@boostsnippet('Bundled Loading Blade', 'blade')
<livewire:revenue lazy.bundle />
<livewire:expenses defer.bundle />
@endboostsnippet
@boostsnippet('Bundled Loading PHP', 'php')
#[Lazy(bundle: true)]
class Revenue extends Component { ... }
@endboostsnippet
[Learn more about lazy and deferred loading →](/docs/4.x/lazy)
### Async actions
Run actions in parallel without blocking other requests using the `.async` modifier or `#[Async]` attribute:
@boostsnippet('Async Actions Blade', 'blade')
<button wire:click.async="logActivity">Track</button>
@endboostsnippet
@boostsnippet('Async Actions PHP', 'php')
#[Async]
public function logActivity() { ... }
@endboostsnippet
[Learn more about async actions →](/docs/4.x/actions#parallel-execution-with-async)
### New directives and modifiers
**`wire:sort` - Drag-and-drop sorting**
Built-in support for sortable lists with drag-and-drop:
@boostsnippet('Wire Sort', 'blade')
<ul wire:sort="updateOrder">
@@foreach ($items as $item)
<li wire:sort:item="@{{ $item->id }}" wire:key="@{{ $item->id }}">@{{ $item->name }}</li>
@@endforeach
</ul>
@endboostsnippet
[Learn more about wire:sort →](/docs/4.x/wire-sort)
**`wire:intersect` - Viewport intersection**
Run actions when elements enter or leave the viewport, similar to Alpine's [`x-intersect`](https://alpinejs.dev/plugins/intersect):
@boostsnippet('Wire Intersect', 'blade')
<!-- Basic usage -->
<div wire:intersect="loadMore">...</div>
<!-- With modifiers -->
<div wire:intersect.once="trackView">...</div>
<div wire:intersect:leave="pauseVideo">...</div>
<div wire:intersect.half="loadMore">...</div>
<div wire:intersect.full="startAnimation">...</div>
<!-- With options -->
<div wire:intersect.margin.200px="loadMore">...</div>
<div wire:intersect.threshold.50="trackScroll">...</div>
@endboostsnippet
Available modifiers:
- `.once` - Fire only once
- `.half` - Wait until half is visible
- `.full` - Wait until fully visible
- `.threshold.X` - Custom visibility percentage (0-100)
- `.margin.Xpx` or `.margin.X%` - Intersection margin
[Learn more about wire:intersect →](/docs/4.x/wire-intersect)
**`wire:ref` - Element references**
Easily reference and interact with elements in your template:
@boostsnippet('Wire Ref', 'blade')
<div wire:ref="modal">
<!-- Modal content -->
</div>
<button wire:click="$js.scrollToModal">Scroll to modal</button>
<script>
this.$js.scrollToModal = () => {
this.$refs.modal.scrollIntoView()
}
</script>
@endboostsnippet
[Learn more about wire:ref →](/docs/4.x/wire-ref)
**`.renderless` modifier**
Skip component re-rendering directly from the template:
@boostsnippet('Renderless Modifier', 'blade')
<button wire:click.renderless="trackClick">Track</button>
@endboostsnippet
This is an alternative to the `#[Renderless]` attribute for actions that don't need to update the UI.
**`.preserve-scroll` modifier**
Preserve scroll position during updates to prevent layout jumps:
@boostsnippet('Preserve Scroll', 'blade')
<button wire:click.preserve-scroll="loadMore">Load More</button>
@endboostsnippet
**`data-loading` attribute**
Every element that triggers a network request automatically receives a `data-loading` attribute, making it easy to style loading states with Tailwind:
@boostsnippet('Data Loading', 'blade')
<button wire:click="save" class="data-loading:opacity-50 data-loading:pointer-events-none">
Save Changes
</button>
@endboostsnippet
[Learn more about loading states →](/docs/4.x/loading-states)
### JavaScript improvements
**`$errors` magic property**
Access your component's error bag from JavaScript:
@boostsnippet('Errors Magic Property', 'blade')
<div wire:show="$errors.has('email')">
<span wire:text="$errors.first('email')"></span>
</div>
@endboostsnippet
[Learn more about validation →](/docs/4.x/validation)
**`$intercept` magic**
Intercept and modify Livewire requests from JavaScript:
@boostsnippet('Intercept Magic', 'blade')
<script>
this.$intercept('save', ({ ... }) => {
// ...
})
</script>
@endboostsnippet
[Learn more about JavaScript interceptors →](/docs/4.x/javascript#interceptors)
**Island targeting from JavaScript**
Trigger island renders directly from the template:
@boostsnippet('Island Targeting', 'blade')
<button wire:click="loadMore" wire:island.append="stats">
Load more
</button>
@endboostsnippet
[Learn more about islands →](/docs/4.x/islands)
## Getting help
If you encounter issues during the upgrade:
- Check the [documentation](https://livewire.laravel.com) for detailed feature guides
- Visit the [GitHub discussions](https://github.com/livewire/livewire/discussions) for community support
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Resources;
use Laravel\Boost\Mcp\ToolExecutor;
use Laravel\Boost\Mcp\Tools\ApplicationInfo as ApplicationInfoTool;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Resource;
class ApplicationInfo extends Resource
{
public function __construct(protected ToolExecutor $toolExecutor) {}
/**
* The resource's description.
*/
protected string $description = 'Comprehensive application information including PHP version, Laravel version, database engine, all installed packages with their versions, and all Eloquent models in the application.';
/**
* The resource's URI.
*/
protected string $uri = 'file://instructions/application-info.md';
/**
* The resource's MIME type.
*/
protected string $mimeType = 'text/markdown';
/**
* Handle the resource request.
*/
public function handle(): Response
{
$response = $this->toolExecutor->execute(ApplicationInfoTool::class);
if ($response->isError()) {
return $response; // Return the error response directly
}
$data = json_decode((string) $response->content(), true);
if (! $data) {
return Response::error('Error parsing application information');
}
return Response::json($data);
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Resources;
use Laravel\Boost\Mcp\Prompts\Concerns\RendersBladeGuidelines;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Resource;
class PackageGuidelineResource extends Resource
{
use RendersBladeGuidelines;
public function __construct(
protected string $packageName,
protected string $bladePath,
) {
$this->name = $this->packageName;
$this->title = $this->packageName;
$this->uri = "file://instructions/{$packageName}.md";
$this->description = "Guidelines for {$packageName}";
$this->mimeType = 'text/markdown';
}
public function handle(): Response
{
$content = $this->renderGuidelineFile($this->bladePath);
return Response::text($content);
}
}
+133
View File
@@ -0,0 +1,133 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp;
use Dotenv\Dotenv;
use Illuminate\Support\Env;
use Laravel\Mcp\Response;
use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Exception\ProcessTimedOutException;
use Symfony\Component\Process\Process;
class ToolExecutor
{
public function execute(string $toolClass, array $arguments = []): Response
{
if (! ToolRegistry::isToolAllowed($toolClass)) {
return Response::error("Tool not registered or not allowed: {$toolClass}");
}
return $this->executeInSubprocess($toolClass, $arguments);
}
protected function executeInSubprocess(string $toolClass, array $arguments): Response
{
$command = $this->buildCommand($toolClass, $arguments);
// We need to 'unset' env vars that will be passed from the parent process to the child process, stopping the child process from reading .env and getting updated values
$env = (Dotenv::create(
Env::getRepository(),
app()->environmentPath(),
app()->environmentFile()
))->safeLoad();
$cleanEnv = array_fill_keys(array_keys($env), false);
$process = new Process(
command: $command,
env: $cleanEnv,
timeout: $this->getTimeout($arguments)
);
try {
$process->mustRun();
$output = $process->getOutput();
$decoded = json_decode($output, true);
if (json_last_error() !== JSON_ERROR_NONE) {
return Response::error('Invalid JSON output from tool process: '.json_last_error_msg());
}
return $this->reconstructResponse($decoded);
} catch (ProcessTimedOutException) {
$process->stop();
return Response::error("Tool execution timed out after {$this->getTimeout($arguments)} seconds");
} catch (ProcessFailedException) {
$errorOutput = $process->getErrorOutput().$process->getOutput();
return Response::error("Process tool execution failed: {$errorOutput}");
}
}
protected function getTimeout(array $arguments): int
{
$timeout = (int) ($arguments['timeout'] ?? 180);
return max(1, min(600, $timeout));
}
/**
* Reconstruct a Response from JSON data.
*
* @param array<string, mixed> $data
*/
protected function reconstructResponse(array $data): Response
{
if (! isset($data['isError']) || ! isset($data['content'])) {
return Response::error('Invalid tool response format.');
}
if ($data['isError']) {
$errorText = 'Unknown error';
if (is_array($data['content']) && ! empty($data['content'])) {
$firstContent = $data['content'][0] ?? [];
if (is_array($firstContent)) {
$errorText = $firstContent['text'] ?? $errorText;
}
}
return Response::error($errorText);
}
// Handle array format - extract text content
if (is_array($data['content']) && ! empty($data['content'])) {
$firstContent = $data['content'][0] ?? [];
if (is_array($firstContent)) {
$text = $firstContent['text'] ?? '';
$decoded = json_decode((string) $text, true);
if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
return Response::json($decoded);
}
return Response::text($text);
}
}
return Response::text('');
}
/**
* Build the command array for executing a tool in a subprocess.
*
* @param array<string, mixed> $arguments
* @return array<string>
*/
protected function buildCommand(string $toolClass, array $arguments): array
{
return [
PHP_BINARY,
base_path('artisan'),
'boost:execute-tool',
$toolClass,
base64_encode(json_encode($arguments)),
];
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp;
use DirectoryIterator;
class ToolRegistry
{
/** @var array<int, class-string>|null */
private static ?array $cachedTools = null;
/**
* Get all available tools based on the discovery logic from Boost server.
*
* @return array<int, class-string>
*/
public static function getAvailableTools(): array
{
if (self::$cachedTools !== null) {
return self::$cachedTools;
}
$tools = [];
// Discover tools from the Tools directory
$excludedTools = config('boost.mcp.tools.exclude', []);
$toolDir = new DirectoryIterator(__DIR__.DIRECTORY_SEPARATOR.'Tools');
foreach ($toolDir as $toolFile) {
if ($toolFile->isFile() && $toolFile->getExtension() === 'php') {
$fqdn = 'Laravel\\Boost\\Mcp\\Tools\\'.$toolFile->getBasename('.php');
if (class_exists($fqdn) && ! in_array($fqdn, $excludedTools, true)) {
$tools[] = $fqdn;
}
}
}
// Add extra tools from configuration
$extraTools = config('boost.mcp.tools.include', []);
foreach ($extraTools as $toolClass) {
if (class_exists($toolClass) && ! in_array($toolClass, $tools, true)) {
$tools[] = $toolClass;
}
}
self::$cachedTools = $tools;
return $tools;
}
/**
* Check if a tool class is allowed to be executed.
*/
public static function isToolAllowed(string $toolClass): bool
{
return in_array($toolClass, self::getAvailableTools(), true);
}
/**
* Clear the cached tools (useful for testing or when configuration changes).
*/
public static function clearCache(): void
{
self::$cachedTools = null;
}
/**
* Get tool names (class basenames) mapped to their full class names.
*
* @return array<string, class-string>
*/
public static function getToolNames(): array
{
$tools = self::getAvailableTools();
$names = [];
foreach ($tools as $toolClass) {
$name = class_basename($toolClass);
$names[$name] = $toolClass;
}
return $names;
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Laravel\Boost\Install\GuidelineAssist;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
use Laravel\Roster\Package;
use Laravel\Roster\Roster;
#[IsReadOnly]
class ApplicationInfo extends Tool
{
public function __construct(protected Roster $roster, protected GuidelineAssist $guidelineAssist) {}
/**
* The tool's description.
*/
protected string $description = 'Get comprehensive application information including PHP version, Laravel version, database engine, all installed packages with their versions, and all Eloquent models in the application. You should use this tool on each new chat, and use the package & version data to write version specific code for the packages that exist.';
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
return Response::json([
'php_version' => PHP_VERSION,
'laravel_version' => app()->version(),
'database_engine' => config('database.default'),
'packages' => $this->roster->packages()->map(fn (Package $package): array => ['roster_name' => $package->name(), 'version' => $package->version(), 'package_name' => $package->rawName()]),
'models' => array_keys($this->guidelineAssist->models()),
]);
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Laravel\Boost\Concerns\ReadsLogs;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class BrowserLogs extends Tool
{
use ReadsLogs;
/**
* The tool's description.
*/
protected string $description = 'Read the last N log entries from the BROWSER log. Very helpful for debugging the frontend and JS/Javascript';
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'entries' => $schema->integer()
->description('Number of log entries to return.')
->required(),
];
}
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$maxEntries = $request->integer('entries');
if ($maxEntries <= 0) {
return Response::error('The "entries" argument must be greater than 0.');
}
// Locate the correct log file using the shared helper.
$logFile = storage_path('logs/browser.log');
if (! file_exists($logFile)) {
return Response::error('No log file found, probably means no logs yet.');
}
$entries = $this->readLastLogEntries($logFile, $maxEntries);
if ($entries === []) {
return Response::text('Unable to retrieve log entries, or no logs');
}
$logs = implode("\n\n", $entries);
if (empty(trim($logs))) {
return Response::text('No log entries yet.');
}
return Response::text($logs);
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class DatabaseConnections extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'List the configured database connection names for this application.';
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$connections = array_keys(config('database.connections', []));
return Response::json([
'default_connection' => config('database.default'),
'connections' => $connections,
]);
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Illuminate\Support\Facades\DB;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
use Throwable;
#[IsReadOnly]
class DatabaseQuery extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'Execute a read-only SQL query against the configured database.';
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'query' => $schema->string()
->description('The SQL query to execute. Only read-only queries are allowed (i.e. SELECT, SHOW, EXPLAIN, DESCRIBE).')
->required(),
'database' => $schema->string()
->description("Optional database connection name to use. Defaults to the application's default connection."),
];
}
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$query = trim((string) $request->string('query'));
$token = strtok(ltrim($query), " \t\n\r");
if (! $token) {
return Response::error('Please pass a valid query');
}
$firstWord = strtoupper($token);
// Allowed read-only commands.
$allowList = [
'SELECT',
'SHOW',
'EXPLAIN',
'DESCRIBE',
'DESC',
'WITH', // SELECT must follow Common-table expressions
'VALUES', // Returns literal values
'TABLE', // PostgresSQL shorthand for SELECT *
];
$isReadOnly = in_array($firstWord, $allowList, true);
// Additional validation for WITH … SELECT.
if ($firstWord === 'WITH' && ! preg_match('/with\s+.*select\b/i', $query)) {
$isReadOnly = false;
}
if (! $isReadOnly) {
return Response::error('Only read-only queries are allowed (SELECT, SHOW, EXPLAIN, DESCRIBE, DESC, WITH … SELECT).');
}
$connectionName = $request->get('database');
try {
return Response::json(
DB::connection($connectionName)->select($query)
);
} catch (Throwable $throwable) {
return Response::error('Query failed: '.$throwable->getMessage());
}
}
}
+174
View File
@@ -0,0 +1,174 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Exception;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;
use Laravel\Boost\Mcp\Tools\DatabaseSchema\SchemaDriverFactory;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class DatabaseSchema extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'Read the database schema for this application, including table names, columns, data types, indexes, foreign keys, and more.';
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'database' => $schema->string()
->description("Name of the database connection to dump (defaults to app's default connection, often not needed)"),
'filter' => $schema->string()
->description('Filter the tables by name'),
];
}
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$connection = $request->get('database') ?? config('database.default');
$filter = $request->get('filter') ?? '';
$cacheKey = "boost:mcp:database-schema:{$connection}:{$filter}";
$schema = Cache::remember($cacheKey, 20, fn (): array => $this->getDatabaseStructure($connection, $filter));
return Response::json($schema);
}
protected function getDatabaseStructure(?string $connection, string $filter = ''): array
{
return [
'engine' => DB::connection($connection)->getDriverName(),
'tables' => $this->getAllTablesStructure($connection, $filter),
'global' => $this->getGlobalStructure($connection),
];
}
protected function getAllTablesStructure(?string $connection, string $filter = ''): array
{
$structures = [];
foreach ($this->getAllTables($connection) as $table) {
$tableName = $table['name'];
if ($filter && ! str_contains(strtolower((string) $tableName), strtolower($filter))) {
continue;
}
$structures[$tableName] = $this->getTableStructure($connection, $tableName);
}
return $structures;
}
protected function getAllTables(?string $connection): array
{
return Schema::connection($connection)->getTables();
}
protected function getTableStructure(?string $connection, string $tableName): array
{
$driver = SchemaDriverFactory::make($connection);
try {
$columns = $this->getTableColumns($connection, $tableName);
$indexes = $this->getTableIndexes($connection, $tableName);
$foreignKeys = $this->getTableForeignKeys($connection, $tableName);
$triggers = $driver->getTriggers($tableName);
$checkConstraints = $driver->getCheckConstraints($tableName);
return [
'columns' => $columns,
'indexes' => $indexes,
'foreign_keys' => $foreignKeys,
'triggers' => $triggers,
'check_constraints' => $checkConstraints,
];
} catch (Exception $exception) {
Log::error('Failed to get table structure for: '.$tableName, [
'error' => $exception->getMessage(),
'trace' => $exception->getTraceAsString(),
]);
return [
'error' => 'Failed to get structure: '.$exception->getMessage(),
];
}
}
protected function getTableColumns(?string $connection, string $tableName): array
{
$columns = Schema::connection($connection)->getColumnListing($tableName);
$columnDetails = [];
foreach ($columns as $column) {
$columnDetails[$column] = [
'type' => Schema::connection($connection)->getColumnType($tableName, $column),
];
}
return $columnDetails;
}
protected function getTableIndexes(?string $connection, string $tableName): array
{
try {
$indexes = Schema::connection($connection)->getIndexes($tableName);
$indexDetails = [];
foreach ($indexes as $index) {
$indexDetails[$index['name']] = [
'columns' => Arr::get($index, 'columns'),
'type' => Arr::get($index, 'type'),
'is_unique' => Arr::get($index, 'unique', false),
'is_primary' => Arr::get($index, 'primary', false),
];
}
return $indexDetails;
} catch (Exception) {
return [];
}
}
protected function getTableForeignKeys(?string $connection, string $tableName): array
{
try {
return Schema::connection($connection)->getForeignKeys($tableName);
} catch (Exception) {
return [];
}
}
protected function getGlobalStructure(?string $connection): array
{
$driver = SchemaDriverFactory::make($connection);
return [
'views' => $driver->getViews(),
'stored_procedures' => $driver->getStoredProcedures(),
'functions' => $driver->getFunctions(),
'sequences' => $driver->getSequences(),
];
}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools\DatabaseSchema;
abstract class DatabaseSchemaDriver
{
public function __construct(protected $connection = null) {}
protected function hasTable(?string $table): bool
{
return ! in_array($table, [null, '', '0'], true);
}
abstract public function getViews(): array;
abstract public function getStoredProcedures(): array;
abstract public function getFunctions(): array;
abstract public function getTriggers(?string $table = null): array;
abstract public function getCheckConstraints(string $table): array;
abstract public function getSequences(): array;
}
@@ -0,0 +1,74 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools\DatabaseSchema;
use Exception;
use Illuminate\Support\Facades\DB;
class MySQLSchemaDriver extends DatabaseSchemaDriver
{
public function getViews(): array
{
try {
return DB::connection($this->connection)->select('
SELECT TABLE_NAME as name, VIEW_DEFINITION as definition
FROM information_schema.VIEWS
WHERE TABLE_SCHEMA = DATABASE()
');
} catch (Exception) {
return [];
}
}
public function getStoredProcedures(): array
{
try {
return DB::connection($this->connection)->select('SHOW PROCEDURE STATUS WHERE Db = DATABASE()');
} catch (Exception) {
return [];
}
}
public function getFunctions(): array
{
try {
return DB::connection($this->connection)->select('SHOW FUNCTION STATUS WHERE Db = DATABASE()');
} catch (Exception) {
return [];
}
}
public function getTriggers(?string $table = null): array
{
try {
if ($this->hasTable($table)) {
return DB::connection($this->connection)->select('SHOW TRIGGERS WHERE `Table` = ?', [$table]);
}
return DB::connection($this->connection)->select('SHOW TRIGGERS');
} catch (Exception) {
return [];
}
}
public function getCheckConstraints(string $table): array
{
try {
return DB::connection($this->connection)->select('
SELECT CONSTRAINT_NAME, CHECK_CLAUSE
FROM information_schema.CHECK_CONSTRAINTS
WHERE CONSTRAINT_SCHEMA = DATABASE()
AND TABLE_NAME = ?
', [$table]);
} catch (Exception) {
return [];
}
}
public function getSequences(): array
{
return [];
}
}
@@ -0,0 +1,38 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools\DatabaseSchema;
class NullSchemaDriver extends DatabaseSchemaDriver
{
public function getViews(): array
{
return [];
}
public function getStoredProcedures(): array
{
return [];
}
public function getFunctions(): array
{
return [];
}
public function getTriggers(?string $table = null): array
{
return [];
}
public function getCheckConstraints(string $table): array
{
return [];
}
public function getSequences(): array
{
return [];
}
}
@@ -0,0 +1,101 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools\DatabaseSchema;
use Exception;
use Illuminate\Support\Facades\DB;
class PostgreSQLSchemaDriver extends DatabaseSchemaDriver
{
public function getViews(): array
{
try {
return DB::connection($this->connection)->select("
SELECT schemaname, viewname, definition
FROM pg_views
WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
");
} catch (Exception) {
return [];
}
}
public function getStoredProcedures(): array
{
try {
return DB::connection($this->connection)->select("
SELECT proname, prosrc, proargnames, prorettype
FROM pg_proc p
JOIN pg_namespace n ON p.pronamespace = n.oid
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
AND prokind = 'p'
");
} catch (Exception) {
return [];
}
}
public function getFunctions(): array
{
try {
return DB::connection($this->connection)->select("
SELECT proname, prosrc, proargnames, prorettype
FROM pg_proc p
JOIN pg_namespace n ON p.pronamespace = n.oid
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
AND prokind = 'f'
");
} catch (Exception) {
return [];
}
}
public function getTriggers(?string $table = null): array
{
try {
$sql = '
SELECT trigger_name, event_manipulation, event_object_table, action_statement
FROM information_schema.triggers
WHERE trigger_schema = current_schema()
';
if ($this->hasTable($table)) {
$sql .= ' AND event_object_table = ?';
return DB::connection($this->connection)->select($sql, [$table]);
}
return DB::connection($this->connection)->select($sql);
} catch (Exception) {
return [];
}
}
public function getCheckConstraints(string $table): array
{
try {
return DB::connection($this->connection)->select("
SELECT conname, pg_get_constraintdef(oid) as definition
FROM pg_constraint
WHERE contype = 'c'
AND conrelid = ?::regclass
", [$table]);
} catch (Exception) {
return [];
}
}
public function getSequences(): array
{
try {
return DB::connection($this->connection)->select('
SELECT sequence_name, start_value, minimum_value, maximum_value, increment
FROM information_schema.sequences
WHERE sequence_schema = current_schema()
');
} catch (Exception) {
return [];
}
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools\DatabaseSchema;
use Exception;
use Illuminate\Support\Facades\DB;
class SQLiteSchemaDriver extends DatabaseSchemaDriver
{
public function getViews(): array
{
try {
return DB::connection($this->connection)->select("
SELECT name, sql
FROM sqlite_master
WHERE type = 'view'
");
} catch (Exception) {
return [];
}
}
public function getStoredProcedures(): array
{
return [];
}
public function getFunctions(): array
{
return [];
}
public function getTriggers(?string $table = null): array
{
try {
$sql = "SELECT name, sql FROM sqlite_master WHERE type = 'trigger'";
if ($this->hasTable($table)) {
$sql .= ' AND tbl_name = ?';
return DB::connection($this->connection)->select($sql, [$table]);
}
return DB::connection($this->connection)->select($sql);
} catch (Exception) {
return [];
}
}
public function getCheckConstraints(string $table): array
{
return [];
}
public function getSequences(): array
{
return [];
}
}
@@ -0,0 +1,22 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools\DatabaseSchema;
use Illuminate\Support\Facades\DB;
class SchemaDriverFactory
{
public static function make(?string $connection = null): DatabaseSchemaDriver
{
$driverName = DB::connection($connection)->getDriverName();
return match ($driverName) {
'mysql', 'mariadb' => new MySQLSchemaDriver($connection),
'pgsql' => new PostgreSQLSchemaDriver($connection),
'sqlite' => new SQLiteSchemaDriver($connection),
default => new NullSchemaDriver($connection),
};
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class GetAbsoluteUrl extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'Get the absolute URL for a given relative path or named route. If no arguments are provided, you will get the absolute URL for "/"';
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'path' => $schema->string()
->description('The relative URL/path (e.g. "/dashboard") to convert to an absolute URL.'),
'route' => $schema->string()
->description('The named route to generate an absolute URL for (e.g. "home").'),
];
}
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$path = $request->get('path');
$routeName = $request->get('route');
if ($path) {
return Response::text(url($path));
}
if ($routeName) {
return Response::text(route($routeName));
}
return Response::text(url('/'));
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Illuminate\Support\Facades\Config;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class GetConfig extends Tool
{
protected string $description = 'Get the value of a specific config variable using dot notation (e.g., "app.name", "database.default")';
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'key' => $schema
->string()
->description('The config key in dot notation (e.g., "app.name", "database.default")')
->required(),
];
}
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$key = $request->get('key');
if (! Config::has($key)) {
return Response::error("Config key '{$key}' not found.");
}
return Response::json([
'key' => $key,
'value' => Config::get($key),
]);
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Log\Events\MessageLogged;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Laravel\Boost\Concerns\ReadsLogs;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class LastError extends Tool
{
use ReadsLogs;
/**
* Indicates whether the Log listener has been registered for this process.
*/
private static bool $listenerRegistered = false;
public function __construct()
{
// Register the listener only once per PHP process.
if (! self::$listenerRegistered) {
Log::listen(function (MessageLogged $event): void {
if ($event->level === 'error') {
Cache::forever('boost:last_error', [
'timestamp' => now()->toDateTimeString(),
'level' => $event->level,
'message' => $event->message,
'context' => [], // $event->context,
]);
}
});
self::$listenerRegistered = true;
}
}
/**
* The tool's description.
*/
protected string $description = 'Get details of the last error/exception created in this application on the backend. Use browser-log tool for browser errors.';
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
// First, attempt to retrieve the cached last error captured during runtime.
// This works even if the log driver isn't a file driver, so is the preferred approach
$cached = Cache::get('boost:last_error');
if ($cached) {
$entry = "[{$cached['timestamp']}] {$cached['level']}: {$cached['message']}";
if (! empty($cached['context'])) {
$entry .= ' '.json_encode($cached['context']);
}
return Response::text($entry);
}
// Locate the correct log file using the shared helper.
$logFile = $this->resolveLogFilePath();
if (! file_exists($logFile)) {
return Response::error("Log file not found at {$logFile}");
}
$entry = $this->readLastErrorEntry($logFile);
if ($entry !== null) {
return Response::text($entry);
}
return Response::error('Unable to find an ERROR entry in the inspected portion of the log file.');
}
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Artisan;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class ListArtisanCommands extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'List all available Artisan commands registered in this application.';
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$commands = Artisan::all();
$commandList = [];
foreach ($commands as $name => $command) {
/** @var Command $command */
$commandList[] = [
'name' => $name,
'description' => $command->getDescription(),
];
}
// Sort alphabetically by name for determinism.
usort($commandList, fn (array $firstCommand, array $secondCommand): int => strcmp((string) $firstCommand['name'], (string) $secondCommand['name']));
return Response::json($commandList);
}
}
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Support\Facades\Config;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class ListAvailableConfigKeys extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'List all available Laravel configuration keys (from config/*.php) in dot notation.';
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$configArray = Config::all();
$dotKeys = $this->flattenToDotNotation($configArray);
sort($dotKeys);
return Response::json($dotKeys);
}
/**
* Flatten a multi-dimensional config array into dot notation keys.
*
* @param array<int|string, string|array<int|string, string>> $array
* @return array<int|string, int|string>
*/
protected function flattenToDotNotation(array $array, string $prefix = ''): array
{
$results = [];
foreach ($array as $key => $value) {
$currentKey = $prefix.$key;
if (is_array($value)) {
$results = array_merge($results, $this->flattenToDotNotation($value, $currentKey.'.'));
} else {
// Skip numeric keys at the top level (they're likely array values, not config keys)
if ($prefix === '' && is_numeric($key)) {
continue;
}
$results[] = $currentKey;
}
}
return $results;
}
}
@@ -0,0 +1,70 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class ListAvailableEnvVars extends Tool
{
/**
* The tool's description.
*/
protected string $description = '🔧 List all available environment variable names from a given .env file (default .env).';
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'filename' => $schema->string()
->description('The name of the .env file to read (e.g. .env, .env.example). Defaults to .env if not provided.'),
];
}
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$filename = $request->get('filename', '.env');
$filePath = base_path($filename);
if (! str_contains($filePath, '.env')) {
return Response::error('This tool can only read .env files');
}
if (! file_exists($filePath)) {
return Response::error("File not found at '{$filePath}'");
}
$envLines = file_get_contents($filePath);
if (! $envLines) {
return Response::error('Failed to read .env file.');
}
$count = preg_match_all('/^(?!\s*#)\s*([^=\s]+)=/m', $envLines, $matches);
if (! $count) {
return Response::error('Failed to parse .env file');
}
$envVars = array_map(trim(...), $matches[1]);
sort($envVars);
return Response::json($envVars);
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Illuminate\Support\Facades\Artisan;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
use Symfony\Component\Console\Command\Command as CommandAlias;
use Symfony\Component\Console\Output\BufferedOutput;
#[IsReadOnly]
class ListRoutes extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'List all available routes defined in the application, including Folio routes if used';
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'method' => $schema->string()->description('Filter the routes by HTTP method (e.g., GET, POST, PUT, DELETE).'),
'action' => $schema->string()->description('Filter the routes by controller action (e.g., UserController@index, ChatController, show).'),
'name' => $schema->string()->description('Filter the routes by route name (no wildcards supported).'),
'domain' => $schema->string()->description('Filter the routes by domain.'),
'path' => $schema->string()->description('Only show routes matching the given path pattern.'),
'except_path' => $schema->string()->description('Do not display the routes matching the given path pattern.'),
'except_vendor' => $schema->boolean()->description('Do not display routes defined by vendor packages.'),
'only_vendor' => $schema->boolean()->description('Only display routes defined by vendor packages.'),
];
}
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$optionMap = [
'method' => 'method',
'action' => 'action',
'name' => 'name',
'domain' => 'domain',
'path' => 'path',
'except_path' => 'except-path', // Convert underscore back to hyphen
'except_vendor' => 'except-vendor',
'only_vendor' => 'only-vendor',
];
$options = [
'--no-ansi' => true,
'--no-interaction' => true,
];
foreach ($optionMap as $argKey => $cliOption) {
$value = $request->get($argKey);
if (! empty($value)) {
if (is_bool($value)) {
$options['--'.$cliOption] = true;
} else {
$sanitizedValue = str_replace(['*', '?'], '', $value);
if (filled($sanitizedValue)) {
$options['--'.$cliOption] = $sanitizedValue;
}
}
}
}
$routesOutput = $this->artisan('route:list', $options);
// If Folio is installed, include folio routes (JSON to prevent hanging)
if (class_exists('Laravel\\Folio\\FolioRoutes')) {
$routesOutput .= "\n\n=== FOLIO ROUTES (JSON) ===\n\n";
$folioOptions = $options;
$folioOptions['--json'] = true; // Ensure non-interactive json output
$routesOutput .= $this->artisan('folio:list', $folioOptions);
}
return Response::text($routesOutput);
}
/**
* @param array<string|bool> $options
*/
protected function artisan(string $command, array $options = []): string
{
$output = new BufferedOutput;
$response = Artisan::call($command, $options, $output);
if ($response !== CommandAlias::SUCCESS) {
return 'Failed to list routes: '.$output->fetch();
}
return trim($output->fetch());
}
}
+73
View File
@@ -0,0 +1,73 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Laravel\Boost\Concerns\ReadsLogs;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;
#[IsReadOnly]
class ReadLogEntries extends Tool
{
use ReadsLogs;
/**
* The tool's description.
*/
protected string $description = 'Read the last N log entries from the application log, correctly handling multi-line PSR-3 formatted logs. Only works for log files.';
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'entries' => $schema->integer()
->description('Number of log entries to return.')
->required(),
];
}
/**
* Handle the tool request.
*/
public function handle(Request $request): Response
{
$maxEntries = (int) $request->get('entries');
if ($maxEntries <= 0) {
return Response::error('The "entries" argument must be greater than 0.');
}
// Determine log file path via helper.
$logFile = $this->resolveLogFilePath();
if (! file_exists($logFile)) {
return Response::error("Log file not found at {$logFile}");
}
$entries = $this->readLastLogEntries($logFile, $maxEntries);
if ($entries === []) {
return Response::text('Unable to retrieve log entries, or no entries yet.');
}
$logs = implode("\n\n", $entries);
if (empty(trim($logs))) {
return Response::text('No log entries yet.');
}
return Response::text($logs);
}
// The isNewLogEntry and readLinesReverse helper methods are now provided by the ReadsLogs trait.
}
+107
View File
@@ -0,0 +1,107 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Generator;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Laravel\Boost\Concerns\MakesHttpRequests;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Laravel\Roster\Package;
use Laravel\Roster\Roster;
use Throwable;
class SearchDocs extends Tool
{
use MakesHttpRequests;
public function __construct(protected Roster $roster) {}
/**
* The tool's description.
*/
protected string $description = "Search for up-to-date version-specific documentation related to this project and its packages. This tool will search Laravel hosted documentation based on the packages installed and is perfect for all Laravel ecosystem packages. Laravel, Inertia, Pest, Livewire, Filament, Nova, Tailwind, and more. You must use this tool to search for Laravel-ecosystem docs before using other approaches. The results provided are for this project's package version and does not cover all versions of the package.";
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'queries' => $schema->array()
->items($schema->string()->description('Search query'))
->description('List of queries to perform, pass multiple if you aren\'t sure if it is "toggle" or "switch", for example')
->required(),
'packages' => $schema->array()
->items($schema->string()->description("The composer package name (e.g., 'symfony/console')"))
->description('Package names to limit searching to from application-info. Useful if you know the package(s) you need. i.e. laravel/framework, inertiajs/inertia-laravel, @inertiajs/react'),
'token_limit' => $schema->integer()
->description('Maximum number of tokens to return in the response. Defaults to 3,000 tokens, maximum 1,000,000 tokens. If results are truncated, or you need more complete documentation, increase this value (e.g.5000, 10000)'),
];
}
/**
* Handle the tool request.
*/
public function handle(Request $request): Response|Generator
{
$apiUrl = config('boost.hosted.api_url', 'https://boost.laravel.com').'/api/docs';
$packagesFilter = $request->get('packages');
$queries = array_filter(
array_map(trim(...), $request->get('queries')),
fn (string $query): bool => $query !== '' && $query !== '*'
);
try {
$packagesCollection = $this->roster->packages();
// Only search in specific packages
if ($packagesFilter) {
$packagesCollection = $packagesCollection->filter(fn (Package $package): bool => in_array($package->rawName(), $packagesFilter, true));
}
$packages = $packagesCollection->map(function (Package $package): array {
$name = $package->rawName();
$version = $package->majorVersion().'.x';
return [
'name' => $name,
'version' => $version,
];
});
$packages = $packages->values()->toArray();
} catch (Throwable $throwable) {
return Response::error('Failed to get packages: '.$throwable->getMessage());
}
$tokenLimit = $request->get('token_limit') ?? 3000;
$tokenLimit = min($tokenLimit, 1000000); // Cap at 1M tokens
$payload = [
'queries' => $queries,
'packages' => $packages,
'token_limit' => $tokenLimit,
'format' => 'markdown',
];
try {
$response = $this->client()->asJson()->post($apiUrl, $payload);
if (! $response->successful()) {
return Response::error('Failed to search documentation: '.$response->body());
}
} catch (Throwable $throwable) {
return Response::error('HTTP request failed: '.$throwable->getMessage());
}
return Response::text($response->body());
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Mcp\Tools;
use Exception;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Illuminate\JsonSchema\Types\Type;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
use Throwable;
class Tinker extends Tool
{
/**
* The tool's description.
*/
protected string $description = 'Execute PHP code in the Laravel application context, like artisan tinker. Use this for debugging issues, checking if functions exist, and testing code snippets. You should not create models directly without explicit user approval. Prefer Unit/Feature tests using factories for functionality testing. Prefer existing artisan commands over custom tinker code. Returns the output of the code, as well as whatever is "returned" using "return".';
/**
* Get the tool's input schema.
*
* @return array<string, Type>
*/
public function schema(JsonSchema $schema): array
{
return [
'code' => $schema->string()
->description('PHP code to execute (without opening <?php tags)')
->required(),
'timeout' => $schema->integer()
->description('Maximum execution time in seconds (default: 180)')
->required(),
];
}
/**
* Handle the tool request.
*
* @throws Exception
*/
public function handle(Request $request): Response
{
$code = str_replace(['<?php', '?>'], '', (string) $request->get('code'));
ini_set('memory_limit', '256M');
ob_start();
try {
$result = eval($code);
$output = ob_get_contents();
$response = [
'result' => $result,
'output' => $output,
'type' => gettype($result),
];
// If a result is an object, include the class name
if (is_object($result)) {
$response['class'] = $result::class;
}
return Response::json($response);
} catch (Throwable $throwable) {
return Response::json([
'error' => $throwable->getMessage(),
'type' => $throwable::class,
'file' => $throwable->getFile(),
'line' => $throwable->getLine(),
]);
} finally {
ob_end_clean();
}
}
}
+81
View File
@@ -0,0 +1,81 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Middleware;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Laravel\Boost\Services\BrowserLogger;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
class InjectBoost
{
public function handle(Request $request, Closure $next): Response
{
/** @var Response $response */
$response = $next($request);
if ($this->shouldInject($response)) {
$originalView = $response->original ?? null;
$injectedContent = $this->injectScript($response->getContent());
$response->setContent($injectedContent);
if ($originalView instanceof View && property_exists($response, 'original')) {
$response->original = $originalView;
}
}
return $response;
}
protected function shouldInject(Response $response): bool
{
$responseTypes = [
StreamedResponse::class,
BinaryFileResponse::class,
JsonResponse::class,
RedirectResponse::class,
];
foreach ($responseTypes as $type) {
if ($response instanceof $type) {
return false;
}
}
if (! str_contains((string) $response->headers->get('content-type', ''), 'html')) {
return false;
}
$content = $response->getContent();
// Check if it's HTML
if (! str_contains($content, '<html') && ! str_contains($content, '<head')) {
return false;
}
// Check if already injected
return ! str_contains($content, 'browser-logger-active');
}
protected function injectScript(string $content): string
{
$script = BrowserLogger::getScript();
// Try to inject before closing </head>
if (str_contains($content, '</head>')) {
return str_replace('</head>', $script."\n</head>", $content);
}
// Fallback: inject before closing </body>
if (str_contains($content, '</body>')) {
return str_replace('</body>', $script."\n</body>", $content);
}
return $content.$script;
}
}
+217
View File
@@ -0,0 +1,217 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Services;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Vite;
use Illuminate\View\ComponentAttributeBag;
class BrowserLogger
{
public static function getScript(): string
{
$endpoint = Route::has('boost.browser-logs')
? route('boost.browser-logs')
: '/_boost/browser-logs';
$attributes = new ComponentAttributeBag([
'id' => 'browser-logger-active',
]);
if ($nonce = Vite::cspNonce()) {
$attributes = $attributes->merge(['nonce' => $nonce]);
}
return <<<HTML
<script {$attributes->toHtml()}>
(function() {
const ENDPOINT = '{$endpoint}';
const logQueue = [];
let flushTimeout = null;
console.log('🔍 Browser logger active (MCP server detected). Posting to: ' + ENDPOINT);
// Store original console methods
const originalConsole = {
log: console.log,
info: console.info,
error: console.error,
warn: console.warn,
table: console.table
};
// Helper to safely stringify values
function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]';
seen.add(value);
}
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack
};
}
return value;
});
}
// Batch and send logs
function flushLogs() {
if (logQueue.length === 0) return;
const batch = logQueue.splice(0, logQueue.length);
fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest'
},
body: JSON.stringify({ logs: batch })
}).catch(err => {
// Silently fail to avoid infinite loops
originalConsole.error('Failed to send logs:', err);
});
}
// Debounced flush (100ms)
function scheduleFlush() {
if (flushTimeout) clearTimeout(flushTimeout);
flushTimeout = setTimeout(flushLogs, 100);
}
// Intercept console methods
['log', 'info', 'error', 'warn', 'table'].forEach(method => {
console[method] = function(...args) {
// Call original method
originalConsole[method].apply(console, args);
// Capture log data
try {
logQueue.push({
type: method,
timestamp: new Date().toISOString(),
data: args.map(arg => {
try {
return typeof arg === 'object' ? JSON.parse(safeStringify(arg)) : arg;
} catch (e) {
return String(arg);
}
}),
url: window.location.href,
userAgent: navigator.userAgent
});
scheduleFlush();
} catch (e) {
// Fail silently
}
};
});
// Global error handlers for uncaught errors
const originalOnError = window.onerror;
window.onerror = function boostErrorHandler(errorMsg, url, lineNumber, colNumber, error) {
try {
logQueue.push({
type: 'uncaught_error',
timestamp: new Date().toISOString(),
data: [{
message: errorMsg,
filename: url,
lineno: lineNumber,
colno: colNumber,
error: error ? {
name: error.name,
message: error.message,
stack: error.stack
} : null
}],
url: window.location.href,
userAgent: navigator.userAgent
});
scheduleFlush();
} catch (e) {
// Fail silently
}
// Call original handler if it exists
if (originalOnError && typeof originalOnError === 'function') {
return originalOnError(errorMsg, url, lineNumber, colNumber, error);
}
// Let the error continue to propagate
return false;
}
window.addEventListener('error', (event) => {
try {
logQueue.push({
type: 'window_error',
timestamp: new Date().toISOString(),
data: [{
message: event.message,
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
error: event.error ? {
name: event.error.name,
message: event.error.message,
stack: event.error.stack
} : null
}],
url: window.location.href,
userAgent: navigator.userAgent
});
scheduleFlush();
} catch (e) {
// Fail silently
}
// Let the error continue to propagate
return false;
});
window.addEventListener('unhandledrejection', (event) => {
try {
logQueue.push({
type: 'error',
timestamp: new Date().toISOString(),
data: [{
message: 'Unhandled Promise Rejection',
reason: event.reason instanceof Error ? {
name: event.reason.name,
message: event.reason.message,
stack: event.reason.stack
} : event.reason
}],
url: window.location.href,
userAgent: navigator.userAgent
});
scheduleFlush();
} catch (e) {
// Fail silently
}
// Let the rejection continue to propagate
return false;
});
// Flush on page unload
window.addEventListener('beforeunload', () => {
if (logQueue.length > 0) {
navigator.sendBeacon(ENDPOINT, JSON.stringify({ logs: logQueue }));
}
});
})();
</script>
HTML;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Support;
class Composer
{
public static function packagesDirectories(): array
{
return collect(static::packages())
->mapWithKeys(fn (string $key, string $package): array => [$package => implode(DIRECTORY_SEPARATOR, [
base_path('vendor'),
str_replace('/', DIRECTORY_SEPARATOR, $package),
])])
->filter(fn (string $path): bool => is_dir($path))
->toArray();
}
public static function packages(): array
{
$composerJsonPath = base_path('composer.json');
if (! file_exists($composerJsonPath)) {
return [];
}
$composerData = json_decode(file_get_contents($composerJsonPath), true);
if (json_last_error() !== JSON_ERROR_NONE) {
return [];
}
return collect($composerData['require'] ?? [])
->merge($composerData['require-dev'] ?? [])
->mapWithKeys(fn (string $key, string $package): array => [$package => $key])
->toArray();
}
public static function packagesDirectoriesWithBoostGuidelines(): array
{
return collect(Composer::packagesDirectories())
->map(fn (string $path): string => implode(DIRECTORY_SEPARATOR, [
$path,
'resources',
'boost',
'guidelines',
]))->filter(fn (string $path): bool => is_dir($path))
->toArray();
}
}
+120
View File
@@ -0,0 +1,120 @@
<?php
declare(strict_types=1);
namespace Laravel\Boost\Support;
use Illuminate\Support\Str;
class Config
{
protected const FILE = 'boost.json';
/**
* @return array<int, string>
*/
public function getGuidelines(): array
{
return $this->get('guidelines', []);
}
/**
* @param array<int, string> $guidelines
*/
public function setGuidelines(array $guidelines): void
{
$this->set('guidelines', $guidelines);
}
public function setEditors(array $editors): void
{
$this->set('editors', $editors);
}
/**
* @param array<int, string> $agents
*/
public function setAgents(array $agents): void
{
$this->set('agents', $agents);
}
/**
* @return array<int, string>
*/
public function getAgents(): array
{
return $this->get('agents', []);
}
public function getEditors(): array
{
return $this->get('editors', []);
}
public function setHerdMcp(bool $installed): void
{
$this->set('herd_mcp', $installed);
}
public function getHerdMcp(): bool
{
return $this->get('herd_mcp', false);
}
public function setSail(bool $useSail): void
{
$this->set('sail', $useSail);
}
public function getSail(): bool
{
return $this->get('sail', false);
}
public function flush(): void
{
$path = base_path(self::FILE);
if (file_exists($path)) {
unlink($path);
}
}
protected function get(string $key, mixed $default = null): mixed
{
$config = $this->all();
return data_get($config, $key, $default);
}
protected function set(string $key, mixed $value): void
{
$config = array_filter($this->all());
data_set($config, $key, $value);
ksort($config);
$path = base_path(self::FILE);
file_put_contents($path, Str::of(json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES))->append(PHP_EOL));
}
protected function all(): array
{
$path = base_path(self::FILE);
if (! file_exists($path)) {
return [];
}
$config = json_decode(file_get_contents($path), true);
if (json_last_error() !== JSON_ERROR_NONE) {
return [];
}
return $config ?? [];
}
}