惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
月光博客
月光博客
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
大猫的无限游戏
大猫的无限游戏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
博客园 - 聂微东
Apple Machine Learning Research
Apple Machine Learning Research
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
雷峰网
雷峰网
小众软件
小众软件
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
美团技术团队
宝玉的分享
宝玉的分享
Hugging Face - Blog
Hugging Face - Blog
阮一峰的网络日志
阮一峰的网络日志
A
About on SuperTechFans
Jina AI
Jina AI
D
Docker
Last Week in AI
Last Week in AI
MongoDB | Blog
MongoDB | Blog
Stack Overflow Blog
Stack Overflow Blog
Microsoft Azure Blog
Microsoft Azure Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
One-Step Install and One-Flag OAuth for a Laravel MCP Server
Nasrul Hazim Bin Mohamad · 2026-06-17 · via DEV Community

I tagged cleaniquecoders/laravel-mcp-kit 1.0.0 today, and most of the work that got it there was about one thing: making the setup boring. A kit is only worth shipping if dropping it into the tenth host app feels the same as the first. So the day went into collapsing a fiddly multi-command setup into php artisan mcp-kit:install, and turning "enable OAuth" from a service-provider editing session into a single env flag. Here's how it's wired, and the design calls behind it.

Repo if you want to read along: https://github.com/cleaniquecoders/laravel-mcp-kit

The problem: setup that drifts

The kit ships a ready-to-use "tasks" MCP server with two transports — a local STDIO one for php artisan mcp:start, and an HTTP one for remote connectors. The HTTP transport can authenticate two ways: token-only via Sanctum (the default), or the full OAuth 2.1 authorization-code + PKCE flow for header-less connectors like claude.ai.

Before today, standing that up meant a sequence every host had to get right by hand: publish config, publish migrations, publish a consent view, install Passport, generate keys, register the api guard, point Passport at the consent view, load Passport's migrations. Miss one and you get a runtime error three steps later. That's exactly the kind of tribal setup that drifts between projects — and the kit's whole pitch is "same every time."

One command instead of a checklist

The fix is an invokable-style install command that wraps the whole dance. The signature carries the optional pieces as flags, so a token-only install and a full OAuth install are the same command with different switches:

protected $signature = 'mcp-kit:install
    {--oauth : Also stand up the OAuth 2.1 (Passport) transport}
    {--ui : Also publish the Livewire + Flux token-management UI}
    {--force : Overwrite any files that were already published}';

public function handle(): int
{
    $this->components->info('Installing the Laravel MCP Kit');

    $this->publish('mcp-kit-config', 'config');
    $this->publish('mcp-kit-migrations', 'migration');

    if ($this->option('oauth') && ! $this->installOAuth()) {
        return self::FAILURE;
    }

    if ($this->option('ui')) {
        $this->installUi();
    }

    $this->nextSteps();

    return self::SUCCESS;
}

Two design choices worth calling out.

First, everything is idempotent, and --force is the only way to overwrite. Re-running the command on a half-set-up app is safe — it republishes what's missing and leaves the rest. That matters because install commands get re-run constantly during development, and a command that's destructive on the second run is a footgun.

Second, the command fails loudly when a precondition is missing instead of limping forward. The --oauth branch checks Passport is actually installed before touching anything, and bails with instructions rather than producing a half-wired OAuth setup:

protected function installOAuth(): bool
{
    if (! class_exists(Passport::class)) {
        $this->components->warn('Laravel Passport is not installed — the OAuth transport needs it.');
        $this->components->bulletList([
            'Install it:  composer require laravel/passport',
            'Then re-run: php artisan mcp-kit:install --oauth',
        ]);

        return false;
    }

    $this->publish('mcp-kit-views', 'consent view');

    // passport:keys is only available once Passport's provider is registered.
    if ($this->getApplication()->has('passport:keys')) {
        $this->components->task('Generating Passport encryption keys', function () {
            $this->callSilently('passport:keys', array_filter([
                '--force' => $this->option('force') ?: null,
            ]));

            return true;
        });
    } else {
        $this->components->warn('Skipped passport:keys — run it once Passport is fully registered.');
    }

    return true;
}

Notice the command only does the one-time, imperative steps — publish files, generate keys. It deliberately does not edit the host's service providers or config to make OAuth work at runtime. That part belongs somewhere idempotent-by-nature: the package's own service provider.

One-flag OAuth: let the provider do the wiring

This is the half I'm happiest with. The goal was: set MCP_KIT_WEB_OAUTH_ENABLED=true, run migrate, generate keys — and OAuth just works. No host service-provider edits at all.

The trick is that the package's service provider does the runtime wiring itself, guarded so it never stomps on a real app's config. Passport 13 stopped auto-loading its oauth_* migrations and ships no consent view, so the provider fills both gaps — but both are opt-out via config, so a host that wants its own branded consent screen or its own migration strategy just overrides them:

protected function configureOAuth(): void
{
    // ... only runs when OAuth is enabled AND Passport is installed ...

    // Consent screen for the auth-code flow. Passport 13 ships none, so wire
    // our publishable stub unless the host opted out or pointed at their own.
    $view = config('mcp-kit.web.oauth.authorization_view', 'mcp-kit::authorize');

    if ($view !== false && $view !== null) {
        Passport::authorizationView($view);
    }

    // Passport 13 no longer auto-loads its oauth_* migrations. Register them
    // so a plain `migrate` creates the tables — saving the host a
    // `vendor:publish --tag=passport-migrations` step.
    if (config('mcp-kit.web.oauth.load_migrations', true)) {
        $passportMigrations = dirname((new ReflectionClass(Passport::class))->getFileName(), 2)
            .'/database/migrations';

        if (is_dir($passportMigrations)) {
            $this->loadMigrationsFrom($passportMigrations);
        }
    }
}

The principle here is the one I keep coming back to with packages: the host app's config always wins. The api guard is only registered if the host hasn't defined one. The consent view binding is skipped if config says false. Migration loading is opt-out. A package that quietly overrides your config/auth.php is a package you'll rip out the first time it surprises you — so every piece of auto-wiring here has an escape hatch, and the escape hatch is plain config, not a subclass.

Locating Passport's migrations by reflecting on the class file rather than hardcoding vendor/laravel/passport/... is a small thing, but it survives Composer installing the dependency somewhere unexpected (a merged vendor dir, a path repo during local dev). Resolve from the class, not from an assumed path.

Prove the whole flow end to end

A setup this convenient is only trustworthy if there's a test that drives the actual OAuth flow — not just "the config key exists." So the headline test walks the entire authorization-code + PKCE path the way claude.ai would: dynamic client registration, the consent screen, approval, code-for-token exchange, then a real authenticated MCP call with the issued token.

it('issues a token through the consent flow that authenticates the MCP endpoint', function () {
    $user = User::create(['email' => 'imran@example.test', 'grants' => ['view', 'manage']]);

    // 1. The connector self-registers (DCR) — a public client, so PKCE, no secret.
    $clientId = $this->postJson('/oauth/register', [
        'client_name' => 'Claude',
        'redirect_uris' => ['https://claude.ai/api/mcp/auth_callback'],
    ])->assertCreated()->json('client_id');

    // 2. PKCE pair.
    $verifier = str_repeat('mcp-kit-pkce-verifier-0123456789', 2); // 64 chars
    $challenge = rtrim(strtr(base64_encode(hash('sha256', $verifier, true)), '+/', '-_'), '=');

    // 3. The signed-in user sees the kit's consent screen (auto-wired, no host edit).
    $this->actingAs($user)
        ->get('/oauth/authorize?'.http_build_query([
            'client_id' => $clientId,
            'redirect_uri' => 'https://claude.ai/api/mcp/auth_callback',
            'response_type' => 'code',
            'scope' => 'mcp:use',
            'state' => 'opaque-state',
            'code_challenge' => $challenge,
            'code_challenge_method' => 'S256',
        ]))
        ->assertOk()
        ->assertSee('Authorization Request');

    // 4. Approve → redirect back with the authorization code.
    $location = $this->post('/oauth/authorize', ['auth_token' => session('authToken')])
        ->assertRedirect()->headers->get('Location');

    parse_str(parse_url($location, PHP_URL_QUERY), $callback);

    // 5. Exchange the code for a token (PKCE verifier, no secret).
    $accessToken = $this->post('/oauth/token', [
        'grant_type' => 'authorization_code',
        'client_id' => $clientId,
        'redirect_uri' => 'https://claude.ai/api/mcp/auth_callback',
        'code_verifier' => $verifier,
        'code' => $callback['code'],
    ])->assertOk()->json('access_token');

    // 6. The Passport token authenticates the MCP endpoint.
    $this->withHeader('Authorization', "Bearer {$accessToken}")
        ->postJson(route('mcp-kit.tasks'), ['jsonrpc' => '2.0', 'id' => 1, 'method' => 'ping'])
        ->assertOk();
});

There's a companion test for the cancel path — the user declines, and Passport redirects back with access_denied and no code. The denial path is where auth bugs hide; a flow that only tests the happy path will happily hand out tokens to someone who clicked "No."

Two testbench details that saved me time. The browser flow posts without a CSRF token, so the test disables VerifyCsrfToken — we're exercising OAuth issuance, not Laravel's CSRF guard. And the test case forces the array cache driver so token issuance doesn't need a cache table to exist in the test DB. Small frictions, but they're the difference between "the suite runs anywhere" and "works on my machine."

What this unlocks

The payoff showed up immediately in another project: the provisioning tool that scaffolds new Laravel apps now just adds the kit to its package list and runs php artisan mcp-kit:install --no-interaction as one more bootstrap step. Every freshly provisioned app gets a working MCP server with zero bespoke setup. That's the whole point of collapsing setup into one command — it stops being a thing a human has to remember and becomes a line in a script.

The one piece the host still owns is authorization: the kit ships no permission system, it just requires two gates (mcp-kit.view-tasks, mcp-kit.manage-tasks) to be defined. That's deliberate — the kit shouldn't guess how your app does permissions. Map those two abilities to whatever your app already uses (a policy, a gate, a permission package) and you're done.

Next up: documenting the OAuth path properly in the new docs/ tree, and probably a --ui walkthrough for the token-management screens. But the foundation I wanted for 1.0.0 is there: install in one command, enable OAuth with one flag, and a test that proves the whole handshake actually works.