esoul-cz / laravel-ai-connector
The OAuth 2.1 and MCP protocol layer of the eSoul AI connector for Laravel: discovery, client registration (CIMD and DCR), token binding to the MCP resource, scopes and the ai-connector guard, on laravel/mcp and Passport.
Requires
- php: ^8.4
- laravel/framework: ^12.41 || ^13.0
- laravel/mcp: ^1.3
- laravel/passport: ^13.12
Requires (Dev)
- esoul-cz/coding-standard: ^0.1
- larastan/larastan: ^3.0
- orchestra/testbench: ^10.0 || ^11.0
- phpstan/extension-installer: ^1
- phpstan/phpstan: ^2
- phpstan/phpstan-deprecation-rules: ^2
- phpstan/phpstan-phpunit: ^2
- phpstan/phpstan-strict-rules: ^2
- phpunit/phpunit: ^12.0 || ^13.0
Suggests
None
Provides
None
Conflicts
None
Replaces
None
README
Lets a client connect their own Claude or ChatGPT to an eSoul Laravel application as a custom connector (a remote MCP server with OAuth 2.1). The assistant reads the application's content and proposes changes; a person accepts them, and publishing stays a human action. The decision is ADR-0004 of esoul-infrastructure; how this repository is split is ADR-0001.
Status: package released (latest 0.1.1, ADR-0001 Decision 5); not yet tried live with Claude or ChatGPT, which gates 0.2.0. Declared variants: laravel-cms, laravel-filament, laravel-inertia-filament, laravel-inertia, laravel-lunar and astro-cms. The addon's cms layer (the content tools of laravel-cms: list and read pages, block types, drafts, proposed revisions, restore) builds on the revisions, drafts and block catalogue of the laravel/cms template layer (app-templates#10).
What this repository is
| Role | Name | Files |
|---|---|---|
Composer package: the OAuth and MCP protocol layer (discovery, CIMD, token binding, iss, scopes, the ai-connector guard) |
esoul-cz/laravel-ai-connector |
composer.json, src/, config/, database/, routes/, tests/ |
| Template addon: everything a project owns (consent and connections pages, audit, switches, rate limits, the base tool, the tools, the client guide) | ai-connector |
addon.json, layers/ |
| Guideline source: the rules for connector code | ai-connector (layer ai-connector:laravel) |
guidelines/ |
The addon declares laravel-cms, laravel-filament, laravel-inertia-filament, laravel-inertia, laravel-lunar and astro-cms (the nginx
locations of a CMS site). Its layers, per variant:
| Variant | Layers | The connections page, "Connected assistants" | Sign-in the assistants' people are sent to (AI_CONNECTOR_LOGIN_ROUTE) |
|---|---|---|---|
laravel-filament, laravel-inertia-filament |
core, users, filament-page, filament |
A Filament page of the admin panel | filament.admin.auth.login |
laravel-cms |
core, users, filament-page, filament, cms |
The same, and the content tools | filament.admin.auth.login |
laravel-inertia |
core, users, inertia |
A Vue page (/connected-assistants) with an entry in the account menu, for who may use the connector (admins by default) |
login (the sign-in of laravel/auth-inertia) |
laravel-lunar |
core, filament-page, lunar, lunar-catalogue |
The same Filament page, in Lunar's panel (/admin/connected-assistants); the principals are the Lunar staff (guard staff, administrators by the admin flag), never the customers, who get no tokens; and the catalogue tools, with the page "Pending changes" (/admin/catalogue-pending-changes) for staff with catalog:manage-products |
filament.lunar.auth.login |
astro-cms |
nginx |
none (the backend is the laravel-cms project) |
none |
lunar-catalogueis the catalogue of a Lunar shop for the assistant: read tools (products, collections, product types with the tax classes, languages, pending changes) and propose tools (the texts of a product per language, its collections, a new product as an invisible draft that names its product type and tax class). A change of an existing product is a pending change (one open per product, with the value the assistant saw) that staff with Lunar'scatalog:manage-productsapply or discard on a page of the Lunar panel, and an entry whose live value changed since the proposal is refused. No tool sets a price, a stock level, an image or the status. The Lunar models are resolved through Lunar'sModelManifest, so a project's replacement classes are used. See the developer note.usersis the customerUseras the principal (Passport's traits onUser, theis_adminpolicy, the tests for it);laravel-lunarleaves it out.filament-pageis the Filament page, shared by the admin panel (filament) and Lunar's panel (lunar).coreis every Laravel variant's base: the consent page (a Blade page, so a variant without an admin panel needs none), the audit, the switches, the rate limits, the base tool and the MCP server. Its config has no login route: a layer setsAI_CONNECTOR_LOGIN_ROUTEin.env.example, and a deployment must set it too. Without it, and withoutai-connector.login_url, a signed-out person at the authorize step gets401 login_requiredand cannot connect; with onlylogin_urlthey are sent to that URL (ADR-0004 Decision 13: neverroute('login')by default).filamentis the Filament page,inertiathe Inertia page. Both do the same through the same commands and query ofcore: a person lists and disconnects their own assistants; an admin sees everybody's, disconnects an assistant for every user, blocks a user from a connection row, unblocks any blocked user (also one with no connection left) and switches the whole connector off and on. The Inertia page also blocks a user who has not connected yet.inertianeeds the sign-in oflaravel-inertia(users.is_admin, theloginroute, the account menu with the slotuser-menu) and takes the slotsroutesanduser-menu. Its provider is registered bycore's, because an addon may insert one block per slot andprovidersiscore's.
Who the principal is
An assistant acts as a principal: any authenticatable the guard ai-connector resolves, not only App\Infrastructure\Models\User. core types every actor as Illuminate\Contracts\Auth\Authenticatable and asks one contract, App\Application\Contract\AiConnector\ConnectorPrincipalPolicy, for what depends on the kind of principal: may it connect and keep using the connector (asked at the consent step and on every call), does it administer the connections, its display name, and how to find principals by id or email. Blocks (ai_connector_user_blocks) and the audit log (ai_connector_tool_calls) are keyed by auth provider and id (user_provider, user_id, no foreign key), and every query and command works on the configured provider only, so a customer and a staff member with the same id never meet.
| Setting (environment) | Default | Meaning |
|---|---|---|
ai-connector.principal_policy (AI_CONNECTOR_PRINCIPAL_POLICY) |
none: App\Infrastructure\AiConnector\UserPrincipalPolicy |
The class that implements the contract. The default is today's behaviour: administrators of users (users.is_admin) may connect and administer, the name is users.name |
ai-connector.web_guard (AI_CONNECTOR_WEB_GUARD) |
the default guard | The session guard of the people who approve a connection |
ai-connector.user_provider (AI_CONNECTOR_USER_PROVIDER) |
the provider of the web guard | The auth provider of the principals: it finds the user of a token, and keys blocks and audit rows |
A layer that has other principals (lunar, for the staff of Lunar) substitutes the policy without a slot of core: it brings its own policy class (as a file) and appends the three lines above to .env.example, like the login route. The default users policy is in the layer users, which also inserts Passport's HasApiTokens and OAuthenticatable into the customer User (slots user-traits and user-interfaces); core needs User to have none of it, so laravel-lunar leaves users out and its principal model (Staff, which uses HasApiTokens and implements OAuthenticatable) is named in allowed-models.json for the architecture rule of the tools. A layer's own service provider is registered by core from its list of layer providers (inertia, lunar), so no second layer inserts into the slot providers.
Taking the connector into a project
From a checkout of eSoul-cz/app-templates, on a project that is caught up with its template:
bin/templates addon:apply git@github.com:eSoul-cz/laravel-ai-connector.git <project-dir>
The command adds the addon's files, requires the package, adds the guideline source and prints the manual steps
(Passport keys as a deploy secret, migrations, the client's written decision to turn the connector on). A CMS site takes
the addon in its laravel-cms backend and in its astro-cms root. The esoul-project-update skill keeps it current.
The package
esoul-cz/laravel-ai-connector is the protocol and token layer of ADR-0004, and nothing else: no page, no tool, no audit log, and it imports no class of the application. It requires laravel/mcp and laravel/passport (PHP 8.4 or later, Laravel 12.41 or 13) and its service provider is auto-discovered. It runs an OAuth server of its own on Passport's keys and tables, so its lifetimes and rules do not touch the application's other Passport use.
| What | How it behaves |
|---|---|
| Discovery | /.well-known/oauth-protected-resource and /.well-known/oauth-authorization-server, each also with a path (RFC 9728 inserts the resource's path: /.well-known/oauth-protected-resource/mcp). The authorization server says client_id_metadata_document_supported, none as the only token authentication method, S256 as the only PKCE method, the scopes read, propose and offline_access, and authorization_response_iss_parameter_supported |
| Client registration | Client ID Metadata Documents: a client_id that is an https URL is fetched only from an allowlisted host (claude.ai, chatgpt.com), within a size limit and a timeout, without following a redirect to another host, and cached. A document that is refused is an unknown client; stored data stands in only while the host cannot be reached (an outage or a server error). A client the connector revoked stays revoked. Dynamic registration (POST /oauth/register) is the fallback: public clients only, every redirect URI on an allowlist (the two assistants; loopback addresses for desktop clients), throttled; ai-connector:prune-clients removes registrations that never got a token |
| Authorize and token | Authorization code with PKCE S256 only. resource, when sent, must equal the MCP URL (invalid_target otherwise) and the token is bound to it. iss is in every authorization response. Access tokens live 1 hour, refresh tokens 30 days from their last use and are replaced on every use: the rotation is an atomic conditional write, so one refresh token has one successor and a concurrent second use fails as invalid_grant. Tokens are issued under a row lock of the client, which the revocation of connections takes too. No implicit, password, client credentials or device grant. Revocation is checked on every request. passport:purge is scheduled |
The guard ai-connector |
Accepts a bearer token only if it was issued by this package for the MCP URL, to a client of this package, with at least the read scope, and is neither revoked nor expired, and was issued for the guard's user provider (see "User provider"). A token of the application's own Passport API is refused here, and a token of this package is refused by auth:api. The user carries a ConnectorAccessToken: AiConnector::accessToken($user)->level() is AccessLevel::Read or AccessLevel::Propose |
| The MCP endpoint | AiConnector::route(Server::class) registers it behind the switch (404 while off) and the guard, on every method of the URL (Mcp::web() also registers GET and DELETE, which answer 405). An unauthenticated request gets 401 JSON with WWW-Authenticate: Bearer realm="mcp", resource_metadata="...", scope="read propose" whatever its Accept header says, never a redirect. The package changes no global state of laravel/mcp, so other MCP servers of the application keep their own challenge |
| Sign-in and consent | A guest at /oauth/authorize goes to the configured login route and comes back; there is no default (never route('login')). The consent screen is not in the package: it renders the view the application names, with the data below. The decision comes back as POST (approve) or DELETE (cancel) to /oauth/authorize |
Manual install (a Laravel application that is not made from a template)
A template project takes the connector with bin/templates addon:apply and gets all of this ready-made. For any other Laravel application:
composer require esoul-cz/laravel-ai-connector, thenphp artisan vendor:publish --tag=ai-connector-config. (--tag=ai-connector-migrationspublishes the migrations; they also run from the package without publishing. They create Passport's four OAuth tables where they are missing (and remember which ones they created: a rollback drops only those, never the tables of an application that used Passport first) and addresource,user_provider,registration,metadata_urlandlast_used_at.)- Make the signing keys with
php artisan passport:keys, or setPASSPORT_PRIVATE_KEYandPASSPORT_PUBLIC_KEY. They are a deploy secret: never commit them, never share them between environments. php artisan migrate.- On the user model:
use Laravel\Passport\HasApiTokens;andimplements Laravel\Passport\Contracts\OAuthenticatable. The guardai-connectoris configured by the package (on the provider of the guard that approves connections,ai-connector.web_guard, or of the default guard when that is not set; see "User provider"); define it inconfig/auth.phpto change that. - Write the consent view and name it in
ai-connector.consent.view. It receives$clientName,$clientUrl(the URL of a metadata client, otherwisenull),$redirectHost,$redirectUri,$registration(cimdordcr),$user,$requestedLeveland$levels(ESoul\LaravelAiConnector\AccessLevelvalues: show the levels the person may choose from),$resource,$authToken,$approveUrland$denyUrl. The form postsauth_tokenandlevelto$approveUrl; "Cancel" is the same form sent asDELETEto$denyUrl. The level the person chooses is lowered to what the assistant asked for; no choice means read only. Never skip the screen. - Set
ai-connector.login_route(a route name) orai-connector.login_url, the sign-in of the people who approve connections; the package has no default, and without either the authorize step answers401 login_required.ai-connector.web_guardnames their session guard (default: the default guard). - Build your MCP server with
laravel/mcpand register it:AiConnector::route(YourServer::class)->middleware('throttle:your-limiter');in a routes file that a provider loads. Inside a tool,$request->user(AiConnector::GUARD)is the user andAiConnector::accessToken($user)->level()the level of the connection. - Decide who may connect and when the connector is on, in a provider:
AiConnector::authorizeUsing(fn (Authenticatable $user): bool => ...)(asked at authorize; ask the same thing in every tool call) andAiConnector::enabledUsing(fn (): bool => ...)(a runtime switch; the config keyai-connector.enabled,AI_CONNECTOR_ENABLED, is on top of it and is off by default). - Set
TRUSTED_PROXIESso that the URLs of the discovery documents arehttps://, and let/mcp,/oauth/and/.well-known/oauth-*reach the application at the host the assistants call. With a path (ai-connector.path,ai-connector.oauth_path) the RFC 9728 URL carries it. An application served under a prefix (APP_URL=https://host/backend) advertiseshttps://host/.well-known/oauth-protected-resource/backend/mcp: the well-known segment follows the host, and the prefix appears once, in the resource's path; let the proxy pass that URL to the application. - The package schedules
passport:purgeandai-connector:prune-clientsdaily (ai-connector.schedule).
Passport's own routes are switched off by default, so the application has no second OAuth surface. An application that serves Passport's routes for its own API sets ai-connector.keep_passport_routes and gives ai-connector.oauth_path another prefix; two servers on one prefix is refused at boot.
What the template addon adds on top, and that a manual install has to build itself if it wants it: the consent page, an audit log without arguments, the switches and revocation commands, the rate limits, the base tool that checks ability, level and effect on every call, the architecture test that keeps tools from writing or sending anything, and the connections page. The addon's layers are project code for the eSoul templates, which run Laravel 13; they use its model attributes (#[Fillable]), so they are not meant for a Laravel 12 application (the package alone is, see above).
To revoke connections from your own code, take the lock that tokens are issued under: AiConnector::withClientLock($clientIds, fn () => ...) runs the callback in a transaction on Passport's connection with the rows of those clients (null: all of them) locked. A refresh that is in flight then either finishes first, and the revocation sees its new tokens, or waits and finds its refresh token revoked.
Settings
config/ai-connector.php (published with the tag above; every key has a default in the package):
| Key | Default | Meaning |
|---|---|---|
enabled |
false (AI_CONNECTOR_ENABLED) |
Off: every route of the package and every route with ai-connector.enabled is 404 |
path, oauth_path, issuer |
mcp, oauth, the origin |
The MCP URL (the OAuth resource), the prefix of authorize, token and register, the authorization server identifier |
keep_passport_routes |
false |
Leave Passport's own routes on |
web_guard, login_route, login_url, consent.view |
none, none, none, ai-connector.consent |
Sign-in and consent |
user_provider |
provider of the web_guard (the default guard when that is null) |
Finds the user of a token, and the provider a token is issued for (AI_CONNECTOR_USER_PROVIDER; see "User provider") |
tokens.access_ttl_minutes, tokens.refresh_ttl_days, tokens.auth_code_ttl_minutes |
60, 30, 5 | Lifetimes of the package's own grant |
redirect_uris.allowed, redirect_uris.allow_loopback |
the two assistants, true |
Where a client may send the person back (* at the end is a prefix; a bare * never matches). Applied again whenever a client is loaded, so tightening it also stops clients stored under the old rule |
client_metadata.* |
claude.ai, chatgpt.com; 10 KiB; 5 s; 1 h |
Allowed hosts, size limit, timeout and cache of metadata documents |
registration.* |
on; 10 per minute; 30 days | Dynamic registration, its throttle and the pruning age |
throttle.authorize_per_minute, throttle.token_per_minute |
30, 60 | Per IP address |
require_resource |
false |
Refuse requests without the resource parameter (a missing one is bound to the MCP URL anyway) |
consent_ttl_minutes, schedule |
10, true |
How long a consent screen can be answered; schedule the daily commands |
User provider
A token holds only the user's id, so which table that id belongs to matters as soon as an application has two kinds of user (customers in users, staff in staff, both with an id 5). The package therefore keeps the provider with the token and never mixes them:
- The guard's provider is
ai-connector.user_provider, else the provider ofai-connector.web_guard(the default guard when that is null), elseusers; a guard the application defines itself inconfig/auth.phpkeeps its own provider. It is worked out when the guard is created and when a token is issued, not when the package registers, so a value that an application provider or the environment (AI_CONNECTOR_USER_PROVIDER,AI_CONNECTOR_WEB_GUARD) sets later still counts.AiConnector::userProvider()returns it. - Every access token records that provider (
oauth_access_tokens.user_provider, added by a migration of the package: runphp artisan migrateafter updating). The guard refuses a token whose provider is not its own, and a refresh token of another provider gives no new token (invalid_grant). A token that names no provider (null) is refused: the migration that adds the column gives the tokens already there the provider configured when it runs (AiConnector::userProvider()), so setAI_CONNECTOR_USER_PROVIDERorweb_guardbeforephp artisan migrate. - The user model of that provider must use
Laravel\Passport\HasApiTokensand implementLaravel\Passport\Contracts\OAuthenticatable, whichever model it is.
Not in the package
Image upload, a JSON API for connections, CORS for browser-based clients and the content tools are not part of it. The package does not verify the claims of an assistant beyond what the metadata document and the allowlists say: the person on the consent screen is the final check.
Development
composer install # no composer.lock is committed (D-31) composer test # PHPUnit with Orchestra Testbench: the OAuth flow, discovery, client metadata, registration, the guard composer phpstan # PHPStan level max with the strict, deprecation and PHPUnit rules and Larastan composer cs # PHP-CS-Fixer with esoul-cz/coding-standard (`composer cs:fix` applies it)
CI is the Jenkinsfile: templateAddonPipeline(package: true, nightly: true) runs the package checks on PHP 8.4, 8.5 and 8.6, then builds every variant the addon declares with it against app-templates main and runs the variant's own checks.
Documentation
- GLOSSARY.md: the connector's vocabulary.
- docs/adr/: decisions about this repository.
- CHANGELOG.md: every change, in the app-templates format, read by the update skill.
Licence
MIT, see LICENSE. A project that takes the addon owns the code the addon copied into it.