Search by

qiick / laravel-mcp-oauth

LucaGiardi20

OAuth authorization server for laravel/mcp endpoints in qiick Laravel products.

Package info

github.com/qiick-io/laravel-mcp-oauth

pkg:composer/qiick/laravel-mcp-oauth

Statistics

Installs: 488

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 11

v1.0.0-beta.2 2026-11-29 08:37 UTC

This package is auto-updated.

Last update: 2026-12-04 17:39:52 UTC


README

laravel-mcp-oauth: OAuth for laravel/mcp endpoints

qiick/laravel-mcp-oauth

OpenSSF Scorecard

PHPStan at max and the existing CI checks cover PHP. CodeQL covers GitHub Actions and JavaScript/TypeScript.

In development. Not released and not on Packagist yet: do not depend on it.

OAuth authorization server for laravel/mcp endpoints in qiick Laravel products. Consent plumbing, governed dynamic client registration, redirect URI rules, refresh-token family revocation, RFC 6750 errors, fail-closed Passport keys, and the /mcp Bearer authentication — built on Passport and laravel/mcp.

Part of the qiick fleet. Binding design: projects/qiick/packages/laravel-mcp-oauth-design.md in the knowledge base (answers: decisions/2026-11-22-mcp-oauth-and-access-design-answers.md).

Status

This guide targets 1.0.0-beta.2. The public API and migrations may still change during the beta. Pin an exact version and check UPGRADING.md before updating. Stable 1.0.0 requires an adopter besides externa and the maintainer's approval.

Requirements

  • PHP ^8.4 with ext-intl and ext-openssl
  • illuminate/console, contracts, database, http, routing, support ^12.41.1 \|\| ^13.0 (never laravel/framework)
  • laravel/passport ^13.12, laravel/mcp ^1.2, league/uri ^7.8
  • qiick/laravel-outbound ^0.2.0-beta.4 || ^1.0 for this beta
  • OAuth grant binding requires the host product to install Laravel Access with the resource grant and ceiling schema and migrate it before the OAuth binding table.
  • Optional: inertiajs/inertia-laravel ^3.0 (default ConsentViewContract)

Install

composer require qiick/laravel-mcp-oauth:1.0.0-beta.2 'qiick/laravel-outbound:@beta'
php artisan vendor:publish --tag=mcp-oauth-config
php artisan vendor:publish --tag=passport-migrations
php artisan vendor:publish --tag=mcp-oauth-migrations
php artisan vendor:publish --tag=mcp-oauth-binding-stub
php artisan passport:keys

The Outbound argument allows a compatible beta while keeping the project's minimum stability. If your project already allows a compatible Outbound version, keep its constraint and omit that argument. See Composer stability flags.

The service provider is auto-discovered. Products implement the contracts (AdminSwitchContract, GrantStoreContract, ConsentProviderContract, …), call McpOAuthRoutes::register() from their MCP routes file, and keep OAuth off until keys exist and the admin switch is flipped.

McpOAuthRoutes::register() serves DCR, authorize, token, revocation (RFC 7009) and the RFC 8414 / RFC 9728 discovery documents. Do not also call Mcp::oauthRoutes(): its documents are built from the request Host and sit outside the off-gate, and its oauth/register would replace the package's. With OAuth on, boot (or, with route:cache, the first request) fails while any of its routes is mounted, and mcp-oauth:check lists them.

Browser-based MCP clients (the MCP inspector, for example) call these endpoints cross-origin. The package sets no CORS headers itself: add the paths to the product's config/cors.php, where Laravel's HandleCors answers the preflight before routing:

'paths' => ['api/*', '.well-known/*', 'oauth/register', 'oauth/token', 'oauth/revoke', 'mcp'],

mcp is the MCP endpoint itself (mcp-oauth.mcp_path): a browser client calls it cross-origin with the token it got.

Mount the package's Bearer authentication and challenge on the product's /mcp route. It replaces the product's own /mcp authentication middleware and sits before its throttle; the challenge replaces laravel/mcp's AddWwwAuthenticateHeader, which would overwrite the RFC 6750 error code:

Mcp::web('/mcp', ProductServer::class)
    ->withoutMiddleware(AddWwwAuthenticateHeader::class)
    ->middleware([McpChallengeMiddleware::class, McpBearerAuthenticationMiddleware::class, 'throttle:mcp']);

The Bearer authentication takes an API key through the product's ApiKeyAuthenticatorContract and an OAuth access token through AccessTokenAuthenticator (audience, client, blocked hosts, bound grant, mcp:use, then the product's GrantAuthorizerContract, on every call), binds either through McpCredentialBinderContract, and answers 429 to an address that failed mcp_auth_failures_per_minute times. With OAuth off it behaves as before the package: every Bearer is an API key, and a 401 says Bearer realm="mcp", error="invalid_token". With OAuth on, every 401 and 403 points at the protected resource metadata built from APP_URL.

The product's settings page switches OAuth on and off through SwitchMcpOAuthAction, which refuses to switch on (with a reason to show) while OAuth could not serve, and dispatches McpOAuthEnabledEvent or McpOAuthDisabledEvent. The product keeps its own store behind AdminSwitchContract, and every write to that store must go through the action (behind the product's admin permission and CSRF), or the rule can be bypassed:

try {
    $switchMcpOAuth->execute($request->boolean('enabled'), $request->user(), fn (bool $isEnabled) => $settings->setMcpOAuth($isEnabled));
} catch (McpOAuthCannotBeEnabledException $exception) {
    return back()->withErrors(['enabled' => $exception->getMessage()]);
}

Mount the admin backend for MCP clients and blocked hosts inside the product's own admin group, naming the permission middleware every route needs. The routes stay up while OAuth is off, so an admin can still clean up:

Route::middleware(['web', 'auth'])->prefix('admin')->group(
    fn () => McpOAuthAdminRoutes::register('permission:can-manage-mcp-clients'),
);
Route Does
GET mcp-oauth-clients JSON: the package's clients (50 a page) and the blocked hosts
POST mcp-oauth-clients/{client}/block revokes the client, its grants, tokens and codes
POST mcp-oauth-clients/bulk-block the same for 1 to 100 distinct client UUIDs
POST mcp-oauth-clients/prune-unused runs the unused-client prune now; JSON prunedClientCount
POST mcp-oauth-clients/blocked-hosts blocks a host (match_mode exact or, by default, with its subdomains) and every client that redirects there; a host already blocked keeps its first mode and reason
DELETE mcp-oauth-clients/blocked-hosts/{id} lifts a block; blocked clients stay revoked

Writes answer 204 to a JSON call (the prune 200, with prunedClientCount) and redirect back for a form or Inertia post. Only clients the package registered are listed or blocked, never the product's own Passport clients.

Mount Connected apps, where a signed-in user lists the MCP clients they authorised and revokes one, inside the product's authenticated group. Like the admin routes, they stay up while OAuth is off:

Route::middleware(['web', 'auth'])->group(fn () => McpOAuthSettingsRoutes::register());

GET settings/connected-apps answers JSON (connectedApps: grant id, client, scopes, display, dates); DELETE settings/connected-apps/{grant} revokes the grant and every token bound to it, answering 204 to a JSON call and redirecting back otherwise. A grant that is not the user's own active one is a 404.

The package schedules its retention jobs itself while mcp-oauth.enabled is on, on one server and never overlapping. On more than one server, the single-server lock needs a cache store every server shares (database, Redis, Memcached, DynamoDB); with a local store each server runs the jobs.

  • mcp-oauth:prune-revoked deletes the clients the package registered and revoked more than revoked_retention_days (90) ago, reading them 100 at a time and deleting each with its tokens and codes; the consent records whose own retention_until has passed, 100 at a time, each delete checking the deadline again; and the product's grants through GrantStoreContract::purgeRevokedBefore(), which batches as the product chooses and may keep rows under a legal hold.
  • mcp-oauth:prune-unused-clients deletes the DCR clients nobody authorised within unused_client_retention_hours (24), reading 100 at a time and deleting one client at a time. It also deletes the metadata rows of Passport clients deleted outside the package: there is no foreign key to oauth_clients, because Laravel re-dates a published Passport migration so it runs after this package's, and this cleanup is the cascade instead. That cleanup never deletes an oauth_clients row: it deletes the metadata only while oauth_clients has no row with that id (checked in the same statement), then every Passport code and access token whose client row is gone, registered or not, then every refresh token whose access token is gone. It reads Passport's tables past any global scope on their models and deletes by subquery, whatever the number of rows.
  • mcp-oauth:prune-auth-code-exchanges walks the exchange rows one at a time.

Every command takes --dry-run. mcp-oauth:check reports whether OAuth is on and ready and exits 1 when it is on but not ready. The schedule the package registers:

Schedule::command('mcp-oauth:prune-unused-clients')->hourly()->onOneServer()->withoutOverlapping();
Schedule::command('mcp-oauth:prune-revoked')->daily()->onOneServer()->withoutOverlapping();
Schedule::command('mcp-oauth:prune-auth-code-exchanges')->daily()->onOneServer()->withoutOverlapping();

To schedule them differently, set MCP_OAUTH_RETENTION_SCHEDULE=false (then php artisan config:cache if you cache config) and add your own lines; a value that is not a boolean stops the boot.

Personal data erasure

Resolve Qiick\McpOAuth\Erasure\McpOAuthEraser from the container and call erase($userId, $userPublicId, $mode, $publicIds, $identifiers) from the product's erasure orchestrator after it locks out the person and revokes their product-owned grants. Run this before deleting the user so credential rows and replay records can still be found. Pass McpOAuthEraser::DELETE or McpOAuthEraser::ANONYMISE for $mode.

Both modes remove the person's code exchanges and all of their Passport auth codes, access tokens and refresh tokens of existing clients, one statement per table, registered by the package or not (a client whose oauth_client_metadata row was lost looks exactly like the product's own). They unlink the author of each affected redirect-host block and erase its notes while keeping the block active. Consent decisions remain as evidence with identifying fields scrubbed until retention_until.

A Passport user key names a person only within one Laravel user provider: mcp-oauth.subject_provider (MCP_OAUTH_SUBJECT_PROVIDER), or when it is null auth.guards.api.provider, the provider Passport gives a client without one. Export and erasure do not guess: they throw AmbiguousSubjectAttributionException before touching anything when no subject provider is configured, when a Passport client serves another provider (names are compared byte for byte, whatever the column collation), or when a client without a provider exists and more than one user provider is configured. mcp-oauth:check reports the same problems with their fix. Every subject query also requires the client's provider itself, read on the primary in the same transaction as the check, so a client added meanwhile cannot slip in.

Operator contract: no Passport row records which provider a providerless client's tokens were issued under. Before changing the user provider that providerless clients serve (renaming the api guard's provider, or replacing one provider with another), revoke or prune their existing Passport tokens and codes: export and erasure would otherwise attribute them to the new provider's people. Restoring a deleted Passport client under its old id is not supported either: the prune may already be deleting its credentials.

A credential whose client row is gone names no provider, so export and erasure attribute it to no one. mcp-oauth:prune-unused-clients deletes every such code and access token, registered or not; run it before an erasure if those must be gone too. A refresh token whose access token is gone, as Passport's passport:purge leaves one (it deletes expired access tokens first), holds no user key either: erasure deletes all such rows as housekeeping and reports them as the detached:<table> store, the export cannot include them, and the prune deletes them too.

An open consent record starts its configured retention period at erasure. The scheduled mcp-oauth:prune-revoked job still removes expired evidence.

The package requires its erasure stores to share a database connection so all writes can roll back together. Supply organisationId to erase that person's verified grant bindings, consent and code snapshots, and associated Passport credentials in one tenant. Unscoped Passport credentials, detached refresh tokens and the instance-wide blocklist are outside a scoped run. Use dryRun: true to preview the counts. A real run dispatches Qiick\McpOAuth\Events\SubjectErasedEvent after commit with the counts-only ErasureReport. The product owns the user row, grants and sessions.

Personal data export

Resolve Qiick\McpOAuth\Export\McpOAuthExporter from the container and call export($userId, $userPublicId, $publicIds, $organisationId) from the product's export orchestrator (GDPR Art. 15 and 20, fleet F37). It reads exactly the rows the eraser would change, writes nothing, and returns one entry per store:

['oauth_consent_records' => ['basis' => 'observed', 'rows' => [[...], ...]], ...]

Every store has basis observed: consent rows mix the person's decision with the observed IP address, user agent and request id, so none is wholly provided (the fleet's conservative floor), and the other stores are observed. Records about the person are exported in full; a host block the person only authored is a reference (public_id, action, created_at), without the host or its notes. Rows hold scalars only: JSON columns as their JSON text, instants as RFC 3339 UTC. Every Passport credential of the person of an existing client is exported; client_registered is false where the client has no metadata row. Credential ids (code, token and refresh token ids), internal user keys and the grant binding column are left out. On MySQL and MariaDB a Passport user key is matched after converting the column to utf8mb4 and comparing it byte for byte, so the database connection must use utf8mb4 (Laravel's default). Pass the person's matching internal and public user keys and only grant UUIDs you verified as theirs: a row that names another owner is never exported for a grant id, but an unlinked row is. Like the eraser it refuses an organisationId.

Keys, digests and rotation

  • Client identifier digests. metadata_document_url_digest carries its format (sha256:<hex>). It is a lookup key, not a secret: no key or pepper is involved and nothing needs rotating. Rows in a format the package does not know are never matched.
  • Passport token encryption. Authorization codes and refresh tokens are encrypted by League with Passport's single token encryption key (Passport::tokenEncryptionKey(), the raw APP_KEY by default). APP_PREVIOUS_KEYS does not reach them: rotating APP_KEY invalidates every outstanding code and refresh token, so clients sign in again. Keep the token encryption key stable across an app-key rotation, or accept that re-authorisation.
  • Client secrets. Clients registered by the package are public and have none. A confidential client the product provisions has a Passport secret hashed by Laravel's hasher (bcrypt or Argon2, with the algorithm in the stored string); mcp-oauth's revocation endpoint verifies it with the same hasher. Changing the hashing driver needs a rehash plan or new secrets.
  • Passport signing keys. Rotating them invalidates issued access tokens; see the README of laravel/passport.

Threat model (short)

Threat Mitigation
Public DCR flood / phishing Off by default (three gates); per-key and global caps; prune; admin block
Hostile redirect hosts League URI only; ASCII hosts; UTS #46; exact/subdomain block
Host-header discovery poisoning Issuer and resource from APP_URL only
Refresh-token theft / races Atomic rotation; family + grant revocation; live binding required
Code replay One-shot codes; a replay revokes the grant and every token issued with it
A token used after revocation /mcp re-checks token, audience, client, blocked hosts and bound grant on every call; nothing cached
Credential guessing at /mcp Per-address failure brake (429 before the credential is read). Clients behind one shared address (carrier NAT, a corporate egress) share the counter: raise mcp_auth_failures_per_minute or throttle sharper at the edge
Missing Passport keys 503 temporarily_unavailable; switch refuses to turn on

Full table: design §16.

Public API (contracts and data)

Products implement Qiick\McpOAuth\Contracts\* (AdminSwitchContract, GrantStoreContract, ConsentProviderContract, GrantCeilingContract, GrantAuthorizerContract, ApiKeyAuthenticatorContract, McpCredentialBinderContract, AuditLoggerContract, ConsentViewContract, OAuthUserResolverContract). Wire and consent shapes are the @api DTOs under Qiick\McpOAuth\Data and events under Qiick\McpOAuth\Events. Package records use UUIDs. CIMD clients use their document URL as the OAuth wire identifier.

Additional protected resources

Register each product resource with McpOAuthServer::registerResource() before registering the OAuth routes or resolving Passport's authorization server. A definition pairs a canonical URL under APP_URL with one wire scope unique to the audience and a list of server-assigned client classes. Each resource has its own RFC 9728 metadata document under /.well-known/oauth-protected-resource/. The existing /mcp configuration works without a definition.

An authorization request may repeat resource to ask for several audiences. The user sees each audience at consent. The product's GrantStoreContract copies ConsentDecisionData::resourceScopes to the grant and returns the same immutable pairs in GrantRecordData::resourceScopes on reads. POST /oauth/token takes exactly one resource on both the code exchange and refresh. A grant may refresh into another approved audience. Rotation retires the selected audience's previous access token, and reuse still revokes the whole family.

For an additional endpoint, pass its exact registered identifier and the server-selected operation to AccessTokenAuthenticator::authenticate(). It verifies the audience, wire scope and current client ownership before passing the operation to the product's GrantAuthorizerContract. The authorizer applies the live Access perimeter for that operation.

Config

Publishable config/mcp-oauth.php (tag mcp-oauth-config). Env prefix MCP_OAUTH_*. Dynamic clients use the redirect policy from laravel/mcp’s mcp.redirect_domains and mcp.custom_schemes. Issuer is always APP_URL.

Client ID Metadata Documents

Set MCP_OAUTH_CIMD_ENABLED=true to accept public HTTPS client_id URLs at authorize, token and revocation. The discovery flag is omitted by default. The document's client_id must match the URL byte for byte. The URL needs a non-root path without dot segments. The package resolves it to a Passport UUID internally and requires an exact registered callback for CIMD authorization and code exchange. Only public clients using authorization code with PKCE are supported. A document may omit its authentication method or declare none.

CIMD uses an isolated Outbound transport with HTTPS, pinned public DNS answers, no redirects, and the timeout and byte ceilings in cimd.*. Document freshness is bounded by cache_min_seconds and cache_max_seconds. max-age=0, no-cache and no-store all use the minimum interval before the next fetch. no-store retains only the validated fields needed for the client registration. It keeps neither the cached document nor its ETag. A 304 renews a previously validated entry. Fetch failures are remembered for the minimum interval using a status under the URL's digest in the application's cache. Use a shared cache for multiple servers to apply the same limit across them.

An unavailable client document returns 503 and preserves the last good entry. It cannot be used for an authorization or token request until revalidated. Invalid documents return invalid_client locally. Terminal failures and changes to callbacks or grant types revoke the client's issued credentials.

Applications using Outbound solely for CIMD can add qiick/laravel-outbound to their own Composer extra.laravel.dont-discover list to omit its webhook provider, migrations and scheduled jobs. The CIMD transport uses the library factory directly.

Pre-registered Companion clients

The product or Companion service provider supplies the shipped identity during boot. Pass the claimed HTTPS callback URLs from the mobile build to McpOAuthServer::registerCompanionClient().

use Qiick\McpOAuth\Data\CompanionClientDefinitionData;
use Qiick\McpOAuth\McpOAuthServer;

app(McpOAuthServer::class)->registerCompanionClient(new CompanionClientDefinitionData(
    identifier: 'https://companion.qiick.io/oauth/client-metadata.json',
    name: 'qiick Companion',
    redirectUris: ['https://companion.qiick.io/oauth/callback'],
    operatorName: 'qiick',
));

Bind an InstallationGrantStoreContract and set MCP_OAUTH_COMPANION_ENABLED=true to enable the client. The reservation holds regardless of this setting or the live CIMD switch. The definition validates the identifier and HTTPS callback list when constructed. The shipped list authorizes exact callbacks for this identity, subject to the instance's host blocklist. Run mcp-oauth:check to check the enabled definition before deploy. The consent page identifies the operator. The authorization server advertises RFC 9207 support and every redirect with an authorization result includes the issuer as iss.

Testing

node tests/Erasure/run.mjs
composer test
composer lint
composer analyse
node --test scripts/mutation-inventory.test.mjs
bash scripts/mutate-per-class.sh   # per-source mutation score ≥ 95
node --test scripts/mutation-declarations.test.mjs
php scripts/mutate-declarations.php

docs/security-checklist.md maps every design scenario (S1–S81) to the tests that prove it, and lists what is still open.

The mutation gate derives its targets from src/, including erasure and the shipped test fakes. Pest enforces 95% per source path with executable mutants. PHP declaration initializers with a reasoned directive are linted and mutated in an isolated copy. The contract tests must detect every one. The required CI aggregate includes both runs. See the declaration mutation decision. Release-preparation changes to the changelog run the full gate on the PR head.

CI runs the PHP 8.3/8.4/8.5 × Laravel 12/13 × lowest/stable matrix, Pint, PHPStan max, Pest, Composer validation and audit, real HTTP tests, and qiick standards drift against app-ui v0.15.0. The fleet erasure suite runs on SQLite, PostgreSQL, MySQL and MariaDB.

License

MIT