Looking to hire Laravel developers? Try LaraJobs

laravel-ai-connector maintained by esoul-cz

Description
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.
Last update
2026/11/29 17:57 (dev-main)
License
Downloads
1
Tags

Comments
comments powered by Disqus

eSoul AI connector for Laravel

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: first delivery, package released as 0.1.0 (ADR-0001 Decision 5); not yet tried live with Claude or ChatGPT, which gates 0.2.0. 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 and astro-cms (the nginx locations of a CMS site).

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. 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:

  1. composer require esoul-cz/laravel-ai-connector, then php artisan vendor:publish --tag=ai-connector-config. (--tag=ai-connector-migrations publishes 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 add resource, registration, metadata_url and last_used_at.)
  2. Make the signing keys with php artisan passport:keys, or set PASSPORT_PRIVATE_KEY and PASSPORT_PUBLIC_KEY. They are a deploy secret: never commit them, never share them between environments.
  3. php artisan migrate.
  4. On the user model: use Laravel\Passport\HasApiTokens; and implements Laravel\Passport\Contracts\OAuthenticatable. The guard ai-connector is 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); define it in config/auth.php to change that.
  5. Write the consent view and name it in ai-connector.consent.view. It receives $clientName, $clientUrl (the URL of a metadata client, otherwise null), $redirectHost, $redirectUri, $registration (cimd or dcr), $user, $requestedLevel and $levels (ESoul\LaravelAiConnector\AccessLevel values: show the levels the person may choose from), $resource, $authToken, $approveUrl and $denyUrl. The form posts auth_token and level to $approveUrl; "Cancel" is the same form sent as DELETE to $denyUrl. The level the person chooses is lowered to what the assistant asked for; no choice means read only. Never skip the screen.
  6. Set ai-connector.login_route (a route name) or ai-connector.login_url, the sign-in of the people who approve connections. ai-connector.web_guard names their session guard (default: the default guard).
  7. Build your MCP server with laravel/mcp and 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 and AiConnector::accessToken($user)->level() the level of the connection.
  8. 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) and AiConnector::enabledUsing(fn (): bool => ...) (a runtime switch; the config key ai-connector.enabled, AI_CONNECTOR_ENABLED, is on top of it and is off by default).
  9. Set TRUSTED_PROXIES so that the URLs of the discovery documents are https://, 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) advertises https://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.
  10. The package schedules passport:purge and ai-connector:prune-clients daily (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: the token holds only the user's id, so it is looked up where the approving guard found the person
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

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.