<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/"><channel><title>Anass Ez-zouaine | Backend, AI &amp; Shopify Engineer | Laravel</title><description>Laravel posts from Anass Ez-zouaine | Backend, AI &amp; Shopify Engineer.</description><link>https://ansezz.com/</link><item><title>Stop sending your Laravel search filters as POST</title><link>https://ansezz.com/blog/laravel-query-method-search-endpoints/</link><guid isPermaLink="true">https://ansezz.com/blog/laravel-query-method-search-endpoints/</guid><description>Laravel 13.35 adds Route::query(), so a search endpoint can take a JSON body and still say it is read only. Here is why I would move internal search endpoints to QUERY now, and the three things to check first.</description><pubDate>Wed, 21 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Every Laravel app with a serious search screen ends up with the same route: &lt;code&gt;Route::post(&apos;/products/search&apos;, ...)&lt;/code&gt;. The filters are too big or too nested for a query string, and GET with a body is not something you can count on. So we use POST, and every tool between the client and the app now thinks that request changes data.&lt;/p&gt;
&lt;p&gt;Laravel 13.35 gives you another option.&lt;/p&gt;

- Laravel 13.35.0 adds `Route::query()` for the HTTP QUERY method ([PR #61797](https://github.com/laravel/framework/pull/61797)).
- QUERY is a safe, idempotent method that carries a request body. The spec is an IETF HTTP working group draft.
- My claim: for search and filter endpoints you control on both ends, switch from POST to QUERY now, even before CDNs cache it.
- Check three things first: CSRF on `web` routes, `Route::any()` routes, and your CORS allowed methods.

&lt;h2&gt;What changed&lt;/h2&gt;
&lt;p&gt;&lt;a href=&quot;https://github.com/laravel/framework/releases/tag/v13.35.0&quot;&gt;Laravel v13.35.0&lt;/a&gt;, released on 6 October 2026, includes &quot;Add QUERY route method support&quot;. The PR adds a &lt;code&gt;query()&lt;/code&gt; method to the router and the &lt;code&gt;Route&lt;/code&gt; facade, and adds &lt;code&gt;QUERY&lt;/code&gt; to &lt;code&gt;Router::$verbs&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;// src/Illuminate/Routing/Router.php, v13.35.0
public static $verbs = [&apos;GET&apos;, &apos;HEAD&apos;, &apos;POST&apos;, &apos;PUT&apos;, &apos;PATCH&apos;, &apos;DELETE&apos;, &apos;OPTIONS&apos;, &apos;QUERY&apos;];
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The testing helpers &lt;code&gt;query()&lt;/code&gt; and &lt;code&gt;queryJson()&lt;/code&gt; landed earlier in 13.x (&lt;a href=&quot;https://github.com/laravel/framework/pull/60662&quot;&gt;PR #60662&lt;/a&gt;), so you can test these routes the same way you test the others.&lt;/p&gt;
&lt;h2&gt;What QUERY means&lt;/h2&gt;
&lt;p&gt;The &lt;a href=&quot;https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/&quot;&gt;HTTP QUERY method draft&lt;/a&gt; describes a method that is safe and idempotent like GET, but sends its query in the request body like POST. It is still a draft, so treat the details as subject to change.&lt;/p&gt;
&lt;p&gt;That one property matters more than it sounds. POST tells retries, proxies, logs, and other developers &quot;this may change something&quot;. A search does not change anything. With POST you are sending a message that is false, and every layer has to be told about it by hand.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;The route&lt;/h2&gt;
&lt;p&gt;Moving an endpoint is small. Before:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Route::post(&apos;/products/search&apos;, SearchProductsController::class);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;After, on Laravel 13.35 or later:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use App\Http\Controllers\SearchProductsController;
use Illuminate\Support\Facades\Route;

Route::query(&apos;/products/search&apos;, SearchProductsController::class);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The controller does not change. &lt;code&gt;$request-&amp;gt;input()&lt;/code&gt; reads the JSON body as it does for POST, and &lt;code&gt;$request-&amp;gt;query()&lt;/code&gt; still reads the query string. The framework&apos;s own tests cover both: a JSON body read with &lt;code&gt;input(&apos;filters.name&apos;)&lt;/code&gt;, and a query string mixed with body data.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;

class SearchProductsController
{
    public function __invoke(Request $request)
    {
        $validated = $request-&amp;gt;validate([
            &apos;filters.brand&apos; =&amp;gt; [&apos;array&apos;],
            &apos;filters.brand.*&apos; =&amp;gt; [&apos;string&apos;],
            &apos;filters.price_max&apos; =&amp;gt; [&apos;nullable&apos;, &apos;numeric&apos;],
        ]);

        return Product::query()
            -&amp;gt;when($validated[&apos;filters&apos;][&apos;brand&apos;] ?? null, fn ($q, $brands) =&amp;gt; $q-&amp;gt;whereIn(&apos;brand&apos;, $brands))
            -&amp;gt;when($validated[&apos;filters&apos;][&apos;price_max&apos;] ?? null, fn ($q, $max) =&amp;gt; $q-&amp;gt;where(&apos;price&apos;, &apos;&amp;lt;=&apos;, $max))
            -&amp;gt;paginate(25);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And the test:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public function test_search_filters_by_brand(): void
{
    Product::factory()-&amp;gt;create([&apos;brand&apos; =&amp;gt; &apos;acme&apos;]);
    Product::factory()-&amp;gt;create([&apos;brand&apos; =&amp;gt; &apos;other&apos;]);

    $this-&amp;gt;queryJson(&apos;/api/products/search&apos;, [
        &apos;filters&apos; =&amp;gt; [&apos;brand&apos; =&amp;gt; [&apos;acme&apos;]],
    ])
        -&amp;gt;assertOk()
        -&amp;gt;assertJsonCount(1, &apos;data&apos;);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;On the client, &lt;code&gt;fetch&lt;/code&gt; accepts any method name:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;const res = await fetch(&apos;/api/products/search&apos;, {
  method: &apos;QUERY&apos;,
  headers: { &apos;Content-Type&apos;: &apos;application/json&apos;, Accept: &apos;application/json&apos; },
  body: JSON.stringify({ filters: { brand: [&apos;acme&apos;], price_max: 120 } }),
});
&lt;/code&gt;&lt;/pre&gt;
&lt;h2&gt;Three things to check first&lt;/h2&gt;
&lt;h3&gt;1. CSRF still applies on web routes&lt;/h3&gt;
&lt;p&gt;The Laravel PR made a deliberate choice: QUERY is still checked for a CSRF token. The PR explains that the spec calls QUERY safe, but your handler is app code, and nothing forces it to be free of side effects. So a QUERY route in the &lt;code&gt;web&lt;/code&gt; group needs a token, just like POST. If you call it from your own frontend with the usual &lt;code&gt;X-XSRF-TOKEN&lt;/code&gt; or &lt;code&gt;X-CSRF-TOKEN&lt;/code&gt; header, nothing changes. If you want to skip the check for one route, the PR points to &lt;code&gt;preventRequestForgery(except: [...])&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;I agree with this choice. It means moving from POST to QUERY on a &lt;code&gt;web&lt;/code&gt; route does not open a new hole.&lt;/p&gt;
&lt;h3&gt;2. &lt;code&gt;Route::any()&lt;/code&gt; now matches QUERY&lt;/h3&gt;
&lt;p&gt;Because &lt;code&gt;QUERY&lt;/code&gt; was added to &lt;code&gt;Router::$verbs&lt;/code&gt;, every &lt;code&gt;Route::any()&lt;/code&gt; route and every &lt;code&gt;Route::redirect()&lt;/code&gt; now also answers QUERY requests. The &lt;code&gt;route:list&lt;/code&gt; command also reads &lt;code&gt;ANY&lt;/code&gt; from the verbs list now. If you have an &lt;code&gt;any()&lt;/code&gt; route that writes data, it now takes one more method. Search your routes for &lt;code&gt;any(&lt;/code&gt; after you upgrade.&lt;/p&gt;
&lt;h3&gt;3. Cross-origin calls need a preflight&lt;/h3&gt;
&lt;p&gt;QUERY is not one of the methods a browser sends without asking first, so a cross-origin call triggers a CORS preflight. If your &lt;code&gt;config/cors.php&lt;/code&gt; lists methods by hand, add &lt;code&gt;QUERY&lt;/code&gt; to &lt;code&gt;allowed_methods&lt;/code&gt;. The default &lt;code&gt;[&apos;*&apos;]&lt;/code&gt; already covers it.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Why now, before caches support it&lt;/h2&gt;
&lt;p&gt;This is the part you can argue with. Most CDNs and reverse proxies do not cache QUERY today, and some older proxies or WAF rules may reject a method they do not know. So why switch?&lt;/p&gt;
&lt;p&gt;Because the main gain is not caching. It is that the request tells the truth. For endpoints where you own the client and the server, like an admin search, an internal API, or a service to service call, you can test the whole path today. You get a method name that tells retry logic it is safe to retry, makes logs easier to read, and stops a reviewer from asking &quot;does this POST write anything?&quot;.&lt;/p&gt;
&lt;p&gt;For public endpoints behind infrastructure you do not control, wait. Test that every hop passes QUERY through before you move.&lt;/p&gt;

- Laravel 13.35 adds `Route::query()`. Your controller code stays the same.
- Use it for read only search endpoints where you control both ends.
- Keep CSRF on, audit `Route::any()`, and allow `QUERY` in CORS.
- Keep POST for public endpoints until every proxy in the path accepts QUERY.

&lt;p&gt;How many of your POST routes only read?&lt;/p&gt;
&lt;h2&gt;Sources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/laravel/framework/releases/tag/v13.35.0&quot;&gt;laravel/framework v13.35.0 release&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/laravel/framework/pull/61797&quot;&gt;PR #61797: Add QUERY route method support&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/laravel/framework/pull/60662&quot;&gt;PR #60662: Add query and queryJson HTTP testing helpers&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://datatracker.ietf.org/doc/draft-ietf-httpbis-safe-method-w-body/&quot;&gt;IETF draft: The HTTP QUERY Method&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>api-design</category><category>networking</category><category>security</category></item><item><title>Your Laravel queue workers may be skipping your read replicas</title><link>https://ansezz.com/blog/laravel-sticky-connections-queue-workers/</link><guid isPermaLink="true">https://ansezz.com/blog/laravel-sticky-connections-queue-workers/</guid><description>With sticky read/write connections, one job that writes can push every later job in the same worker onto the primary database. Laravel 13.36 adds an opt-in reset. Here is how it works and when to turn it on.</description><pubDate>Thu, 15 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;You added read replicas so the primary database could rest. Then you look at the metrics and the primary is still doing most of the reads. If you run queue workers with &lt;code&gt;sticky&lt;/code&gt; turned on, the workers may be the reason.&lt;/p&gt;

- With `sticky` on, a write sends later reads on that connection to the write (primary) database.
- A queue worker is one long process, so one job that writes can pin the reads of every later job in that worker to the primary.
- Laravel 13.36 adds `Worker::$flushStickyConnections`, an opt-in reset before each job.
- Turn it on unless a job depends on reading what an earlier, unrelated job wrote in the same worker.

&lt;h2&gt;What &lt;code&gt;sticky&lt;/code&gt; does&lt;/h2&gt;
&lt;p&gt;Laravel lets you split a database connection into a &lt;code&gt;read&lt;/code&gt; side and a &lt;code&gt;write&lt;/code&gt; side. Selects go to the read hosts, and inserts, updates and deletes go to the write host (&lt;a href=&quot;https://laravel.com/docs/13.x/database#read-and-write-connections&quot;&gt;Laravel docs&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;Replicas lag a little behind the primary. So if you write a row and read it back right away from a replica, it may not be there yet. The &lt;code&gt;sticky&lt;/code&gt; option fixes that. The docs describe it this way: if a write has run &quot;during the current request cycle&quot;, any further reads use the write connection, so you can read back what you just wrote (&lt;a href=&quot;https://laravel.com/docs/13.x/database#the-sticky-option&quot;&gt;Laravel docs&lt;/a&gt;).&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&apos;mysql&apos; =&amp;gt; [
    &apos;driver&apos; =&amp;gt; &apos;mysql&apos;,
    &apos;read&apos; =&amp;gt; [&apos;host&apos; =&amp;gt; [&apos;10.0.0.11&apos;, &apos;10.0.0.12&apos;]],
    &apos;write&apos; =&amp;gt; [&apos;host&apos; =&amp;gt; [&apos;10.0.0.10&apos;]],
    &apos;sticky&apos; =&amp;gt; true,
    // ...
],
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;In a web request this is a good trade. The request ends, the process state resets, and the next request starts on the replicas again.&lt;/p&gt;
&lt;h2&gt;Why queue workers are different&lt;/h2&gt;
&lt;p&gt;A queue worker does not end after one job. &lt;code&gt;php artisan queue:work&lt;/code&gt; boots once and keeps running jobs until it is restarted. There is no &quot;request cycle&quot; boundary between jobs.&lt;/p&gt;
&lt;p&gt;The Laravel News write-up of the release puts it plainly: &quot;a single job that writes can send the reads of every later job in that worker to the write connection&quot; (&lt;a href=&quot;https://laravel-news.com/laravel-13-36-0&quot;&gt;Laravel News&lt;/a&gt;).&lt;/p&gt;
&lt;p&gt;The pull request that added the fix gives a concrete picture. For a worker with a high memory limit, one job that writes &quot;could mean for the next 10,000 jobs it uses the write connection&quot;, or until the next deploy restarts the worker, &quot;which means we actually lose the benefit of having replicas&quot; (&lt;a href=&quot;https://github.com/laravel/framework/pull/61915&quot;&gt;PR #61915&lt;/a&gt;).&lt;/p&gt;
&lt;figure&gt;
&lt;p&gt;Most job workloads write something. So in practice, almost every long-running worker ends up reading from the primary.&lt;/p&gt;
&lt;h2&gt;The fix in Laravel 13.36&lt;/h2&gt;
&lt;p&gt;Laravel v13.36.0 was released on October 13, 2026 (&lt;a href=&quot;https://github.com/laravel/framework/releases/tag/v13.36.0&quot;&gt;GitHub release&lt;/a&gt;). It includes a new static flag on the queue worker, merged on October 7 (&lt;a href=&quot;https://github.com/laravel/framework/pull/61915&quot;&gt;PR #61915&lt;/a&gt;):&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use Illuminate\Queue\Worker;

// AppServiceProvider::boot()
Worker::$flushStickyConnections = true;
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;With the flag on, the worker resets the sticky state before each job. Each job starts on the replicas, and only switches to the primary for reads after it writes something itself.&lt;/p&gt;
&lt;p&gt;It is off by default. The reason given is that &quot;a job could depend on reading what an earlier job in the same worker wrote&quot; (&lt;a href=&quot;https://laravel-news.com/laravel-13-36-0&quot;&gt;Laravel News&lt;/a&gt;). The PR author suggests it could become the default in Laravel 14, but did not want to break existing apps in a minor release (&lt;a href=&quot;https://github.com/laravel/framework/pull/61915&quot;&gt;PR #61915&lt;/a&gt;).&lt;/p&gt;

  &lt;div&gt;
&lt;p&gt;Job 1 writes. Jobs 2 to N in that worker read from the primary until the worker restarts.&lt;/p&gt;
  &lt;/div&gt;
  &lt;div&gt;
&lt;p&gt;Job 1 writes. Job 2 starts fresh on the replicas. It only reads from the primary after its own first write.&lt;/p&gt;
  &lt;/div&gt;

&lt;h2&gt;Should you turn it on?&lt;/h2&gt;
&lt;p&gt;Ask one question: does any job read data that a different job wrote moments before, and only works because both ran in the same worker?&lt;/p&gt;
&lt;p&gt;If the answer is yes, that is a hidden dependency. The PR author makes the same point: if jobs depend on other jobs, &quot;they should be a chain or a batch, not quietly relying on whichever worker process happened to pop them&quot; (&lt;a href=&quot;https://github.com/laravel/framework/pull/61915&quot;&gt;PR #61915&lt;/a&gt;). With several workers, the second job can already land on a different process, so the dependency is fragile today.&lt;/p&gt;
&lt;p&gt;If the answer is no, turning the flag on is a small change with a clear upside: your workers start using the replicas you already pay for.&lt;/p&gt;
&lt;p&gt;A simple rollout:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Upgrade to Laravel 13.36 or later.&lt;/li&gt;
&lt;li&gt;Add the flag in &lt;code&gt;AppServiceProvider::boot()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Deploy, then restart your workers so they pick up the change (&lt;code&gt;php artisan queue:restart&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;Watch read traffic on the primary and on the replicas. Reads should move toward the replicas.&lt;/li&gt;
&lt;li&gt;Watch failed jobs for &quot;model not found&quot; style errors. Those point to a job reading a replica before replication caught up.&lt;/li&gt;
&lt;/ol&gt;
&lt;figure&gt;
&lt;h2&gt;Watch for replica lag&lt;/h2&gt;
&lt;p&gt;The flag does not remove replica lag. It only stops one job&apos;s write from deciding where the next job reads.&lt;/p&gt;
&lt;p&gt;If a job is dispatched right after a web request writes a row, and the job reads that row from a replica, it can still miss it. That was true before this change for the first job in a fresh worker, too. For those jobs, read from the write connection on purpose, for example with &lt;code&gt;Model::onWriteConnection()&lt;/code&gt; (&lt;a href=&quot;https://api.laravel.com/docs/13.x/Illuminate/Database/Eloquent/Model.html&quot;&gt;API docs&lt;/a&gt;), or dispatch the job with &lt;code&gt;afterCommit()&lt;/code&gt; so it only runs once the transaction is committed (&lt;a href=&quot;https://laravel.com/docs/13.x/queues#jobs-and-database-transactions&quot;&gt;Laravel docs&lt;/a&gt;).&lt;/p&gt;
&lt;h2&gt;Other queue fixes in the same release&lt;/h2&gt;
&lt;p&gt;The same release has a few more changes for people running workers (&lt;a href=&quot;https://laravel-news.com/laravel-13-36-0&quot;&gt;Laravel News&lt;/a&gt;, &lt;a href=&quot;https://github.com/laravel/framework/releases/tag/v13.36.0&quot;&gt;GitHub release&lt;/a&gt;):&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Change&lt;/th&gt;
&lt;th&gt;What it means&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;#[DeleteWhenMissingModels]&lt;/code&gt; and &lt;code&gt;#[FailOnTimeout]&lt;/code&gt; now work on queued mailables&lt;/td&gt;
&lt;td&gt;A mail for a deleted model is dropped instead of failing, and a timed out mail is not retried and sent twice.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Redis queue notification pushes are batched&lt;/td&gt;
&lt;td&gt;Fewer round trips to Redis when pushing many notifications.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;PgBouncer SSL EOF errors count as lost connections&lt;/td&gt;
&lt;td&gt;Laravel can reconnect instead of failing the job.&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Mercure broadcasts run synchronously by default&lt;/td&gt;
&lt;td&gt;Set &lt;code&gt;MERCURE_ASYNC=true&lt;/code&gt; to queue them again.&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

- `sticky` is built for request cycles, and a queue worker has no request cycle between jobs.
- One writing job can pin a worker&apos;s reads to the primary until the worker restarts.
- Laravel 13.36 adds `Worker::$flushStickyConnections = true` to reset that before each job.
- If a job depends on another job&apos;s write, make it a chain or a batch, then turn the flag on.
- Measure read traffic on the primary before and after.

&lt;p&gt;Have you checked where your workers actually read from?&lt;/p&gt;
&lt;h2&gt;Sources&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href=&quot;https://laravel-news.com/laravel-13-36-0&quot;&gt;Laravel 13.36 release notes, Laravel News&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/laravel/framework/releases/tag/v13.36.0&quot;&gt;laravel/framework v13.36.0 release&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://github.com/laravel/framework/pull/61915&quot;&gt;PR #61915: Allow queue workers to flush sticky connections between jobs&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://laravel.com/docs/13.x/database#read-and-write-connections&quot;&gt;Laravel 13.x docs: read and write connections, the sticky option&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://laravel.com/docs/13.x/queues#jobs-and-database-transactions&quot;&gt;Laravel 13.x docs: jobs and database transactions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href=&quot;https://api.laravel.com/docs/13.x/Illuminate/Database/Eloquent/Model.html&quot;&gt;Laravel API: Eloquent Model::onWriteConnection&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>databases</category><category>performance</category><category>scaling</category></item><item><title>MCP OAuth PKCE for multi-tenant SaaS</title><link>https://ansezz.com/blog/mcp-oauth-pkce-multi-tenant-saas/</link><guid isPermaLink="true">https://ansezz.com/blog/mcp-oauth-pkce-multi-tenant-saas/</guid><description>Laravel MCP requires PKCE S256 and prefers Client ID Metadata Documents. How multi-tenant SaaS should bind workspace at consent and avoid common agent auth failures.</description><pubDate>Thu, 01 Oct 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Agent OAuth fails in boring ways: missing PKCE, wrong &lt;code&gt;APP_URL&lt;/code&gt;, a new dynamic client on every redirect, a token that has scopes but no tenant.&lt;/p&gt;

- Laravel MCP 1.0 requires PKCE S256 in your authorization server metadata before it will redirect.
- Client ID Metadata Documents replace habitual Dynamic Client Registration, with a null client secret.
- Scopes do not name a tenant. Bind the workspace at consent and enforce it on every tool call.

&lt;p&gt;Laravel MCP 1.0 makes two of those failures explicit. As of the &lt;a href=&quot;https://github.com/laravel/mcp/blob/main/UPGRADE.md&quot;&gt;1.0 upgrade guide&lt;/a&gt; and &lt;a href=&quot;https://laravel.com/docs/mcp&quot;&gt;Laravel MCP auth docs&lt;/a&gt;:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;PKCE is required.&lt;/strong&gt; &lt;code&gt;OAuthClient::redirect()&lt;/code&gt; throws if the authorization server metadata omits &lt;code&gt;code_challenge_methods_supported&lt;/code&gt; (and S256 is the expected method).&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Client ID Metadata Documents&lt;/strong&gt; are preferred over Dynamic Client Registration (DCR). Your &lt;code&gt;client_id&lt;/code&gt; can be an HTTPS URL to a JSON document your app hosts.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;This post is the multi-tenant SaaS reading of those rules: how to register clients, where tenant binding belongs, and the auth failures agents hit in production.&lt;/p&gt;
&lt;p&gt;Pair with &lt;a href=&quot;https://ansezz.com/blog/stateless-mcp-servers-laravel/&quot;&gt;stateless MCP servers&lt;/a&gt;, &lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;MCP auth and audit&lt;/a&gt;, and &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;Laravel multi-tenancy&lt;/a&gt;.&lt;/p&gt;
&lt;h2&gt;PKCE is not optional anymore&lt;/h2&gt;
&lt;p&gt;Previously, some servers omitted &lt;code&gt;code_challenge_methods_supported&lt;/code&gt; and clients proceeded anyway. Laravel MCP 1.0 rejects that.&lt;/p&gt;

  &lt;div&gt;The server leaves out PKCE metadata and the client carries on anyway.&lt;/div&gt;
  &lt;div&gt;`redirect()` throws until the server advertises S256.&lt;/div&gt;

&lt;p&gt;If you operate the authorization server (Passport / your IdP), publish:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&quot;code_challenge_methods_supported&quot;: [&quot;S256&quot;]
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;in &lt;code&gt;/.well-known/oauth-authorization-server&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;If you are the MCP &lt;strong&gt;client&lt;/strong&gt; connecting to a third party that will not advertise PKCE, you need another grant that fits (for example pre-issued credentials where appropriate). There is no &quot;turn off PKCE&quot; flag in &lt;code&gt;redirect()&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;For public agents and desktop hosts, PKCE is how you survive without embedding a client secret. Treat missing PKCE metadata as a hard misconfiguration, not a soft warning.&lt;/p&gt;

Open your `/.well-known/oauth-authorization-server` in a browser and confirm it lists `S256` under `code_challenge_methods_supported`.

&lt;h2&gt;Client ID Metadata Documents&lt;/h2&gt;
&lt;p&gt;MCP revision &lt;code&gt;2026-07-28&lt;/code&gt; deprecates DCR in favor of metadata documents. Flow in Laravel:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;Mcp::oAuthRoutesFor(&apos;github&apos;, $handler)&lt;/code&gt; registers connect, callback, and &lt;strong&gt;&lt;code&gt;GET /mcp/oauth/{client}/client-metadata.json&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;When the auth server advertises &lt;code&gt;client_id_metadata_document_supported&lt;/code&gt;, Laravel can use that document URL as &lt;code&gt;client_id&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;The app is treated as a &lt;strong&gt;public&lt;/strong&gt; client: &lt;code&gt;token_endpoint_auth_method&lt;/code&gt; is &lt;code&gt;none&lt;/code&gt;, and &lt;code&gt;$token-&amp;gt;clientSecret&lt;/code&gt; is &lt;code&gt;null&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;What changes in your app&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;Database columns for &lt;code&gt;client_secret&lt;/code&gt; must be &lt;strong&gt;nullable&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Refresh / token calls must accept a null secret&lt;/li&gt;
&lt;li&gt;&lt;code&gt;APP_URL&lt;/code&gt; must be correct in production; the document is built from it, not from the incoming Host header&lt;/li&gt;
&lt;li&gt;The metadata route is &lt;strong&gt;unauthenticated&lt;/strong&gt; on purpose so the authorization server can fetch it&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Custom path / extra fields:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Mcp::oAuthRoutesFor(
    &apos;github&apos;,
    $handler,
    clientMetadataUri: &apos;oauth/github/metadata.json&apos;,
    clientMetadata: [
        &apos;client_name&apos; =&amp;gt; &apos;Acme Dashboard&apos;,
        &apos;logo_uri&apos; =&amp;gt; &apos;https://acme.com/logo.png&apos;,
    ],
);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This also fixed a nasty 0.x footgun: calling &lt;code&gt;redirect()&lt;/code&gt; repeatedly could DCR a &lt;strong&gt;new&lt;/strong&gt; client every time. Metadata documents stop that churn.&lt;/p&gt;

Run a migration that makes your `client_secret` column nullable before you switch to metadata documents.

&lt;h2&gt;Multi-tenant: bind workspace at consent&lt;/h2&gt;
&lt;p&gt;Scopes alone do not name a tenant. A token with &lt;code&gt;mcp:use&lt;/code&gt; (or your custom scopes) that is not bound to workspace &lt;code&gt;acme-eu&lt;/code&gt; will happily call tools until your handler guesses wrong.&lt;/p&gt;
&lt;figure&gt;
&lt;p&gt;Pattern that holds up:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Consent UI&lt;/strong&gt; lets the human pick the workspace (or confirms the only one they can access).&lt;/li&gt;
&lt;li&gt;Persist &lt;code&gt;tenant_id&lt;/code&gt; / &lt;code&gt;workspace_id&lt;/code&gt; on the authorization code or token record you issue.&lt;/li&gt;
&lt;li&gt;On every tool call, resolve tenant from the &lt;strong&gt;token&lt;/strong&gt;, not from a free-form argument the model invents.&lt;/li&gt;
&lt;li&gt;Optionally allow a tool argument to &lt;em&gt;select among authorized tenants&lt;/em&gt;, never to invent a new one.&lt;/li&gt;
&lt;li&gt;Audit &lt;code&gt;user_id + tenant_id + tool + idempotency_key&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;h3&gt;Outbound tokens and audience&lt;/h3&gt;
&lt;p&gt;If you connect &lt;strong&gt;outbound&lt;/strong&gt; as an MCP client to GitHub-like servers per tenant, store the TokenSet per &lt;code&gt;user_id + tenant_id + mcp_client_name&lt;/code&gt;. Do not share one refresh across workspaces.&lt;/p&gt;
&lt;p&gt;Resource indicators / audience checks (RFC 8707 style) matter when the same IdP protects multiple APIs. Validate that the access token was minted for your MCP resource, not for an unrelated API.&lt;/p&gt;
&lt;p&gt;Resolve tenant from the token, not from a free-form argument the model invents.&lt;/p&gt;
&lt;h2&gt;Common agent auth failures&lt;/h2&gt;
&lt;figure&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Failure&lt;/th&gt;
&lt;th&gt;Symptom&lt;/th&gt;
&lt;th&gt;Fix&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;No PKCE advertisement&lt;/td&gt;
&lt;td&gt;&lt;code&gt;OAuthException&lt;/code&gt; on redirect&lt;/td&gt;
&lt;td&gt;Publish &lt;code&gt;code_challenge_methods_supported: [&quot;S256&quot;]&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Wrong &lt;code&gt;APP_URL&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Metadata &lt;code&gt;client_id&lt;/code&gt; / redirect mismatch&lt;/td&gt;
&lt;td&gt;Fix env; redeploy metadata&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;DCR every connect&lt;/td&gt;
&lt;td&gt;Orphan clients on IdP&lt;/td&gt;
&lt;td&gt;Prefer metadata documents&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Null secret surprise&lt;/td&gt;
&lt;td&gt;Insert fails / refresh breaks&lt;/td&gt;
&lt;td&gt;Nullable columns; auth method &lt;code&gt;none&lt;/code&gt;&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Scope without tenant&lt;/td&gt;
&lt;td&gt;Cross-tenant tool calls&lt;/td&gt;
&lt;td&gt;Bind tenant at consent; enforce in tools&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Legacy tests&lt;/td&gt;
&lt;td&gt;400 / &lt;code&gt;-32020&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Send MCP headers + &lt;code&gt;_meta&lt;/code&gt; on 2026-07-28&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Agents will narrate these as &quot;the tool is broken.&quot; Your job is to make the HTTP and OAuth errors structured enough that the model (or your skill) can tell the human to reconnect.&lt;/p&gt;
&lt;h2&gt;Checklist for SaaS MCP OAuth&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Advertise PKCE S256 on your auth server metadata.&lt;/li&gt;
&lt;li&gt;Prefer Client ID Metadata Documents; keep DCR only as fallback.&lt;/li&gt;
&lt;li&gt;Ensure metadata route is public; connect/callback stay behind &lt;code&gt;web&lt;/code&gt; (or your chosen) middleware.&lt;/li&gt;
&lt;li&gt;Make &lt;code&gt;client_secret&lt;/code&gt; storage nullable.&lt;/li&gt;
&lt;li&gt;Bind tenant at consent; enforce on every tool.&lt;/li&gt;
&lt;li&gt;Store outbound MCP tokens per tenant.&lt;/li&gt;
&lt;li&gt;Log auth failures with correlation ids (&lt;a href=&quot;https://ansezz.com/blog/stateless-mcp-servers-laravel/&quot;&gt;stateless servers&lt;/a&gt;).&lt;/li&gt;
&lt;li&gt;Dogfood with Claude / Cursor / your bot against a second workspace to prove isolation.&lt;/li&gt;
&lt;/ol&gt;

- Laravel MCP 1.0 requires PKCE support in authorization server metadata before redirect.
- Client ID Metadata Documents replace habitual DCR; `client_id` may be a URL with null secret.
- Multi-tenant safety is consent-time binding plus per-tool enforcement, not scope strings alone.
- Fix `APP_URL`, nullable secrets, and header/`_meta` tests before blaming the model.
- Treat reconnect UX as part of the product; agents cannot heal a broken OAuth client id.

&lt;p&gt;If an agent can call &lt;code&gt;refund_order&lt;/code&gt; with a token from workspace A while the chat is about workspace B, where did tenant binding fail: consent, token storage, or the tool handler?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>mcp</category><category>security</category><category>multi-tenancy</category><category>ai</category><category>agentic-ai</category></item><item><title>Stateless MCP servers on Laravel</title><link>https://ansezz.com/blog/stateless-mcp-servers-laravel/</link><guid isPermaLink="true">https://ansezz.com/blog/stateless-mcp-servers-laravel/</guid><description>Laravel MCP 1.0 drops session IDs. Scale with Octane and queues, keep auth and idempotency, and pass your own correlation ids in _meta.</description><pubDate>Wed, 30 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Laravel MCP 1.0 leans into protocol revision &lt;code&gt;2026-07-28&lt;/code&gt;: &lt;strong&gt;every request stands alone&lt;/strong&gt;.&lt;/p&gt;

- The `MCP-Session-Id` header and the session APIs are gone in Laravel MCP 1.0.
- Scale with Octane and queues, and keep durable state in Redis or your database under your own ids.
- Auth, tenant checks and idempotency now do the job the session used to do.

&lt;p&gt;The &lt;code&gt;MCP-Session-Id&lt;/code&gt; header is gone. &lt;code&gt;Request::sessionId()&lt;/code&gt;, &lt;code&gt;setSessionId()&lt;/code&gt;, and &lt;code&gt;SessionInitialized&lt;/code&gt; are gone. If your tools cached &quot;conversation state&quot; under a session id, that design does not survive the upgrade.&lt;/p&gt;
&lt;p&gt;That sounds scary until you remember how you already scale Laravel: &lt;strong&gt;Octane workers&lt;/strong&gt;, &lt;strong&gt;queues&lt;/strong&gt;, and &lt;strong&gt;explicit keys&lt;/strong&gt;. Stateless MCP is the same idea with stricter honesty.&lt;/p&gt;
&lt;p&gt;As of the &lt;a href=&quot;https://github.com/laravel/mcp/blob/main/UPGRADE.md&quot;&gt;1.0 upgrade guide&lt;/a&gt; and &lt;a href=&quot;https://laravel.com/docs/mcp&quot;&gt;Laravel MCP docs&lt;/a&gt;, modern requests carry protocol version and client capabilities in &lt;code&gt;params._meta&lt;/code&gt;. Older &lt;code&gt;initialize&lt;/code&gt; clients still negotiate, but new work should assume no server-side MCP session.&lt;/p&gt;
&lt;h2&gt;What you lose when sessions disappear&lt;/h2&gt;
&lt;p&gt;You lose a free place to stash:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&quot;Last tool the user ran&quot;&lt;/li&gt;
&lt;li&gt;Multi-step wizard progress keyed only by MCP session&lt;/li&gt;
&lt;li&gt;Implicit auth context that was set once at initialize time&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You do &lt;strong&gt;not&lt;/strong&gt; lose:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Bearer / OAuth identity on each HTTP request&lt;/li&gt;
&lt;li&gt;Database rows, Redis keys, and queue jobs&lt;/li&gt;
&lt;li&gt;Idempotency keys you already should have had for mutations&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If a feature needed a session, give it a &lt;strong&gt;first-class id&lt;/strong&gt; the client sends (workspace id, run id, approval id) in tool arguments or &lt;code&gt;_meta&lt;/code&gt;.&lt;/p&gt;

Search your code for `sessionId` and list every feature that depends on it. Each one needs its own explicit id.

&lt;h2&gt;Scale with Octane and queues&lt;/h2&gt;
&lt;figure&gt;
&lt;p&gt;HTTP MCP endpoints are ordinary Laravel routes (&lt;code&gt;Mcp::web&lt;/code&gt;). Octane helps when you want warm workers and lower boot cost for chatty agents. Rules that already apply to Octane still apply:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Do not leak mutable static state between requests&lt;/li&gt;
&lt;li&gt;Resolve tenant and auth &lt;strong&gt;per request&lt;/strong&gt;&lt;/li&gt;
&lt;li&gt;Prefer short tool handlers; push heavy work to queues&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;The long-running work pattern&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;Tool validates auth + input.&lt;/li&gt;
&lt;li&gt;Dispatch a job; return a structured &lt;code&gt;job_id&lt;/code&gt; / status URL immediately.&lt;/li&gt;
&lt;li&gt;Store progress in Redis or the database.&lt;/li&gt;
&lt;li&gt;Optional follow-up tool &lt;code&gt;get_job_status&lt;/code&gt; reads that store.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That is more reliable than holding an SSE stream open for ten minutes of report generation, and it survives worker restarts. Pair with &lt;a href=&quot;https://ansezz.com/blog/laravel-octane-high-traffic/&quot;&gt;Laravel Octane high traffic&lt;/a&gt; notes if you are tuning the runtime.&lt;/p&gt;
&lt;p&gt;Streaming tools (generators + SSE on web servers) still work for progress notifications. Treat them as &lt;strong&gt;transport&lt;/strong&gt;, not as durable session state.&lt;/p&gt;

Take your slowest tool, make it dispatch a job and return a `job_id`, and add a `get_job_status` tool that reads progress.

&lt;h2&gt;Auth and idempotency become the session&lt;/h2&gt;
&lt;p&gt;Every mutation tool should already:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Authenticate the actor (&lt;code&gt;auth:api&lt;/code&gt; / Sanctum / your middleware).&lt;/li&gt;
&lt;li&gt;Authorize the tenant.&lt;/li&gt;
&lt;li&gt;Accept an &lt;strong&gt;idempotency key&lt;/strong&gt; for refunds, rotates, and creates.&lt;/li&gt;
&lt;li&gt;Return &lt;a href=&quot;https://ansezz.com/blog/mcp-structured-tool-errors-laravel/&quot;&gt;structured errors&lt;/a&gt; the model can recover from.&lt;/li&gt;
&lt;li&gt;Write an &lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;audit line&lt;/a&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Without MCP sessions, those five are not optional polish. They are how two Octane workers and a retried agent call stay coherent. See &lt;a href=&quot;https://ansezz.com/blog/mcp-idempotency-laravel-mutations/&quot;&gt;MCP idempotency for Laravel mutations&lt;/a&gt;.&lt;/p&gt;
&lt;figure&gt;
&lt;p&gt;For protocol &lt;code&gt;2026-07-28&lt;/code&gt; HTTP clients, also send matching &lt;code&gt;MCP-Protocol-Version&lt;/code&gt;, &lt;code&gt;Mcp-Method&lt;/code&gt;, and (for calls) &lt;code&gt;Mcp-Name&lt;/code&gt; headers. Mismatches return HTTP 400 with JSON-RPC &lt;code&gt;-32020&lt;/code&gt;. Update feature tests that used bare &lt;code&gt;postJson&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;Correlation without MCP sessions&lt;/h2&gt;
&lt;p&gt;Pass your own identifiers:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;{
  &quot;params&quot;: {
    &quot;name&quot;: &quot;refund-order&quot;,
    &quot;arguments&quot;: {
      &quot;order_id&quot;: &quot;gid://...&quot;,
      &quot;idempotency_key&quot;: &quot;8f3c...&quot;,
      &quot;_meta&quot;: {
        &quot;io.modelcontextprotocol/protocolVersion&quot;: &quot;2026-07-28&quot;,
        &quot;app.correlation_id&quot;: &quot;run_01J...&quot;
      }
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Log &lt;code&gt;app.correlation_id&lt;/code&gt; (or your chosen key) beside tenant and user ids. Agents can resume by asking for status with that id. Humans can grep it in observability.&lt;/p&gt;
&lt;p&gt;Searchable catalogs and cache hints from Laravel MCP 1.0 (&lt;a href=&quot;https://ansezz.com/blog/laravel-mcp-searchable-tool-catalogs/&quot;&gt;searchable tool catalogs&lt;/a&gt;) also assume list/read responses may be cached while tool calls stay uncacheable.&lt;/p&gt;
&lt;p&gt;Stateless fits that model: discovery can be hot; mutations stay cold and keyed.&lt;/p&gt;
&lt;h2&gt;Migration checklist from 0.9 session code&lt;/h2&gt;
&lt;ol&gt;
&lt;li&gt;Delete &lt;code&gt;sessionId&lt;/code&gt; usage and &lt;code&gt;SessionInitialized&lt;/code&gt; listeners.&lt;/li&gt;
&lt;li&gt;Move conversation memory to your app DB / Redis with explicit ids.&lt;/li&gt;
&lt;li&gt;Ensure every web MCP route still has auth middleware.&lt;/li&gt;
&lt;li&gt;Add idempotency on money and inventory tools if missing.&lt;/li&gt;
&lt;li&gt;Fix tests for &lt;code&gt;_meta&lt;/code&gt; + MCP headers on &lt;code&gt;2026-07-28&lt;/code&gt; clients.&lt;/li&gt;
&lt;li&gt;Load-test Octane with concurrent tool calls for the same tenant.&lt;/li&gt;
&lt;li&gt;Document for agent authors: &quot;no server session; send correlation + idempotency.&quot;&lt;/li&gt;
&lt;/ol&gt;
&lt;h2&gt;What &quot;stateless&quot; does not mean&lt;/h2&gt;
&lt;p&gt;Stateless MCP does not mean &quot;forget the user.&quot; It means the &lt;strong&gt;MCP transport&lt;/strong&gt; does not own a sticky session bag between JSON-RPC messages.&lt;/p&gt;

  &lt;div&gt;The MCP session holds conversation state, wizard progress and auth context set once at initialize.&lt;/div&gt;
  &lt;div&gt;Each request carries identity. Your database carries history under ids you issued.&lt;/div&gt;

&lt;p&gt;Your product still has:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Logged-in users and OAuth tokens&lt;/li&gt;
&lt;li&gt;Tenant databases and feature flags&lt;/li&gt;
&lt;li&gt;Conversation threads in &lt;em&gt;your&lt;/em&gt; tables if you build a chat product&lt;/li&gt;
&lt;li&gt;Approval records waiting for a human&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Those live in application storage. The MCP server becomes a thin, horizontally scalable door into that storage. That is the same split you want for &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;multi-tenant Laravel&lt;/a&gt; APIs.&lt;/p&gt;
&lt;p&gt;The request carries identity; the database carries history.&lt;/p&gt;
&lt;p&gt;When an agent &quot;resumes&quot; work, it should call a tool with the ids you issued earlier (&lt;code&gt;run_id&lt;/code&gt;, &lt;code&gt;draft_id&lt;/code&gt;, &lt;code&gt;approval_id&lt;/code&gt;), not hope the same load balancer owns an in-memory map from last Tuesday.&lt;/p&gt;

- Laravel MCP 1.0 processes each request independently; MCP session APIs are removed.
- Scale with Octane and queues; keep durable state in Redis/DB under your own ids.
- Auth, tenant checks, and idempotency replace &quot;remembered&quot; session context.
- Modern calls carry protocol + capabilities in `params._meta` (and matching HTTP headers).
- Streaming is fine for progress; it is not a substitute for durable job state.

&lt;p&gt;If you deleted &lt;code&gt;MCP-Session-Id&lt;/code&gt; tomorrow, which of your tools would still be safe under two parallel Octane workers retrying the same agent turn?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>mcp</category><category>architecture</category><category>ai</category><category>agentic-ai</category><category>performance</category></item><item><title>Laravel MCP searchable tool catalogs</title><link>https://ansezz.com/blog/laravel-mcp-searchable-tool-catalogs/</link><guid isPermaLink="true">https://ansezz.com/blog/laravel-mcp-searchable-tool-catalogs/</guid><description>Laravel MCP 1.0 searchable catalogs and cache hints cut context bloat. When to expose tools versus discover them with search_tools and execute_tools.</description><pubDate>Sat, 26 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Every tool you advertise to a model costs tokens, up front.&lt;/p&gt;

- A fat `tools/list` taxes the context window. Keep a few hot tools and park the long tail behind `ToolSearch`.
- Cache hints cut how often clients refetch discovery and resources. Tool calls are never cached.
- Default to private cache scope for tenant-filtered catalogs, and keep auth and idempotency on every mutation.

&lt;p&gt;Names, descriptions, input schemas, output schemas. A SaaS MCP server with forty admin actions can burn a surprising slice of the context window before the user asks a single question.&lt;/p&gt;
&lt;p&gt;Laravel MCP 1.0 (as of the stable release covering protocol revision &lt;code&gt;2026-07-28&lt;/code&gt;) gives you two levers for that problem: &lt;strong&gt;searchable tool catalogs&lt;/strong&gt; and &lt;strong&gt;cache hints&lt;/strong&gt;. One shrinks what the model sees. The other reduces how often clients re-fetch discovery and resource payloads.&lt;/p&gt;
&lt;p&gt;This post is the practical split: which tools stay in the hot list, which go behind &lt;code&gt;ToolSearch&lt;/code&gt;, and how to set &lt;code&gt;ttlMs&lt;/code&gt; / scope without lying to shared caches.&lt;/p&gt;
&lt;p&gt;Pair it with the &lt;a href=&quot;https://ansezz.com/blog/mcp-first-is-the-new-mobile-first/&quot;&gt;MCP first&lt;/a&gt; framing and the &lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;Laravel MCP safety trilogy&lt;/a&gt; when you wire real mutations. Official docs: &lt;a href=&quot;https://laravel.com/docs/mcp&quot;&gt;Laravel MCP&lt;/a&gt; (Searchable Tool Catalogs and Cache Hints sections).&lt;/p&gt;
&lt;h2&gt;The context tax of a fat tools/list&lt;/h2&gt;
&lt;p&gt;When a client calls &lt;code&gt;tools/list&lt;/code&gt;, every returned tool definition becomes candidate context for the model. That is fine for five crisp tools. It hurts when you expose:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Rare seasonal ops (&lt;code&gt;close_year_end_books&lt;/code&gt;)&lt;/li&gt;
&lt;li&gt;Deep admin toggles nobody asks for in chat&lt;/li&gt;
&lt;li&gt;Large schemas with nested enums and long descriptions&lt;/li&gt;
&lt;li&gt;Tenant-specific tools that only matter after a search&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The agent does not need those definitions on turn one. It needs a short path to &lt;strong&gt;find&lt;/strong&gt; them when the user asks.&lt;/p&gt;
&lt;p&gt;Laravel MCP&apos;s answer is &lt;code&gt;ToolSearch&lt;/code&gt;: keep hot tools in &lt;code&gt;$tools&lt;/code&gt; as normal classes, and park the long tail under a &lt;code&gt;ToolSearch::class =&amp;gt; [...]&lt;/code&gt; entry.&lt;/p&gt;
&lt;h2&gt;How ToolSearch works in Laravel MCP 1.0&lt;/h2&gt;
&lt;p&gt;As documented, a searchable catalog registers two meta-tools for the client:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;search_tools&lt;/code&gt;: query by name, description, and input schema; returns matches with names, descriptions, and expected inputs (respect a result limit)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;execute_tools&lt;/code&gt;: invoke one or more tools by name from what search (or prior knowledge) surfaced&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Minimal server shape:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use Laravel\Mcp\Server;
use Laravel\Mcp\Server\Tools\ToolSearch;

class OpsServer extends Server
{
    protected array $tools = [
        // Always advertised...
        CreateInvoiceTool::class,
        ListDelayedOrdersTool::class,

        // Discovered on demand...
        ToolSearch::class =&amp;gt; [
            HistoricalAuditTool::class,
            RotateApiKeyTool::class,
            ExportComplianceCsvTool::class,
        ],
    ];
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;CurrentWeatherTool&lt;/code&gt;-style examples in the docs make the same point: advertise the common case; search for historical weather and alerts.&lt;/p&gt;
&lt;h3&gt;Limits and conditional registration&lt;/h3&gt;
&lt;p&gt;Limits for batched execution live in config:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;mcp.tool_search.max_tool_calls&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;mcp.tool_search.max_output_bytes&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Tune those before an agent can fan out ten heavy tools in one &lt;code&gt;execute_tools&lt;/code&gt; call.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Conditional registration still applies.&lt;/strong&gt; If a catalog tool&apos;s &lt;code&gt;shouldRegister&lt;/code&gt; returns &lt;code&gt;false&lt;/code&gt;, it will not appear in search results and cannot be executed. That matters for plan-gated or tenant-gated features.&lt;/p&gt;

Set `mcp.tool_search.max_tool_calls` and `mcp.tool_search.max_output_bytes` in config before you move any tool behind `ToolSearch`.

&lt;h2&gt;When to expose vs discover&lt;/h2&gt;
&lt;figure&gt;
&lt;p&gt;Use this as a decision table, not a vibe:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Put it in the hot list when...&lt;/th&gt;
&lt;th&gt;Put it behind ToolSearch when...&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;It is the main outcome users ask for&lt;/td&gt;
&lt;td&gt;It is long-tail or seasonal&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Search wording is ambiguous (&quot;fix order&quot; could mean five tools)&lt;/td&gt;
&lt;td&gt;The name and description search cleanly&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;You need zero discovery latency&lt;/td&gt;
&lt;td&gt;An extra search turn is acceptable&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;It is the safe entry point into a skill&lt;/td&gt;
&lt;td&gt;It is a deep follow-up after triage&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Schema is small and stable&lt;/td&gt;
&lt;td&gt;Schema is large or rarely needed&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Examples from a multi-tenant ops server:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Expose:&lt;/strong&gt; &lt;code&gt;list_delayed_orders&lt;/code&gt;, &lt;code&gt;get_order&lt;/code&gt;, &lt;code&gt;draft_customer_message&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Discover:&lt;/strong&gt; &lt;code&gt;issue_partial_refund&lt;/code&gt; (after policy skill), &lt;code&gt;export_tax_csv&lt;/code&gt;, &lt;code&gt;rotate_webhook_secret&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Exposing every mutation &quot;so the model can see it&quot; is how you get eager refunds. Discoverability plus a skill that says &lt;em&gt;when&lt;/em&gt; to search is safer.&lt;/p&gt;
&lt;p&gt;Tools without judgment burn money.&lt;/p&gt;
&lt;p&gt;That is the same discipline as &lt;a href=&quot;https://ansezz.com/blog/mcp-first-is-the-new-mobile-first/&quot;&gt;MCP first&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;If your agent already struggles with wrong tool choice, searchable catalogs alone will not fix bad descriptions. Write &lt;code&gt;#[Description]&lt;/code&gt; like a product brief. Ambiguous copy poisons both the hot list and search rankings.&lt;/p&gt;
&lt;h2&gt;Cache hints: stop refetching discovery&lt;/h2&gt;
&lt;figure&gt;
&lt;p&gt;Laravel MCP attaches &lt;strong&gt;advisory&lt;/strong&gt; cache hints to responses that may be cached: server discovery, primitive listings, and resource reads. Defaults are conservative: private scope, &lt;code&gt;ttlMs&lt;/code&gt; of zero (do not cache).&lt;/p&gt;
&lt;p&gt;You can set a server default with &lt;code&gt;#[Cacheable]&lt;/code&gt; and override per method via &lt;code&gt;cacheHints()&lt;/code&gt;:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;use Laravel\Mcp\Enums\CacheScope;
use Laravel\Mcp\Server\Attributes\Cacheable;

#[Cacheable(ttlMs: 60_000, scope: CacheScope::Public)]
class OpsServer extends Server
{
    protected function cacheHints(): array
    {
        return [
            &apos;tools/list&apos; =&amp;gt; new Cacheable(
                ttlMs: 30_000,
                scope: CacheScope::Public,
            ),
        ];
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Rules of thumb&lt;/h3&gt;
&lt;p&gt;From the docs and MCP caching draft:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;CacheScope::Public&lt;/code&gt;&lt;/strong&gt;: safe to share across users (same tool list for everyone)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;CacheScope::Private&lt;/code&gt;&lt;/strong&gt;: tied to the authorization context (filtered lists, user-specific resources)&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Resource-level &lt;code&gt;#[Cacheable]&lt;/code&gt;&lt;/strong&gt; wins over method and server defaults&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Missing or zero &lt;code&gt;ttlMs&lt;/code&gt;&lt;/strong&gt; means do not cache&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tool calls are never cacheable&lt;/strong&gt; (mutations and live reads stay fresh)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;On the client side, Laravel&apos;s MCP client honors hints when you opt in with &lt;code&gt;withCache()&lt;/code&gt;. Installing 1.0 does not enable caching by itself.&lt;/p&gt;
&lt;p&gt;That is good: accidental public caching of a private &lt;code&gt;tools/list&lt;/code&gt; is a tenancy bug waiting to happen.&lt;/p&gt;

  &lt;div&gt;Plan features change the tool list per shop, but `tools/list` is cached as public because the route is authenticated.&lt;/div&gt;
  &lt;div&gt;Tenant-filtered lists stay private. Public scope only when every caller sees the same primitives.&lt;/div&gt;

&lt;p&gt;For multi-tenant SaaS, default private unless you are sure every authenticated caller sees the same primitives. If plan features change the tool list per shop, public scope is wrong even if the HTTP route is authenticated.&lt;/p&gt;

Call `tools/list` as two users on different plans. If the lists differ, make sure its cache scope is private.

&lt;h2&gt;A practical split for a Laravel SaaS MCP&lt;/h2&gt;
&lt;p&gt;Here is a pattern that holds up on real products:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Three to seven hot tools&lt;/strong&gt; that cover 80% of chat intents.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Everything else under &lt;code&gt;ToolSearch&lt;/code&gt;&lt;/strong&gt;, with descriptions that include synonyms users actually say.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Skills / playbooks&lt;/strong&gt; that tell the agent to &lt;code&gt;search_tools&lt;/code&gt; before inventing a workflow.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Public short TTL&lt;/strong&gt; on &lt;code&gt;tools/list&lt;/code&gt; only when the catalog is identical for all callers.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Private longer TTL&lt;/strong&gt; on stable docs resources; zero TTL on anything tenant-flavored.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Auth, idempotency, structured errors&lt;/strong&gt; on mutations (&lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;auth and audit&lt;/a&gt;, &lt;a href=&quot;https://ansezz.com/blog/mcp-idempotency-laravel-mutations/&quot;&gt;idempotency&lt;/a&gt;, &lt;a href=&quot;https://ansezz.com/blog/mcp-structured-tool-errors-laravel/&quot;&gt;tool errors&lt;/a&gt;).&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Searchable catalogs reduce tokens. They do not replace permission checks. An agent that finds &lt;code&gt;rotate_api_key&lt;/code&gt; via search still needs the same actor, tenant, and audit line as a hot tool.&lt;/p&gt;
&lt;p&gt;If you are connecting agents as MCP clients rather than only hosting servers, the Laravel AI SDK path of spreading &lt;code&gt;Client::web(...)-&amp;gt;tools()&lt;/code&gt; into an agent still benefits: fewer advertised tools means less noise in the agent loop.&lt;/p&gt;
&lt;p&gt;Cache the listed collection when it is stable, as the AI SDK docs suggest for remote OAuth servers.&lt;/p&gt;
&lt;h2&gt;What this is not&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Not&lt;/strong&gt; &quot;hide unsafe tools and hope search never finds them.&quot; &lt;code&gt;shouldRegister&lt;/code&gt; and authorization still decide availability.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not&lt;/strong&gt; a substitute for pagination and concise schemas on the tools you do expose.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not&lt;/strong&gt; a reason to mark tenant-specific lists &lt;code&gt;Public&lt;/code&gt; for a cheap cache hit.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Not&lt;/strong&gt; automatic speed: hints are advisory; clients must opt in.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Protocol note: Laravel MCP 1.0 speaks &lt;code&gt;2026-07-28&lt;/code&gt; (including &lt;code&gt;server/discover&lt;/code&gt;) while still negotiating older &lt;code&gt;initialize&lt;/code&gt; clients. If your host is mid-upgrade, check the &lt;a href=&quot;https://laravel.com/docs/mcp&quot;&gt;Laravel MCP docs&lt;/a&gt; for your installed package version.&lt;/p&gt;

- Fat `tools/list` payloads tax the context window before the user speaks.
- Laravel MCP 1.0 `ToolSearch` keeps hot tools advertised and parks the long tail behind `search_tools` / `execute_tools`.
- Expose high-frequency, ambiguous, or entry-point tools; discover long-tail and heavy-schema tools.
- Cache hints (`ttlMs`, public/private) apply to discovery and resource reads, not tool calls.
- Prefer private scope for tenant-filtered catalogs; public only when every caller sees the same list.
- Pair catalogs with skills, auth, and idempotency. Discovery without governance is just a shorter path to the wrong mutation.

&lt;p&gt;If you listed every tool your admin UI exposes into MCP tomorrow, which five would earn a permanent slot in the hot list, and which ones should stay invisible until &lt;code&gt;search_tools&lt;/code&gt; earns them?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>mcp</category><category>agentic-ai</category><category>ai</category><category>architecture</category><category>claude</category></item><item><title>MCP tool errors agents can actually recover from</title><link>https://ansezz.com/blog/mcp-structured-tool-errors-laravel/</link><guid isPermaLink="true">https://ansezz.com/blog/mcp-structured-tool-errors-laravel/</guid><description>Throwing exceptions hides failures from the model. MCP wants isError tool results with actionable text, mapped from Laravel domain failures and audited like auth denials.</description><pubDate>Sat, 19 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;When a tool fails, the model needs a sentence it can act on, not a crashed server.&lt;/p&gt;

- Business failures go back as a normal tool result with `isError: true`. JSON-RPC errors are for protocol problems only.
- Catch once at the MCP adapter and map domain exceptions to a small, stable set of codes.
- Each error needs a hint that names the next tool or field, and the same code goes into your audit log.

&lt;p&gt;&lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;Auth and audit logging&lt;/a&gt; keep a tool attributable. &lt;a href=&quot;https://ansezz.com/blog/mcp-idempotency-laravel-mutations/&quot;&gt;Idempotency keys&lt;/a&gt; keep a retry from charging twice. Neither helps if a failed tool call looks like a crashed server to the model.&lt;/p&gt;
&lt;p&gt;I keep seeing the same bug in Laravel MCP servers. A domain failure throws, the transport turns it into a JSON-RPC error (or an empty 500), and Claude never gets a sentence it can use to self-correct.&lt;/p&gt;
&lt;p&gt;The agent retries the same bad invoice ID, invents a different tool, or apologizes to the user. The invoice was simply not in that tenant.&lt;/p&gt;
&lt;p&gt;This post is the third gate I ship with every mutating MCP surface: &lt;strong&gt;tool execution errors that stay inside the tool result&lt;/strong&gt;, carry a stable code, and tell the model what to try next, without leaking stack traces or other tenants&apos; IDs.&lt;/p&gt;
&lt;h2&gt;The failure mode&lt;/h2&gt;
&lt;p&gt;A support agent asks Claude to fetch invoice &lt;code&gt;inv_9f2&lt;/code&gt;. Your tool does this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public function handle(string $invoiceId, McpActor $actor): array
{
    $invoice = Invoice::query()
        -&amp;gt;where(&apos;tenant_id&apos;, $actor-&amp;gt;tenantId)
        -&amp;gt;where(&apos;id&apos;, $invoiceId)
        -&amp;gt;firstOrFail(); // ModelNotFoundException → 500 / JSON-RPC error

    return $this-&amp;gt;present($invoice);
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;firstOrFail()&lt;/code&gt; is correct for an HTTP controller that should return 404. Over MCP it is wrong.&lt;/p&gt;
&lt;h3&gt;Two channels for errors&lt;/h3&gt;
&lt;p&gt;The Model Context Protocol draws a hard line:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Protocol / request errors:&lt;/strong&gt; unknown tool name, malformed arguments at the RPC layer. JSON-RPC &lt;code&gt;error&lt;/code&gt; object. The client may surface these; models rarely recover well.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Tool execution errors:&lt;/strong&gt; business failure, missing row, permission denial you already decided to explain, upstream timeout. Reported as a &lt;strong&gt;successful&lt;/strong&gt; &lt;code&gt;tools/call&lt;/code&gt; result with &lt;code&gt;isError: true&lt;/code&gt; and actionable text in &lt;code&gt;content&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That second path is how the &lt;a href=&quot;https://modelcontextprotocol.io/specification/2025-06-18/server/tools&quot;&gt;MCP tools specification&lt;/a&gt; expects language models to self-correct. Hide the failure in a protocol error and you train the agent to flail.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Return isError. Do not throw across the wire.&lt;/h2&gt;
&lt;p&gt;Every tool handler ends in one of three shapes:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;final class McpToolResult
{
    public static function ok(array $payload): array
    {
        $json = json_encode($payload, JSON_THROW_ON_ERROR);

        return [
            &apos;content&apos; =&amp;gt; [[&apos;type&apos; =&amp;gt; &apos;text&apos;, &apos;text&apos; =&amp;gt; $json]],
            &apos;structuredContent&apos; =&amp;gt; $payload, // optional; keep in sync with outputSchema if you declare one
            &apos;isError&apos; =&amp;gt; false,
        ];
    }

    public static function fail(
        string $code,
        string $message,
        bool $retryable = false,
        ?string $hint = null,
    ): array {
        $body = array_filter([
            &apos;error&apos; =&amp;gt; [
                &apos;code&apos; =&amp;gt; $code,
                &apos;message&apos; =&amp;gt; $message,
                &apos;retryable&apos; =&amp;gt; $retryable,
                &apos;hint&apos; =&amp;gt; $hint,
            ],
        ]);

        $text = $hint
            ? &quot;{$message} Hint: {$hint}&quot;
            : $message;

        return [
            &apos;content&apos; =&amp;gt; [[&apos;type&apos; =&amp;gt; &apos;text&apos;, &apos;text&apos; =&amp;gt; $text]],
            // Prefer omitting structuredContent on errors unless your clients
            // are known to skip outputSchema validation when isError is true.
            &apos;isError&apos; =&amp;gt; true,
        ];
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notes that bite in production:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;isError: true&lt;/code&gt; is still a successful RPC result.&lt;/strong&gt; The call happened; the business outcome failed. That is the whole point.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Put the recovery text in &lt;code&gt;content&lt;/code&gt;.&lt;/strong&gt; Models read the text blocks. A code alone is not enough.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Be careful with &lt;code&gt;structuredContent&lt;/code&gt; on errors&lt;/strong&gt; if the tool declares &lt;code&gt;outputSchema&lt;/code&gt;. Some clients still validate error payloads against the success schema. The safe default today: actionable text in &lt;code&gt;content&lt;/code&gt;, no structured error object, unless you have verified your client stack.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Never put secrets, stack traces, SQL, or other tenants&apos; identifiers in the text the model sees.&lt;/strong&gt; Audit can keep a redacted internal reason; the agent gets a public message.&lt;/li&gt;
&lt;/ul&gt;

Search your MCP tools for `firstOrFail()` and uncaught exceptions. Each one is a place where the model gets a crash instead of a hint.

&lt;h2&gt;Map Laravel domain failures to a small code set&lt;/h2&gt;
&lt;p&gt;Do not invent a new error dialect per tool. Use one mapper, shared with the &lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;auth gate&lt;/a&gt; denial reasons and the &lt;a href=&quot;https://ansezz.com/blog/mcp-idempotency-laravel-mutations/&quot;&gt;idempotency&lt;/a&gt; conflict codes:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Code&lt;/th&gt;
&lt;th&gt;When&lt;/th&gt;
&lt;th&gt;Retry?&lt;/th&gt;
&lt;th&gt;Hint&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;not_found&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Missing in this tenant&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;List first; check the ID&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;forbidden&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Actor lacks scope&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;Elevate or pick another resource&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;validation_failed&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Args fail domain rules&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;Name the bad field and expected shape&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;conflict&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Same key, different args&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;New key for a new intent&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;in_flight&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Idempotency claim held&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;Retry the &lt;strong&gt;same&lt;/strong&gt; key shortly&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;rate_limited&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Tool budget exhausted&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;Back off; include Retry-After&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;upstream_unavailable&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Provider blip&lt;/td&gt;
&lt;td&gt;yes&lt;/td&gt;
&lt;td&gt;Retry once; no second refund&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;internal&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Truly unexpected&lt;/td&gt;
&lt;td&gt;no&lt;/td&gt;
&lt;td&gt;Stop; send the user to support&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;pre&gt;&lt;code&gt;final class McpErrorMapper
{
    public function fromThrowable(\Throwable $e, McpActor $actor): array
    {
        return match (true) {
            $e instanceof ModelNotFoundException =&amp;gt; McpToolResult::fail(
                code: &apos;not_found&apos;,
                message: &apos;Resource not found in your workspace.&apos;,
                hint: &apos;List resources first, then retry with an ID from that list.&apos;,
            ),
            $e instanceof AuthorizationException =&amp;gt; McpToolResult::fail(
                code: &apos;forbidden&apos;,
                message: &apos;You are not allowed to run this tool on that resource.&apos;,
                hint: &apos;Ask the account owner for the required permission.&apos;,
            ),
            $e instanceof ValidationException =&amp;gt; McpToolResult::fail(
                code: &apos;validation_failed&apos;,
                message: $e-&amp;gt;validator-&amp;gt;errors()-&amp;gt;first() ?: &apos;Invalid arguments.&apos;,
                hint: &apos;Fix the field named in the message and call again.&apos;,
            ),
            $e instanceof IdempotencyConflict =&amp;gt; McpToolResult::fail(
                code: &apos;conflict&apos;,
                message: &apos;Idempotency key was reused with different arguments.&apos;,
                hint: &apos;Generate a new idempotency_key for a new intent.&apos;,
            ),
            $e instanceof IdempotencyInFlight =&amp;gt; McpToolResult::fail(
                code: &apos;in_flight&apos;,
                message: &apos;A request with this idempotency key is still running.&apos;,
                retryable: true,
                hint: &apos;Wait a few seconds and retry with the same idempotency_key.&apos;,
            ),
            default =&amp;gt; McpToolResult::fail(
                code: &apos;internal&apos;,
                message: &apos;The tool failed unexpectedly. Do not retry with new side effects.&apos;,
                hint: &apos;Tell the user support needs the session id &apos;.$actor-&amp;gt;sessionId.&apos;.&apos;,
            ),
        };
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Catch once, at the adapter&lt;/h3&gt;
&lt;p&gt;Catch at the MCP adapter boundary, once, not inside every tool with a different string. Tools throw domain exceptions. The adapter decides what the model is allowed to see.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;public function invoke(string $tool, array $args, McpActor $actor): array
{
    try {
        $this-&amp;gt;auth-&amp;gt;assertAllowed($actor, $tool, $args);
        $result = $this-&amp;gt;tools-&amp;gt;run($tool, $args, $actor);
        $this-&amp;gt;audit-&amp;gt;allowed($tool, $args, $result);

        return McpToolResult::ok($result);
    } catch (\Throwable $e) {
        $error = $this-&amp;gt;errors-&amp;gt;fromThrowable($e, $actor);
        $this-&amp;gt;audit-&amp;gt;denied($tool, $args, $this-&amp;gt;errors-&amp;gt;codeOf($e));

        return $error;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;not_found&lt;/code&gt; must mean &quot;not in &lt;strong&gt;this&lt;/strong&gt; tenant,&quot; the same rule as your global scopes from &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;Laravel multi-tenancy&lt;/a&gt;. A row that exists for another customer is still &lt;code&gt;not_found&lt;/code&gt; to this actor.&lt;/p&gt;
&lt;p&gt;Never return &lt;code&gt;forbidden&lt;/code&gt; with the other tenant&apos;s ID in the message. That is an enumeration leak dressed as honesty.&lt;/p&gt;
&lt;h2&gt;Hints beat apologies&lt;/h2&gt;

  &lt;div&gt;Something went wrong.&lt;/div&gt;
  &lt;div&gt;Invoice not found in your workspace. Hint: call `list_invoices` for this customer, then retry `get_invoice` with an ID from that list.&lt;/div&gt;

&lt;p&gt;The first one is useless. The model will guess.&lt;/p&gt;
&lt;p&gt;The hint should name &lt;strong&gt;another tool the agent already has&lt;/strong&gt;, or a field to fix, not a URL to your internal runbook.&lt;/p&gt;
&lt;p&gt;You are writing for an LLM tool loop, not a human SRE.&lt;/p&gt;
&lt;p&gt;For &lt;code&gt;retryable: true&lt;/code&gt;, say what to reuse. Idempotency taught us that &quot;retry&quot; without &quot;same key&quot; creates double refunds. Encode that in the hint every time:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;A refund with this idempotency key is still in flight.
Hint: wait ~30s and call refund_order again with the SAME idempotency_key and arguments.
&lt;/code&gt;&lt;/pre&gt;

Rewrite your three most common error messages so each one ends with a hint that names a tool the agent already has.

&lt;h2&gt;Audit the code the model saw&lt;/h2&gt;
&lt;p&gt;Your audit stream already records &lt;code&gt;allowed | denied | replayed&lt;/code&gt;. Store the public error &lt;code&gt;code&lt;/code&gt; on denials.&lt;/p&gt;
&lt;p&gt;When an agent loops on &lt;code&gt;not_found&lt;/code&gt; fifty times, you want a query, not a vibes-based log scroll.&lt;/p&gt;
&lt;figure&gt;
&lt;pre&gt;&lt;code&gt;McpAuditEvent::query()-&amp;gt;create([
    &apos;tenant_id&apos; =&amp;gt; $actor-&amp;gt;tenantId,
    &apos;user_id&apos; =&amp;gt; $actor-&amp;gt;userId,
    &apos;session_id&apos; =&amp;gt; $actor-&amp;gt;sessionId,
    &apos;tool&apos; =&amp;gt; $tool,
    &apos;decision&apos; =&amp;gt; &apos;denied&apos;,
    &apos;reason&apos; =&amp;gt; $code, // not_found | forbidden | …
    &apos;args_hash&apos; =&amp;gt; hash(&apos;sha256&apos;, json_encode($redactedArgs)),
    &apos;args&apos; =&amp;gt; $redactedArgs,
    &apos;result_summary&apos; =&amp;gt; [&apos;isError&apos; =&amp;gt; true, &apos;code&apos; =&amp;gt; $code],
    &apos;idempotency_key&apos; =&amp;gt; $args[&apos;idempotency_key&apos;] ?? null,
    &apos;duration_ms&apos; =&amp;gt; $ms,
]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Ops dashboard: top denied codes per tool, per tenant, last 24h. Product signal: a spike in &lt;code&gt;validation_failed&lt;/code&gt; usually means your tool schema description is lying to the model.&lt;/p&gt;
&lt;h2&gt;What I refuse to ship&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;firstOrFail()&lt;/code&gt; / uncaught exceptions escaping the MCP adapter&lt;/li&gt;
&lt;li&gt;JSON-RPC errors for &quot;invoice missing&quot; or &quot;seat already reset&quot;&lt;/li&gt;
&lt;li&gt;Stack traces, SQLSTATE, or filesystem paths in &lt;code&gt;content&lt;/code&gt; text&lt;/li&gt;
&lt;li&gt;Different error shapes per tool (&lt;code&gt;err&lt;/code&gt; vs &lt;code&gt;error&lt;/code&gt; vs &lt;code&gt;message&lt;/code&gt; only)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;forbidden&lt;/code&gt; messages that confirm another tenant&apos;s resource exists&lt;/li&gt;
&lt;li&gt;Swallowing idempotency &lt;code&gt;conflict&lt;/code&gt; / &lt;code&gt;in_flight&lt;/code&gt; into a generic &lt;code&gt;internal&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;Marking money-moving failures &lt;code&gt;retryable: true&lt;/code&gt; without a key&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If a human API would return 404/409/422 with a problem+json body, the agent path needs &lt;code&gt;isError&lt;/code&gt; with a code and a hint, not a thrown Exception.&lt;/p&gt;
&lt;h2&gt;Wiring it into the series&lt;/h2&gt;
&lt;p&gt;This sits on top of &lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;MCP auth and audit logging&lt;/a&gt; and &lt;a href=&quot;https://ansezz.com/blog/mcp-idempotency-laravel-mutations/&quot;&gt;idempotency keys for mutations&lt;/a&gt;. Same &lt;code&gt;McpActor&lt;/code&gt;, same audit table, same claim codes, now visible to the model instead of only to your pager.&lt;/p&gt;
&lt;p&gt;Tenancy rules stay the &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;Laravel multi-tenancy&lt;/a&gt; ones; do not invent a parallel &quot;agent ACL.&quot;&lt;/p&gt;
&lt;p&gt;For wallet-level token budgets at the LLM edge, that is a different layer. See &lt;a href=&quot;https://ansezz.com/blog/rate-limiting-ai-wallet/&quot;&gt;rate limiting your AI wallet&lt;/a&gt;. Tool errors are what happen &lt;strong&gt;after&lt;/strong&gt; the model is already allowed to call you.&lt;/p&gt;
&lt;p&gt;If your MCP tools still throw through to the client and you want the error surface reviewed before agents hold live keys, &lt;a href=&quot;https://ansezz.com/contact/?package=ai&quot;&gt;start with an AI Integration Sprint&lt;/a&gt;. We will inventory which failures are recoverable, which must stop the loop, and how the audit trail proves it after a bad night.&lt;/p&gt;

- **Use MCP tool-result errors (`isError: true`) for business failures.** Reserve JSON-RPC errors for protocol problems.
- **Catch once at the adapter.** Map domain exceptions to a small, stable code set.
- **Write for the model:** message + hint that names the next tool or field; set `retryable` honestly.
- **Omit or carefully handle `structuredContent` on errors** if `outputSchema` is in play.
- **Audit the same codes** the agent saw. Spikes are product bugs, not just noise.
- **Never leak cross-tenant existence** through clever error text.

&lt;p&gt;When your agent hits a missing invoice today, does it get a hint it can act on, or a crash it can only apologize for?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>mcp</category><category>agentic-ai</category><category>security</category><category>api-design</category><category>multi-tenancy</category></item><item><title>MCP auth and audit logging in a Laravel SaaS</title><link>https://ansezz.com/blog/mcp-auth-audit-logging-laravel/</link><guid isPermaLink="true">https://ansezz.com/blog/mcp-auth-audit-logging-laravel/</guid><description>An MCP server on Laravel is only as safe as its tenancy boundary. Scoped tool auth, request-bound actor context, and an audit log you can actually read at 3am.</description><pubDate>Fri, 18 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Giving Claude a tool that can read tickets and billing is useful. Giving it the same credentials your admin panel uses is how you invent a new incident class.&lt;/p&gt;

- Bind one actor (tenant, user, session, scopes) at the edge. Tools read it and never accept a tenant from the model.
- Keep MCP tools thin and reuse the same finders and policies as your admin UI.
- Log every attempt, allowed or denied, with redacted args, a reason and the idempotency key.

&lt;p&gt;I have been wiring &lt;a href=&quot;https://ansezz.com/blog/claude-mcp-dev-tools/&quot;&gt;MCP servers&lt;/a&gt; into real Laravel SaaS surfaces, the same domain that powers the &lt;a href=&quot;https://ansezz.com/work/mcp-saas-server/&quot;&gt;MCP SaaS case study&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;The hard part is not JSON-RPC. The hard part is making sure every tool call is tenant-scoped, attributable, and auditable, without teaching the model a parallel permission system.&lt;/p&gt;
&lt;p&gt;This post is the pattern I keep shipping: actor context on the request, tools that refuse to invent a tenant, and an audit log that survives a prompt injection attempt.&lt;/p&gt;
&lt;h2&gt;The failure mode&lt;/h2&gt;
&lt;p&gt;Most first MCP demos look like this:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Boot a Laravel app.&lt;/li&gt;
&lt;li&gt;Register &lt;code&gt;list_tickets&lt;/code&gt;, &lt;code&gt;get_invoice&lt;/code&gt;, &lt;code&gt;refund_order&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;Hand the MCP client a service-account token that can do all three for every tenant.&lt;/li&gt;
&lt;li&gt;Call it a day.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That works in a sandbox. In production it fails the moment:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Two tenants share a deployment and the agent &quot;helpfully&quot; looks up the wrong invoice ID.&lt;/li&gt;
&lt;li&gt;A prompt-injected ticket description asks the agent to dump another customer&apos;s billing.&lt;/li&gt;
&lt;li&gt;A retry doubles a refund because nobody recorded the tool call idempotency key.&lt;/li&gt;
&lt;li&gt;You get paged and the logs say &lt;code&gt;tool=refund_order ok=true&lt;/code&gt; with no actor, no tenant, and no arguments.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;MCP does not invent tenancy for you. Laravel already has it. The job is to force every tool through that gate.&lt;/p&gt;
&lt;h2&gt;One actor per request&lt;/h2&gt;
&lt;figure&gt;
&lt;p&gt;Treat an MCP tool invocation like an HTTP request that happens to arrive over JSON-RPC. Bind an actor before any tool runs:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;final class McpActor
{
    public function __construct(
        public readonly string $tenantId,
        public readonly string $userId,
        public readonly string $sessionId,
        /** @var list&amp;lt;string&amp;gt; */
        public readonly array $scopes,
    ) {}
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Resolve it once at the transport edge (API token, signed agent session, or OAuth subject) and stash it on the container for the lifetime of that call:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;app()-&amp;gt;instance(McpActor::class, $actor);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Tools never accept &lt;code&gt;tenant_id&lt;/code&gt; from the model. If the model passes one, drop it. The only tenant that exists is the one on &lt;code&gt;McpActor&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;That single rule kills the most common cross-tenant footgun: an LLM that &quot;found&quot; an ID in context and used it.&lt;/p&gt;

Grep your tool schemas for `tenant_id`. Remove it from every input and read it from `McpActor` instead.

&lt;h2&gt;Tools are thin. Domain services stay thick.&lt;/h2&gt;
&lt;p&gt;Keep MCP handlers boring. Authorize, call the same service the Filament admin would call, return a shaped DTO:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;final class GetInvoiceTool
{
    public function __construct(
        private readonly McpActor $actor,
        private readonly InvoiceFinder $invoices,
        private readonly McpAuditLogger $audit,
    ) {}

    public function __invoke(array $args): array
    {
        $invoiceId = (string) ($args[&apos;invoice_id&apos;] ?? &apos;&apos;);

        $invoice = $this-&amp;gt;invoices-&amp;gt;findForTenant(
            tenantId: $this-&amp;gt;actor-&amp;gt;tenantId,
            invoiceId: $invoiceId,
        );

        if ($invoice === null) {
            $this-&amp;gt;audit-&amp;gt;denied(&apos;get_invoice&apos;, $args, &apos;not_found_or_foreign&apos;);
            return [&apos;error&apos; =&amp;gt; &apos;invoice_not_found&apos;];
        }

        if (! in_array(&apos;billing:read&apos;, $this-&amp;gt;actor-&amp;gt;scopes, true)) {
            $this-&amp;gt;audit-&amp;gt;denied(&apos;get_invoice&apos;, $args, &apos;missing_scope&apos;);
            return [&apos;error&apos; =&amp;gt; &apos;forbidden&apos;];
        }

        $payload = $invoice-&amp;gt;toMcpArray();
        $this-&amp;gt;audit-&amp;gt;allowed(&apos;get_invoice&apos;, $args, $payload);

        return $payload;
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Notice what is missing: a raw GraphQL passthrough, a &lt;code&gt;DB::table&lt;/code&gt; query that forgets &lt;code&gt;tenant_id&lt;/code&gt;, and any path where &quot;not found&quot; and &quot;wrong tenant&quot; diverge. Same response. Same audit reason code you can filter later.&lt;/p&gt;
&lt;p&gt;If you already enforce tenancy in Eloquent global scopes, keep them. MCP is not a reason to bypass them &quot;just this once.&quot;&lt;/p&gt;
&lt;h2&gt;Audit log shape that survives an incident&lt;/h2&gt;
&lt;figure&gt;
&lt;p&gt;I log one row per tool attempt, allowed or denied, with enough to reconstruct the call without storing secrets:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;McpAuditEvent::query()-&amp;gt;create([
    &apos;tenant_id&apos; =&amp;gt; $actor-&amp;gt;tenantId,
    &apos;user_id&apos; =&amp;gt; $actor-&amp;gt;userId,
    &apos;session_id&apos; =&amp;gt; $actor-&amp;gt;sessionId,
    &apos;tool&apos; =&amp;gt; $tool,
    &apos;decision&apos; =&amp;gt; $decision, // allowed | denied
    &apos;reason&apos; =&amp;gt; $reason,
    &apos;args_hash&apos; =&amp;gt; hash(&apos;sha256&apos;, json_encode($redactedArgs)),
    &apos;args&apos; =&amp;gt; $redactedArgs,
    &apos;result_summary&apos; =&amp;gt; $summary, // counts / IDs, never card data
    &apos;idempotency_key&apos; =&amp;gt; $idempotencyKey,
    &apos;duration_ms&apos; =&amp;gt; $ms,
]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Rules that have paid for themselves:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Redact before write.&lt;/strong&gt; Tokens, raw card PANs, and full email bodies do not belong in &lt;code&gt;args&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Hash + store.&lt;/strong&gt; The hash lets you prove two calls carried the same payload without dumping PII into every analytics export.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Deny is a first-class event.&lt;/strong&gt; Most teams only log successes. The interesting story is usually a denied &lt;code&gt;refund_order&lt;/code&gt; right before a successful one from a different session.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Idempotency keys for mutations.&lt;/strong&gt; Refunds, seat resets, and password emails must key on something the client retries with. Store it on the audit row and short-circuit duplicates.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;This is the same discipline I want on &lt;a href=&quot;https://ansezz.com/blog/secure-agentic-commerce-shopify/&quot;&gt;agentic commerce checkouts&lt;/a&gt;. Money-moving tools are just the obvious version of the rule.&lt;/p&gt;

  &lt;div&gt;`tool=refund_order ok=true`, with no actor, no tenant and no arguments.&lt;/div&gt;
  &lt;div&gt;Tenant, user, session, tool, decision, reason, redacted args, args hash, idempotency key and duration.&lt;/div&gt;

&lt;h2&gt;Scopes beat role names&lt;/h2&gt;
&lt;p&gt;&lt;code&gt;is_admin&lt;/code&gt; is a product concept. MCP wants capabilities:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;tickets:read
tickets:write
billing:read
billing:refund
docs:search
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Map your SaaS roles onto scopes at session mint time. The tool checks scopes.&lt;/p&gt;
&lt;p&gt;When a customer upgrades from &quot;support viewer&quot; to &quot;billing ops,&quot; you change the session mint, not every tool.&lt;/p&gt;
&lt;p&gt;Also expire sessions aggressively. An MCP session that lives for a week is a stolen-laptop story waiting to happen.&lt;/p&gt;

Write down the scopes each of your SaaS roles maps to, then check how long an MCP session lives before it expires.

&lt;h2&gt;What I refuse to expose&lt;/h2&gt;
&lt;p&gt;A short deny-list that has saved me more than any middleware:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Arbitrary Eloquent / Query Builder execution&lt;/li&gt;
&lt;li&gt;Raw GraphQL or &quot;run this SQL&quot; tools&lt;/li&gt;
&lt;li&gt;Cross-tenant search &quot;for convenience&quot;&lt;/li&gt;
&lt;li&gt;Tools that return full PII when a masked summary would do&lt;/li&gt;
&lt;li&gt;Mutations without an idempotency key&lt;/li&gt;
&lt;li&gt;Anything that bypasses the same policy class the HTTP API uses&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If a human support agent cannot do it in the admin UI, the model does not get a secret door.&lt;/p&gt;
&lt;h2&gt;Wiring it into the series&lt;/h2&gt;
&lt;p&gt;This sits next to &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;Laravel multi-tenancy&lt;/a&gt; and &lt;a href=&quot;https://ansezz.com/blog/laravel-octane-high-traffic/&quot;&gt;Octane under load&lt;/a&gt; on the framework side, and next to &lt;a href=&quot;https://ansezz.com/blog/mcp-vs-a2a-vs-acp/&quot;&gt;MCP vs A2A&lt;/a&gt; on the protocol side.&lt;/p&gt;
&lt;p&gt;The tenancy model is Laravel. The tool surface is MCP. The trust boundary is yours.&lt;/p&gt;
&lt;p&gt;If you are putting Claude on top of a multi-tenant Laravel app and want a second pair of eyes on the boundary, &lt;a href=&quot;https://ansezz.com/contact/?package=ai&quot;&gt;start with an AI Integration Sprint&lt;/a&gt;. We will map the tools, the scopes, and the audit trail before any agent sees production data.&lt;/p&gt;

- **Never let the model choose the tenant.** Bind `McpActor` at the edge; tools read it, they do not accept it.
- **Thin tools, thick domain.** Reuse the same finders and policies as your admin UI.
- **Audit allows and denies.** Include tool, actor, redacted args, reason, and idempotency key.
- **Scopes over roles** at the MCP boundary. Mint short-lived sessions.
- **No parallel API.** If it is dangerous in HTTP, it is dangerous in JSON-RPC.

&lt;p&gt;If you got paged tonight about a strange refund, could your audit log tell you which actor, tenant and session asked for it?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>mcp</category><category>agentic-ai</category><category>security</category><category>multi-tenancy</category></item><item><title>Idempotency keys for MCP mutations in Laravel</title><link>https://ansezz.com/blog/mcp-idempotency-laravel-mutations/</link><guid isPermaLink="true">https://ansezz.com/blog/mcp-idempotency-laravel-mutations/</guid><description>Refunds, seat resets, and password emails need more than audit logging. Client-supplied idempotency keys, server-side short-circuits, and race-safe storage under Octane.</description><pubDate>Fri, 18 Sep 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Agents retry. Transports retry. Humans mash &quot;send&quot; when the spinner hangs. Your mutation tools have to survive all three.&lt;/p&gt;

- Every MCP mutation needs a client-supplied idempotency key. Reads stay free.
- The server short-circuits: replay the first result, reject a reused key with new args, and refuse duplicates still in flight.
- A unique database index per tenant, tool and key is the real lock under Octane and Horizon.

&lt;p&gt;&lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;Auth and audit logging&lt;/a&gt; keep an MCP tool attributable. They do not keep a retry from charging the card twice.&lt;/p&gt;
&lt;p&gt;If your mutation tools treat every call as a new intent, you will invent double refunds, duplicate password emails, and seat resets that fire three times for one user request.&lt;/p&gt;
&lt;p&gt;This post is the follow-on pattern: client-supplied idempotency keys, a server short-circuit that returns the first result, keys stored on the same audit rows you already trust at 3am, and the race conditions that show up the moment you put Octane and Horizon in the path.&lt;/p&gt;
&lt;h2&gt;The failure mode is boring and expensive&lt;/h2&gt;
&lt;p&gt;A support agent asks Claude to refund order &lt;code&gt;ord_9f2&lt;/code&gt;. The tool runs. The HTTP connection from the MCP client drops at 30s.&lt;/p&gt;
&lt;p&gt;The client retries with the same arguments. Your handler has no memory of the first call, so Stripe sees two refunds.&lt;/p&gt;
&lt;p&gt;Same story for:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;code&gt;reset_seat&lt;/code&gt;: second call wipes a freshly restored seat.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;send_password_reset&lt;/code&gt;: user gets three emails in ninety seconds.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;apply_credit&lt;/code&gt;: ledger entry lands twice because Horizon re-dispatched after a worker restart.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;None of these are exotic. They are the default behavior of any system that treats &quot;call arrived&quot; as &quot;intent is new.&quot;&lt;/p&gt;
&lt;p&gt;Models and clients will retry. Make the server safe when they do.&lt;/p&gt;
&lt;p&gt;The fix is not &quot;tell the model not to retry.&quot;&lt;/p&gt;
&lt;h2&gt;Client supplies the key. Server owns the semantics.&lt;/h2&gt;
&lt;p&gt;Every mutating tool requires an &lt;code&gt;idempotency_key&lt;/code&gt; in the arguments. The client generates it (UUID v4 is fine) and reuses it for retries of the &lt;em&gt;same&lt;/em&gt; intent.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;final class RefundOrderTool
{
    public function __construct(
        private readonly McpActor $actor,
        private readonly IdempotencyGate $gate,
        private readonly OrderRefunder $refunder,
        private readonly McpAuditLogger $audit,
    ) {}

    public function __invoke(array $args): array
    {
        $key = trim((string) ($args[&apos;idempotency_key&apos;] ?? &apos;&apos;));
        if ($key === &apos;&apos; || strlen($key) &amp;gt; 128) {
            $this-&amp;gt;audit-&amp;gt;denied(&apos;refund_order&apos;, $args, &apos;missing_idempotency_key&apos;);
            return [&apos;error&apos; =&amp;gt; &apos;idempotency_key_required&apos;];
        }

        if (! in_array(&apos;billing:refund&apos;, $this-&amp;gt;actor-&amp;gt;scopes, true)) {
            $this-&amp;gt;audit-&amp;gt;denied(&apos;refund_order&apos;, $args, &apos;missing_scope&apos;);
            return [&apos;error&apos; =&amp;gt; &apos;forbidden&apos;];
        }

        return $this-&amp;gt;gate-&amp;gt;run(
            actor: $this-&amp;gt;actor,
            tool: &apos;refund_order&apos;,
            key: $key,
            args: $args,
            execute: fn () =&amp;gt; $this-&amp;gt;refunder-&amp;gt;refund(
                tenantId: $this-&amp;gt;actor-&amp;gt;tenantId,
                orderId: (string) $args[&apos;order_id&apos;],
                amountCents: (int) $args[&apos;amount_cents&apos;],
            ),
        );
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Rules I enforce at the edge:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Required on mutations, ignored on reads.&lt;/strong&gt; &lt;code&gt;get_invoice&lt;/code&gt; does not need one. &lt;code&gt;refund_order&lt;/code&gt; does not run without one.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Client-generated, not server-minted.&lt;/strong&gt; If the server invents the key, a retry cannot present the same one.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Length-bounded.&lt;/strong&gt; Cap at 128 chars. Reject empty, whitespace-only, and absurdly long strings.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Scoped to the actor&apos;s tenant.&lt;/strong&gt; The uniqueness constraint is never global. See below.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The model is allowed to &lt;em&gt;pass&lt;/em&gt; the key. It is not allowed to invent tenancy, scopes, or &quot;just this once&quot; bypasses.&lt;/p&gt;
&lt;p&gt;Same discipline as the auth post: tools read &lt;code&gt;McpActor&lt;/code&gt;, they do not accept &lt;code&gt;tenant_id&lt;/code&gt; from the payload.&lt;/p&gt;

List every MCP tool that moves money, sends mail or resets state, and make `idempotency_key` a required argument on each one.

&lt;h2&gt;Short-circuit before the domain runs&lt;/h2&gt;
&lt;p&gt;The gate is the whole product. First call executes and records. Later calls with the same key return the stored outcome without touching Stripe, the mailer, or the seat service.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;final class IdempotencyGate
{
    public function __construct(
        private readonly IdempotencyStore $store,
        private readonly McpAuditLogger $audit,
    ) {}

    /**
     * @param  callable(): array  $execute
     * @return array&amp;lt;string, mixed&amp;gt;
     */
    public function run(
        McpActor $actor,
        string $tool,
        string $key,
        array $args,
        callable $execute,
    ): array {
        $fingerprint = $this-&amp;gt;fingerprint($args);
        $claim = $this-&amp;gt;store-&amp;gt;claim(
            tenantId: $actor-&amp;gt;tenantId,
            tool: $tool,
            key: $key,
            argsHash: $fingerprint,
            ttlSeconds: 86_400,
        );

        if ($claim-&amp;gt;status === ClaimStatus::Replay) {
            $this-&amp;gt;audit-&amp;gt;replayed($tool, $args, $key, $claim-&amp;gt;result);
            return $claim-&amp;gt;result;
        }

        if ($claim-&amp;gt;status === ClaimStatus::Conflict) {
            $this-&amp;gt;audit-&amp;gt;denied($tool, $args, &apos;idempotency_payload_mismatch&apos;);
            return [&apos;error&apos; =&amp;gt; &apos;idempotency_key_reuse_with_different_args&apos;];
        }

        if ($claim-&amp;gt;status === ClaimStatus::InFlight) {
            $this-&amp;gt;audit-&amp;gt;denied($tool, $args, &apos;idempotency_in_flight&apos;);
            return [&apos;error&apos; =&amp;gt; &apos;request_in_flight&apos;];
        }

        try {
            $result = $execute();
            $this-&amp;gt;store-&amp;gt;complete($actor-&amp;gt;tenantId, $tool, $key, $result);
            $this-&amp;gt;audit-&amp;gt;allowed($tool, $args, $result, $key);
            return $result;
        } catch (\Throwable $e) {
            $this-&amp;gt;store-&amp;gt;fail($actor-&amp;gt;tenantId, $tool, $key, $e);
            $this-&amp;gt;audit-&amp;gt;denied($tool, $args, &apos;execution_failed&apos;, $key);
            throw $e;
        }
    }

    private function fingerprint(array $args): string
    {
        $copy = $args;
        unset($copy[&apos;idempotency_key&apos;]);
        ksort($copy);

        return hash(&apos;sha256&apos;, json_encode($copy, JSON_THROW_ON_ERROR));
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;figure&gt;
&lt;h3&gt;Four outcomes&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Fresh claim:&lt;/strong&gt; you own the key; run the mutation.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Replay:&lt;/strong&gt; same key, same args hash; return the stored result.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Conflict:&lt;/strong&gt; same key, &lt;em&gt;different&lt;/em&gt; args hash; reject. Reusing a key for a different order is a bug or an attack, not a retry.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;In flight:&lt;/strong&gt; another worker holds the claim; tell the client to wait and retry with the &lt;em&gt;same&lt;/em&gt; key. Do not start a second refund.&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;That conflict case is non-negotiable. Idempotency is &quot;same intent, same result,&quot; not &quot;this UUID is a free pass for whatever args you send next.&quot;&lt;/p&gt;
&lt;h2&gt;Store the key on the audit row&lt;/h2&gt;
&lt;p&gt;You already write one audit event per tool attempt. Put the key there.&lt;/p&gt;
&lt;p&gt;When finance asks &quot;did we double-refund &lt;code&gt;ord_9f2&lt;/code&gt;?&quot;, you join on &lt;code&gt;idempotency_key&lt;/code&gt; instead of guessing from timestamps.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;McpAuditEvent::query()-&amp;gt;create([
    &apos;tenant_id&apos; =&amp;gt; $actor-&amp;gt;tenantId,
    &apos;user_id&apos; =&amp;gt; $actor-&amp;gt;userId,
    &apos;session_id&apos; =&amp;gt; $actor-&amp;gt;sessionId,
    &apos;tool&apos; =&amp;gt; $tool,
    &apos;decision&apos; =&amp;gt; $decision, // allowed | denied | replayed
    &apos;reason&apos; =&amp;gt; $reason,
    &apos;args_hash&apos; =&amp;gt; hash(&apos;sha256&apos;, json_encode($redactedArgs)),
    &apos;args&apos; =&amp;gt; $redactedArgs,
    &apos;result_summary&apos; =&amp;gt; $summary,
    &apos;idempotency_key&apos; =&amp;gt; $idempotencyKey,
    &apos;duration_ms&apos; =&amp;gt; $ms,
]);
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;&lt;code&gt;replayed&lt;/code&gt; is a first-class decision. It is not a silent cache hit. Ops needs to see that the client retried and the server refused to mutate again.&lt;/p&gt;
&lt;p&gt;Index what you query:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;Schema::table(&apos;mcp_audit_events&apos;, function (Blueprint $table) {
    $table-&amp;gt;string(&apos;idempotency_key&apos;, 128)-&amp;gt;nullable();
    $table-&amp;gt;string(&apos;args_hash&apos;, 64)-&amp;gt;nullable();
    $table-&amp;gt;index([&apos;tenant_id&apos;, &apos;tool&apos;, &apos;idempotency_key&apos;]);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Two tables, two jobs&lt;/h3&gt;
&lt;p&gt;The audit table is the narrative. The idempotency store is the lock.&lt;/p&gt;
&lt;p&gt;Do not merge them into one table and hope. Audit wants append-only history; the gate wants a unique claim row you can update from &lt;code&gt;in_flight&lt;/code&gt; to &lt;code&gt;completed&lt;/code&gt;.&lt;/p&gt;
&lt;h2&gt;What to hash vs what to store&lt;/h2&gt;
&lt;p&gt;Separate three things people keep collapsing:&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Field&lt;/th&gt;
&lt;th&gt;Purpose&lt;/th&gt;
&lt;th&gt;Store raw?&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;idempotency_key&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Client retry identity&lt;/td&gt;
&lt;td&gt;Yes, you need it for lookups and support&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;args_hash&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Detect key reuse with different payloads&lt;/td&gt;
&lt;td&gt;Hash only of redacted, sorted args&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;code&gt;args&lt;/code&gt; / &lt;code&gt;result_summary&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Incident reconstruction&lt;/td&gt;
&lt;td&gt;Redacted IDs and counts, never secrets&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;Hash the fingerprint of the business args (order ID, amount, seat ID) after stripping the key itself. Store the raw key. Store redacted args on the audit row the same way you already do for reads.&lt;/p&gt;
&lt;p&gt;Do &lt;strong&gt;not&lt;/strong&gt; hash the idempotency key into oblivion &quot;for privacy.&quot; You will need the original string when a client asks why their retry returned &lt;code&gt;request_in_flight&lt;/code&gt;.&lt;/p&gt;
&lt;p&gt;You will also need it when you correlate MCP logs with Stripe&apos;s &lt;code&gt;Idempotency-Key&lt;/code&gt; header if you forward the same value downstream.&lt;/p&gt;
&lt;p&gt;Forwarding is optional but clean: if Stripe already keys refunds, pass the MCP key through. One identity across your audit log and the payment provider.&lt;/p&gt;
&lt;h2&gt;Uniqueness is per tenant, per tool, with a TTL&lt;/h2&gt;
&lt;p&gt;A global unique index on &lt;code&gt;idempotency_key&lt;/code&gt; alone is wrong in a multi-tenant SaaS. Two tenants can generate the same UUID. Two tools can legitimately reuse a key namespace if you are not careful.&lt;/p&gt;
&lt;p&gt;The claim identity is:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;(tenant_id, tool, idempotency_key)
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;That matches how &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;Laravel multi-tenancy&lt;/a&gt; already scopes every other sensitive row. MCP is not special.&lt;/p&gt;
&lt;h3&gt;Keys are not forever&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;24 hours&lt;/strong&gt; is a sane default for refunds and seat mutations: long enough for flaky clients, short enough that the table does not become a second ledger.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Password reset emails&lt;/strong&gt; can be shorter (1 to 2 hours). The harm window is smaller; the spam window is not.&lt;/li&gt;
&lt;li&gt;Expired keys may be reused for a &lt;em&gt;new&lt;/em&gt; intent. Treat expiry like a new claim, not a silent replay of ancient results.&lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;code&gt;Schema::create(&apos;mcp_idempotency_claims&apos;, function (Blueprint $table) {
    $table-&amp;gt;id();
    $table-&amp;gt;string(&apos;tenant_id&apos;);
    $table-&amp;gt;string(&apos;tool&apos;, 64);
    $table-&amp;gt;string(&apos;idempotency_key&apos;, 128);
    $table-&amp;gt;string(&apos;args_hash&apos;, 64);
    $table-&amp;gt;string(&apos;status&apos;, 16); // in_flight | completed | failed
    $table-&amp;gt;json(&apos;result&apos;)-&amp;gt;nullable();
    $table-&amp;gt;timestamp(&apos;expires_at&apos;);
    $table-&amp;gt;timestamps();

    $table-&amp;gt;unique([&apos;tenant_id&apos;, &apos;tool&apos;, &apos;idempotency_key&apos;]);
});
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;Prune expired rows on a schedule. Do not rely on &quot;we will never get collisions&quot; as a retention policy.&lt;/p&gt;
&lt;h2&gt;Races under Octane and Horizon&lt;/h2&gt;
&lt;p&gt;This is where the naive &lt;code&gt;SELECT&lt;/code&gt; then &lt;code&gt;INSERT&lt;/code&gt; dies.&lt;/p&gt;
&lt;p&gt;&lt;a href=&quot;https://ansezz.com/blog/laravel-octane-high-traffic/&quot;&gt;Octane&lt;/a&gt; keeps workers warm. Two concurrent MCP calls for the same key can hit two workers in the same second.&lt;/p&gt;
&lt;p&gt;Horizon can re-run a job after a SIGKILL mid-refund. Cache locks help for the in-process case; they are not enough alone if the mutation is async.&lt;/p&gt;
&lt;figure&gt;
&lt;h3&gt;What I ship&lt;/h3&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Unique constraint in the database&lt;/strong&gt; on &lt;code&gt;(tenant_id, tool, idempotency_key)&lt;/code&gt;. The database is the source of truth for &quot;who won the claim.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Claim with &lt;code&gt;INSERT … ON CONFLICT&lt;/code&gt; / &lt;code&gt;firstOrCreate&lt;/code&gt; + catch unique violations.&lt;/strong&gt; The loser reads the winner&apos;s row and follows Replay / InFlight / Conflict logic. Never &quot;just run it anyway.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Short Redis lock around the claim&lt;/strong&gt; (a few seconds) to reduce thundering herds. This is an optional optimization, not a substitute for the unique index.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;For Horizon-backed mutations&lt;/strong&gt;, the job payload &lt;em&gt;includes&lt;/em&gt; the idempotency key. The job itself goes through the same gate before calling Stripe. A worker restart must not create a second domain effect.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;In-flight timeout.&lt;/strong&gt; If a worker dies after claiming but before &lt;code&gt;complete&lt;/code&gt;, the row sits in &lt;code&gt;in_flight&lt;/code&gt;. Expire it (e.g. 60 to 120s) so a legitimate retry can reclaim, but only after you are sure the first side effect did not commit. Prefer making the downstream call itself idempotent (Stripe key, mail message-id) so reclaiming is safe.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;public function claim(
    string $tenantId,
    string $tool,
    string $key,
    string $argsHash,
    int $ttlSeconds,
): ClaimResult {
    try {
        $row = McpIdempotencyClaim::query()-&amp;gt;create([
            &apos;tenant_id&apos; =&amp;gt; $tenantId,
            &apos;tool&apos; =&amp;gt; $tool,
            &apos;idempotency_key&apos; =&amp;gt; $key,
            &apos;args_hash&apos; =&amp;gt; $argsHash,
            &apos;status&apos; =&amp;gt; &apos;in_flight&apos;,
            &apos;expires_at&apos; =&amp;gt; now()-&amp;gt;addSeconds($ttlSeconds),
        ]);

        return ClaimResult::fresh($row);
    } catch (UniqueConstraintViolationException) {
        $existing = McpIdempotencyClaim::query()
            -&amp;gt;where(&apos;tenant_id&apos;, $tenantId)
            -&amp;gt;where(&apos;tool&apos;, $tool)
            -&amp;gt;where(&apos;idempotency_key&apos;, $key)
            -&amp;gt;firstOrFail();

        return $this-&amp;gt;interpretExisting($existing, $argsHash);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;If you only remember one sentence: &lt;strong&gt;the unique index is the lock; application locks are a courtesy.&lt;/strong&gt;&lt;/p&gt;

Fire the same `refund_order` call twice in parallel against staging with one key. Exactly one refund should reach the payment provider.

&lt;h2&gt;What I refuse to ship&lt;/h2&gt;
&lt;ul&gt;
&lt;li&gt;Mutations that &quot;probably won&apos;t be retried&quot;&lt;/li&gt;
&lt;li&gt;Server-generated keys the client never sees&lt;/li&gt;
&lt;li&gt;Global idempotency uniqueness across tenants&lt;/li&gt;
&lt;li&gt;Silent success when the key matches but the args hash does not&lt;/li&gt;
&lt;li&gt;Storing card PANs or raw tokens in the claim &lt;code&gt;result&lt;/code&gt; JSON&lt;/li&gt;
&lt;li&gt;Bypassing the gate inside a Horizon job &quot;because we already checked in the tool&quot;&lt;/li&gt;
&lt;li&gt;Infinite TTL that turns the claims table into an unbounded second database&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;If a human admin UI would show a confirmation dialog before doing it twice, the agent path needs a key.&lt;/p&gt;
&lt;h2&gt;Wiring it into the series&lt;/h2&gt;
&lt;p&gt;This sits on top of &lt;a href=&quot;https://ansezz.com/blog/mcp-auth-audit-logging-laravel/&quot;&gt;MCP auth and audit logging&lt;/a&gt;: same &lt;code&gt;McpActor&lt;/code&gt;, same audit stream, stricter rules for anything that moves money or mail.&lt;/p&gt;
&lt;p&gt;Tenancy remains the Laravel model from &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;multi-tenancy&lt;/a&gt;; concurrency reality is the &lt;a href=&quot;https://ansezz.com/blog/laravel-octane-high-traffic/&quot;&gt;Octane&lt;/a&gt; one.&lt;/p&gt;
&lt;p&gt;If you are exposing refund or billing tools over MCP and want the gate reviewed before an agent holds a live key, &lt;a href=&quot;https://ansezz.com/contact/?package=ai&quot;&gt;start with an AI Integration Sprint&lt;/a&gt;. We will map which tools mutate, how keys flow, and what the audit trail must prove after a retry storm.&lt;/p&gt;

- **Require client idempotency keys on every MCP mutation.** Reads stay free; refunds do not.
- **Short-circuit on the server.** Replay the first result; conflict on arg mismatch; reject in-flight duplicates.
- **Store the key on the audit row** and keep a separate claims table with `(tenant_id, tool, key)` uniqueness.
- **Hash args for comparison; store keys raw; redact everything else.**
- **TTL per tool class.** 24h for money, shorter for mail. Prune expired claims.
- **Unique DB constraint beats Redis hope** under Octane workers and Horizon restarts.
- **Downstream idempotency** (Stripe, mail providers) makes reclaim-after-crash safe.

&lt;p&gt;If your MCP client dropped the connection mid-refund right now and retried, how many refunds would your customer see?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>mcp</category><category>agentic-ai</category><category>security</category><category>multi-tenancy</category></item><item><title>Laravel Octane for high-traffic PHP apps</title><link>https://ansezz.com/blog/laravel-octane-high-traffic/</link><guid isPermaLink="true">https://ansezz.com/blog/laravel-octane-high-traffic/</guid><description>Laravel Octane boots your app once and keeps it warm in memory, feeding requests through a worker pool. How to cut boot overhead and scale to high traffic.</description><pubDate>Fri, 29 May 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;Standard PHP rebuilds your whole Laravel app for every request. Octane builds it once and keeps it warm.&lt;/p&gt;

- PHP-FPM boots the framework on every request, so a complex app can spend 30ms to 50ms on setup before your code even runs.
- Octane keeps the app in memory on FrankenPHP, Swoole, Open Swoole or RoadRunner, and feeds requests through a worker pool you size for CPU-bound or I/O-bound work.
- Long-lived workers make leaks dangerous, so avoid request data in statics and singletons, and use `--max-requests` to recycle workers.

&lt;p&gt;Standard PHP is a bit like a restaurant that fires its entire staff and rebuilds the kitchen for every customer order. You walk in, they hire a chef, buy a stove, cook your meal and then demolish the building as soon as you leave.&lt;/p&gt;
&lt;p&gt;It&apos;s consistent and safe, but it wastes a lot of energy when you&apos;re trying to serve thousands of people at once.&lt;/p&gt;
&lt;h3&gt;The PHP-FPM lifecycle&lt;/h3&gt;
&lt;p&gt;Every request boots the entire Laravel framework, loads your service providers, parses your config and instantiates your objects. For low-traffic sites, that&apos;s fine.&lt;/p&gt;
&lt;p&gt;At real scale, say a busy &lt;a href=&quot;https://ansezz.com/blog/laravel-multi-tenancy/&quot;&gt;multi-tenant SaaS&lt;/a&gt;, those milliseconds of &quot;boot time&quot; become a wall you can&apos;t climb without throwing expensive hardware at it. Horizontal scaling buys you room, but it doesn&apos;t fix the underlying latency.&lt;/p&gt;
&lt;h3&gt;Stop rebuilding the kitchen&lt;/h3&gt;
&lt;p&gt;Laravel Octane boots your application once, keeps it in memory and feeds requests to it through a fast worker pool. PHP goes from &quot;short-lived script&quot; to &quot;long-lived process.&quot;&lt;/p&gt;
&lt;h2&gt;Why your app feels heavy without Laravel Octane&lt;/h2&gt;
&lt;p&gt;The overhead of traditional PHP costs you efficiency as well as speed. In a standard request, your CPU spends a big chunk of time just getting the application ready to work.&lt;/p&gt;
&lt;p&gt;Once it finally starts, it runs the database query, renders the view and then dies.&lt;/p&gt;
&lt;h3&gt;Paying for setup again and again&lt;/h3&gt;
&lt;p&gt;If you run a complex Laravel monolith with dozens of packages and custom service providers, your boot time might be 30ms to 50ms before a single line of business logic runs.&lt;/p&gt;
&lt;p&gt;Under high traffic, this leads to CPU thrashing. You&apos;re paying for the &quot;setup&quot; over and over again.&lt;/p&gt;
&lt;h3&gt;Warm workers&lt;/h3&gt;
&lt;p&gt;Octane removes this boot cycle. With application servers like Swoole or RoadRunner, your app stays resident in memory.&lt;/p&gt;
&lt;p&gt;The first request boots the framework, and later requests hit a &quot;warm&quot; application. You can move from 50ms responses to sub-10ms responses just by changing how the process is managed.&lt;/p&gt;

  &lt;div&gt;Every request boots Laravel, loads providers and parses config, runs your code, then throws it all away.&lt;/div&gt;
  &lt;div&gt;The app boots once per worker. Each request goes straight to your code on an app that is already warm.&lt;/div&gt;

&lt;figure&gt;
&lt;h2&gt;Choosing your application server&lt;/h2&gt;
&lt;p&gt;Octane runs on top of an application server, and it supports four: FrankenPHP, Swoole, Open Swoole and RoadRunner.&lt;/p&gt;
&lt;p&gt;FrankenPHP (a Go-based server built on Caddy) is the first option in the Octane docs, and it&apos;s the easiest path to HTTP/2, HTTP/3 and automatic HTTPS. In production, the two I reach for most are Swoole and RoadRunner, and they solve the &quot;persistent state&quot; problem differently.&lt;/p&gt;
&lt;h3&gt;Swoole&lt;/h3&gt;
&lt;p&gt;Swoole is a C extension for PHP. It&apos;s a fast networking engine that lets PHP handle asynchronous tasks, coroutines and long-lived connections.&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Pros:&lt;/strong&gt; it is very fast. Because it lives as an extension, it has deep access to PHP&apos;s internals. It also enables the Octane cache, an in-memory store (backed by Swoole tables) that the docs clock at up to 2 million reads/writes per second, plus concurrent tasks, ticks and intervals.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cons:&lt;/strong&gt; it can be a bit of a nightmare to install and debug. As a binary extension, you have to compile it or find the right package for your OS. Xdebug doesn&apos;t always play nice with it, and it can be picky about your environment.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;RoadRunner&lt;/h3&gt;
&lt;p&gt;RoadRunner is written in Go. It acts as a load balancer and process manager that talks to your PHP workers over a fast binary protocol (Goridge).&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Pros:&lt;/strong&gt; no extensions required. It&apos;s a single binary you drop into your project. It&apos;s much easier to set up in a &lt;a href=&quot;https://ansezz.com/blog/coolify-docker-saas-hosting/&quot;&gt;Docker container&lt;/a&gt; and feels more &quot;cloud-native.&quot;&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Cons:&lt;/strong&gt; it&apos;s slightly slower than Swoole because of the communication overhead between the Go binary and the PHP processes, though for most web apps, where time goes to the database and other I/O, you won&apos;t notice the difference.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;Which one to pick&lt;/h3&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Server&lt;/th&gt;
&lt;th&gt;Install effort&lt;/th&gt;
&lt;th&gt;Pick it when&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;FrankenPHP&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Smoothest setup&lt;/td&gt;
&lt;td&gt;You&apos;re starting out and want HTTP/3 for free&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;RoadRunner&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Single Go binary&lt;/td&gt;
&lt;td&gt;You want no PHP extension to manage&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Swoole&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;C extension, fiddly&lt;/td&gt;
&lt;td&gt;You need every millisecond, task workers or Octane cache&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;p&gt;For most developers starting out, I&apos;d pick FrankenPHP at the install prompt and not overthink it. Reach for Swoole only when you&apos;re chasing every last millisecond or need its concurrency features like async task workers, ticks and the Octane cache.&lt;/p&gt;
&lt;h2&gt;Tuning your worker pool&lt;/h2&gt;
&lt;p&gt;The secret sauce of Octane is the &quot;worker pool.&quot; Instead of one process per request, you have a fixed number of workers waiting for incoming traffic.&lt;/p&gt;
&lt;p&gt;If you misconfigure it, you&apos;ll either leave performance on the table or crash your server. My &lt;a href=&quot;https://ansezz.com/tools/capacity-calculator/&quot;&gt;server capacity calculator&lt;/a&gt; turns requests per second and latency into the number of workers you need.&lt;/p&gt;
&lt;h3&gt;CPU-bound vs I/O-bound&lt;/h3&gt;
&lt;p&gt;The right pool size depends on whether your app is CPU-bound or I/O-bound:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;CPU-bound apps:&lt;/strong&gt; if you do heavy data processing or image manipulation, set your worker count to your number of CPU cores. More workers just cause context switching and slow things down.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;I/O-bound apps:&lt;/strong&gt; most web apps spend 90% of their time waiting for a database, Redis or an external API. Here you can scale workers to 2x or even 4x your core count, so one worker can wait on the DB while another handles a new request.&lt;/li&gt;
&lt;/ol&gt;
&lt;pre&gt;&lt;code&gt;# Starting Octane with 16 workers for an I/O-heavy app
php artisan octane:start --server=swoole --workers=16
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Task workers&lt;/h3&gt;
&lt;p&gt;Don&apos;t forget &lt;strong&gt;task workers&lt;/strong&gt; if you&apos;re using Swoole. Sized separately with the &lt;code&gt;--task-workers&lt;/code&gt; flag, they run in their own processes.&lt;/p&gt;
&lt;p&gt;They&apos;re a good fit for fanning out concurrent queries without blocking the main request cycle.&lt;/p&gt;

Check whether your app is CPU-bound or I/O-bound under load, then start Octane with workers equal to your cores (CPU-bound) or 2x your cores (I/O-bound) and compare P95 latency.

&lt;h2&gt;The danger of persistent state&lt;/h2&gt;
&lt;p&gt;The main hurdle when moving to Octane is the shift in mindset. In traditional PHP, &quot;leaky&quot; code barely matters because the process dies after 100ms.&lt;/p&gt;
&lt;p&gt;Under Octane, a leak doesn&apos;t die with the request. It waits and grows.&lt;/p&gt;
&lt;h3&gt;What to watch&lt;/h3&gt;
&lt;p&gt;If a service provider has a static array that you append to on every request, that array grows until your server runs out of RAM. Be careful with:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;Static properties:&lt;/strong&gt; don&apos;t use them for request-specific data.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Singletons:&lt;/strong&gt; a singleton you register in the app container stays alive. If it caches data, make sure that data is cleared or managed between requests.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Global state:&lt;/strong&gt; avoid &lt;code&gt;global&lt;/code&gt; variables at all costs (which you should be doing anyway).&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Laravel &quot;resets&quot; some core services between requests, but it can&apos;t catch everything. If you&apos;re migrating an old codebase from &lt;a href=&quot;https://ansezz.com/blog/monolith-to-microservices/&quot;&gt;monolith to microservices&lt;/a&gt;, audit your service providers for any long-lived state.&lt;/p&gt;
&lt;figure&gt;
&lt;h3&gt;Protecting yourself with max-requests&lt;/h3&gt;
&lt;p&gt;The best insurance against memory leaks is the &lt;code&gt;--max-requests&lt;/code&gt; flag. It tells Octane to gracefully restart a worker after it has handled a set number of requests.&lt;/p&gt;
&lt;p&gt;Octane already does this every 500 requests by default. Tune the number to match how fast your workers accumulate memory.&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;# Restart workers every 1000 requests to prevent memory bloat
php artisan octane:start --max-requests=1000
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This keeps memory use predictable while still giving you the speed of a warm application.&lt;/p&gt;

Search your service providers for `static` properties and singletons that store request data. Move that data into the request or clear it between requests before you switch to Octane.

&lt;h2&gt;Real-world optimization tips&lt;/h2&gt;
&lt;p&gt;Once Octane is running, a few technical levers can squeeze out more performance.&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Database connections:&lt;/strong&gt; in Octane your workers stay alive, so each one holds its own DB connection open between requests instead of reconnecting every time. That&apos;s a win, but watch the math: more workers means more open connections. Check your &lt;code&gt;database.php&lt;/code&gt; config and make sure the worker count doesn&apos;t blow past your DB server&apos;s max connection limit. This matters even more once you add &lt;a href=&quot;https://ansezz.com/blog/replication-vs-backup-laravel/&quot;&gt;read replicas&lt;/a&gt;.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Octane cache:&lt;/strong&gt; if you&apos;re using Swoole, reach for &lt;code&gt;Cache::store(&apos;octane&apos;)&lt;/code&gt;. It&apos;s an in-memory Swoole table that&apos;s very fast and shared across every worker on the box. Use it for frequently accessed configuration or small datasets that rarely change. Remember it&apos;s wiped when the server restarts.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Bytecode caching:&lt;/strong&gt; make sure OPcache is enabled and tuned. Set &lt;code&gt;opcache.validate_timestamps=0&lt;/code&gt; in production since your code won&apos;t change while the server is running.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Graceful reloads:&lt;/strong&gt; when you deploy new code, run &lt;code&gt;php artisan octane:reload&lt;/code&gt;. It gracefully restarts the workers without dropping current connections, which you need for zero-downtime deployments.&lt;/li&gt;
&lt;/ol&gt;

Add `php artisan octane:reload` as the last step of your deploy script, and check that `workers x app servers` stays below your database&apos;s max connections. My [Postgres connection pool calculator](/tools/postgres-connection-calculator/) does that sum for you and suggests PgBouncer settings.


- **Identify the bottleneck:** only use Octane if boot time is the problem. If your database queries take 2 seconds, Octane won&apos;t help.
- **Test for leaks:** watch how your app behaves under sustained load and profile memory growth over time.
- **Monitor workers:** keep an eye on CPU and RAM to find the right worker count.
- **Use concurrency:** on Swoole, `Octane::concurrently()` runs independent operations in parallel via task workers and returns their results together, cutting total response time for complex pages.

&lt;p&gt;Octane lets PHP compete with Node.js and Go for high-concurrency apps while keeping the Laravel developer experience. If you&apos;re moving a busy Laravel app to Octane, &lt;a href=&quot;https://ansezz.com/services/&quot;&gt;here&apos;s how I help teams tune workers, connections and deploys for high traffic&lt;/a&gt;, or drop a note via &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;contact&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Are you running Octane in production yet, or is the fear of memory leaks keeping you on PHP-FPM?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>performance</category><category>scaling</category></item><item><title>Laravel multi-tenancy: a scalable SaaS architecture</title><link>https://ansezz.com/blog/laravel-multi-tenancy/</link><guid isPermaLink="true">https://ansezz.com/blog/laravel-multi-tenancy/</guid><description>Single DB vs multi-DB, global scopes that stop data leaks, stancl/tenancy in production, isolated storage, automated migrations, and a Docker plus Cloud setup.</description><pubDate>Sun, 08 Feb 2026 00:00:00 GMT</pubDate><content:encoded>&lt;p&gt;The scary moment in a SaaS launch is when you realize you don&apos;t know if customer A can see customer B&apos;s data.&lt;/p&gt;

- Pick your isolation model early: a shared database with `tenant_id` is cheap, a database per tenant gives the strongest isolation.
- Never rely on memory to filter tenant data. A global scope trait adds the filter to every query and sets `tenant_id` on create.
- Keep the web tier stateless and isolate cache and storage per tenant, so you can scale out with Docker and automate tenant setup.

&lt;p&gt;I still remember the panic of my first SaaS launch. I was watching the logs as the third customer signed up, and I realized I had no idea if customer A could see customer B&apos;s data.&lt;/p&gt;
&lt;p&gt;That realization is a rite of passage for every developer.&lt;/p&gt;
&lt;h3&gt;Isolation is the hard part&lt;/h3&gt;
&lt;p&gt;Building a software-as-a-service (SaaS) platform is a big technical challenge, and the main hurdle is almost always data isolation. Every tenant should feel like they have the whole application to themselves.&lt;/p&gt;
&lt;p&gt;If you get this wrong early, it will haunt you for a long time. Here is how I approach Laravel multi-tenancy to serve many customers from one codebase while keeping security and scalability intact.&lt;/p&gt;
&lt;h2&gt;Why simple database structures fail SaaS&lt;/h2&gt;
&lt;p&gt;Most developers start with a single database and add a &lt;code&gt;user_id&lt;/code&gt; or &lt;code&gt;team_id&lt;/code&gt; to every table. It works fine for the first ten users. Then the complexity grows.&lt;/p&gt;
&lt;h3&gt;One missing where clause&lt;/h3&gt;
&lt;p&gt;You add more relationships. You forget a &lt;code&gt;where&lt;/code&gt; clause in one obscure controller. Suddenly one customer can see another customer&apos;s private invoices.&lt;/p&gt;
&lt;p&gt;That is a catastrophic failure. It kills trust and can end your business overnight.&lt;/p&gt;
&lt;h3&gt;Data bloat&lt;/h3&gt;
&lt;p&gt;Performance also suffers. As your database grows to millions of rows, the queries get slower.&lt;/p&gt;
&lt;p&gt;Indexing helps, but it does not solve the underlying problem of data bloat. You need a strategy that isolates data while keeping your infrastructure manageable.&lt;/p&gt;
&lt;h2&gt;Choosing your isolation strategy&lt;/h2&gt;
&lt;p&gt;When I build custom web solutions, I always start by choosing between two paths: a single database or a multi-database setup.&lt;/p&gt;
&lt;h3&gt;Single database&lt;/h3&gt;
&lt;p&gt;The &lt;strong&gt;single database&lt;/strong&gt; approach uses a shared schema, and every row has a &lt;code&gt;tenant_id&lt;/code&gt;. It is cheap to run and easy to update.&lt;/p&gt;
&lt;p&gt;I recommend it for startups where costs need to stay low. You can manage thousands of small tenants on a single server this way.&lt;/p&gt;
&lt;h3&gt;Database per tenant&lt;/h3&gt;
&lt;p&gt;The &lt;strong&gt;multi-database&lt;/strong&gt; approach is the gold standard for enterprise. Every customer gets their own database.&lt;/p&gt;
&lt;p&gt;This gives the strongest isolation and makes per-tenant &lt;a href=&quot;https://ansezz.com/blog/replication-vs-backup-laravel/&quot;&gt;backups and replication&lt;/a&gt; straightforward. If one database crashes, the others stay online. I use this for tenants with strict compliance needs.&lt;/p&gt;
&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Strategy&lt;/th&gt;
&lt;th&gt;Isolation&lt;/th&gt;
&lt;th&gt;Cost and effort&lt;/th&gt;
&lt;th&gt;Good fit&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Single database&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Shared schema, &lt;code&gt;tenant_id&lt;/code&gt;&lt;/td&gt;
&lt;td&gt;Low, easy to update&lt;/td&gt;
&lt;td&gt;Startups, thousands of small tenants&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Multi-database&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;One database per tenant&lt;/td&gt;
&lt;td&gt;Higher, more to run&lt;/td&gt;
&lt;td&gt;Enterprise, strict compliance&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;h3&gt;The package I reach for&lt;/h3&gt;
&lt;p&gt;I often use the &lt;code&gt;stancl/tenancy&lt;/code&gt; package for Laravel. It is a very flexible tool and lets you switch between these strategies as your business grows.&lt;/p&gt;
&lt;p&gt;Some of this work is on my &lt;a href=&quot;https://ansezz.com/work/&quot;&gt;work page&lt;/a&gt;.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;Building with global scopes&lt;/h2&gt;
&lt;p&gt;The secret to sleeping well at night is automation. I never rely on my memory to filter data. Instead I use Laravel global scopes.&lt;/p&gt;
&lt;p&gt;A global scope automatically adds a filter to every query on a model. It makes sure &lt;code&gt;Customer::all()&lt;/code&gt; only returns customers for the current tenant, behind the scenes, so you cannot forget it.&lt;/p&gt;
&lt;p&gt;If tenant filtering depends on someone remembering it, a leak is only a matter of time.&lt;/p&gt;
&lt;h3&gt;The BelongsToTenant trait&lt;/h3&gt;
&lt;p&gt;I create a &lt;code&gt;BelongsToTenant&lt;/code&gt; trait and apply it to every model that needs isolation. It handles the filtering and sets the &lt;code&gt;tenant_id&lt;/code&gt; when a new record is created.&lt;/p&gt;
&lt;p&gt;It is a simple solution that prevents most accidental data leaks. Here&apos;s what that trait looks like in practice:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;&amp;lt;?php

namespace App\Concerns;

use App\Models\Tenant;
use App\Scopes\TenantScope;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

trait BelongsToTenant
{
    protected static function bootBelongsToTenant(): void
    {
        static::addGlobalScope(new TenantScope());

        static::creating(function ($model): void {
            if (! $model-&amp;gt;tenant_id &amp;amp;&amp;amp; app()-&amp;gt;bound(&apos;tenant&apos;)) {
                $model-&amp;gt;tenant_id = app(&apos;tenant&apos;)-&amp;gt;id;
            }
        });
    }

    public function tenant(): BelongsTo
    {
        return $this-&amp;gt;belongsTo(Tenant::class);
    }
}
&lt;/code&gt;&lt;/pre&gt;
&lt;h3&gt;Isolate cache and storage too&lt;/h3&gt;
&lt;p&gt;You also need to isolate your cache and file storage. If two tenants upload a file named &lt;code&gt;logo.png&lt;/code&gt;, they should not overwrite each other.&lt;/p&gt;
&lt;p&gt;I configure Laravel to use tenant-specific prefixes for all storage paths. That gives every tenant a true &quot;sandbox.&quot;&lt;/p&gt;

Write one test that creates two tenants, logs in as the first, and asserts that `Model::all()` returns zero rows from the second. Run it for every tenant-scoped model.

&lt;h2&gt;Scaling on the cloud&lt;/h2&gt;
&lt;p&gt;Your architecture is only as good as the infrastructure it runs on. I usually deploy my Laravel apps with Docker on cloud providers like Google Cloud or AWS.&lt;/p&gt;
&lt;h3&gt;Stateless web tier&lt;/h3&gt;
&lt;p&gt;Containerization is key. It lets me &lt;a href=&quot;https://ansezz.com/blog/horizontal-vs-vertical-scaling/&quot;&gt;scale the application horizontally&lt;/a&gt;: when traffic spikes, I spin up more web server instances.&lt;/p&gt;
&lt;p&gt;That only works because the web tier stays &lt;a href=&quot;https://ansezz.com/blog/stateless-vs-stateful-apps/&quot;&gt;stateless&lt;/a&gt;. Tenant context is resolved per request, not stored on the box, so the infrastructure stays clean.&lt;/p&gt;
&lt;p&gt;When a single tenant starts pushing serious request volume, I reach for &lt;a href=&quot;https://ansezz.com/blog/laravel-octane-high-traffic/&quot;&gt;Laravel Octane to handle high traffic&lt;/a&gt; before throwing more servers at the problem.&lt;/p&gt;
&lt;h3&gt;Automate tenant setup&lt;/h3&gt;
&lt;p&gt;I use managed database services like Google Cloud SQL. They handle the heavy lifting of backups and scaling.&lt;/p&gt;
&lt;p&gt;For multi-database setups, automated scripts provision a new database whenever a customer signs up. With this &quot;infrastructure as code&quot; approach, adding a tenant is a button click away.&lt;/p&gt;

  &lt;div&gt;A new customer signs up, and someone creates the database, runs migrations and sets up storage by hand.&lt;/div&gt;
  &lt;div&gt;Signup triggers a script that provisions the database, runs tenant migrations and sets the storage prefix. The customer is live in minutes.&lt;/div&gt;

&lt;h2&gt;The tenant switcher experience&lt;/h2&gt;
&lt;p&gt;The final piece is the user interface. Customers who own multiple businesses need a smooth way to move between accounts.&lt;/p&gt;
&lt;p&gt;I build clean dashboards with Vue, with the frontend talking to the Laravel backend over a GraphQL API for a reactive feel. The tenant switcher is always within reach and shows exactly which context you are working in.&lt;/p&gt;
&lt;h3&gt;Make switching feel instant&lt;/h3&gt;
&lt;p&gt;I cache the tenant configuration in the frontend to avoid needless API calls. These small details separate a basic app from a polished one.&lt;/p&gt;
&lt;figure&gt;
&lt;h2&gt;My Laravel multi-tenancy checklist&lt;/h2&gt;
&lt;p&gt;If you are starting a new project today, here are the steps I recommend:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;strong&gt;Choose your package early.&lt;/strong&gt; I prefer &lt;code&gt;stancl/tenancy&lt;/code&gt; because of its flexibility. It handles subdomain routing and database switching out of the box.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Add global scopes right away.&lt;/strong&gt; Don&apos;t wait until you have ten models. Add the trait to every tenant-scoped model and make it a standard part of your workflow.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Automate your deployment.&lt;/strong&gt; Use Docker from day one so local development matches production. That avoids the &quot;it works on my machine&quot; bugs that plague SaaS launches.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Plan for data migration.&lt;/strong&gt; As your schema changes, you need a way to run migrations across hundreds of databases. Tools like &lt;code&gt;stancl/tenancy&lt;/code&gt; have built-in commands for this.&lt;/li&gt;
&lt;li&gt;&lt;strong&gt;Keep it simple.&lt;/strong&gt; Don&apos;t build a multi-database setup if you only have five users. Start small and scale as revenue grows.&lt;/li&gt;
&lt;/ol&gt;

List every model in your app and mark which ones hold tenant data. Any marked model without the `BelongsToTenant` trait is a leak waiting to happen.


- **Choose isolation early:** a shared database for low cost, a database per tenant for strict isolation.
- **Automate filtering:** a global scope trait on every tenant model stops most leaks.
- **Isolate cache and storage** with tenant-specific prefixes.
- **Stay stateless** so you can scale the web tier horizontally.
- **Automate tenant provisioning and migrations** from the start.

&lt;p&gt;&lt;a href=&quot;https://ansezz.com/services/&quot;&gt;Here&apos;s how I help teams architect and ship multi-tenant SaaS on Laravel&lt;/a&gt;, and you can always &lt;a href=&quot;https://ansezz.com/contact/&quot;&gt;get in touch&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Are you building a SaaS or migrating your current app to a multi-tenant structure, and what is the main technical hurdle you are facing right now?&lt;/p&gt;
&lt;/figure&gt;&lt;/figure&gt;</content:encoded><category>laravel</category><category>laravel</category><category>multi-tenancy</category><category>architecture</category><category>docker</category><category>databases</category></item></channel></rss>