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

推荐订阅源

L
LangChain Blog
博客园_首页
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
S
SegmentFault 最新的问题
量子位
Apple Machine Learning Research
Apple Machine Learning Research
博客园 - 司徒正美
博客园 - Franky
Google DeepMind News
Google DeepMind News
Recent Announcements
Recent Announcements
B
Blog RSS Feed
C
Check Point Blog
The Cloudflare Blog
M
MIT News - Artificial intelligence
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
F
Fortinet All Blogs
Hugging Face - Blog
Hugging Face - Blog
博客园 - 叶小钗
V
Visual Studio Blog
V
V2EX
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - 聂微东
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

DEV Community

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

Exposing your app to an AI agent over MCP is basically handing someone a master keyring and trusting them to only open the doors they're supposed to. That trust is a bug waiting to happen. This week I wired up a batch of MCP tools over a multi-tenant Laravel app, and the whole exercise was really about one question: how do I let an agent drive the app without letting it drive someone else's data?

Here's the thing about MCP tools — each one is an endpoint. An agent calls list_events, publish_event, check_in_participant, and your server runs code on the caller's behalf. The moment you have more than one tenant, every single tool needs to answer two questions before it does anything: are you allowed to do this, and are you allowed to do it *here*. Authorization and scope. Skip either and you've built a confused deputy.

The trap: ambient scope doesn't exist under token auth

In a normal web request, multi-tenancy is comfortable. You've got a logged-in user, a global scope on the model that quietly appends where organization_id = ?, and you mostly forget it's there. Everything Just Works because there's an ambient "current organization" sitting in the session.

MCP tools don't have that. The caller authenticates with a token, there's no session, no middleware stack that set up a current-tenant context. If you lean on a global OrganizationScope that reads "the current org" from somewhere, it reads nothing — and a query you assumed was fenced returns every tenant's rows. That's the kind of bug that doesn't throw an error; it just silently leaks.

So the rule I settled on: under token auth, never rely on ambient scope. Filter explicitly, every time, in one place.

That "one place" is a small trait every event-scoped tool pulls in:

trait ResolvesOrgEvents
{
    protected function resolveOrgEvent(Authenticatable $user, string $uuid): ?Event
    {
        if (empty($user->organization_id)) {
            return null;
        }

        return Event::query()
            ->withOrganization($user->organization_id)
            ->where('uuid', $uuid)
            ->first();
    }
}

Nothing clever — and that's the point. The org filter isn't a global scope you hope is active; it's a named query scope (withOrganization) applied by hand, living in exactly one trait. Every tool that resolves an event by UUID goes through this. If the resolution returns null, the tool answers "not found in your organization" and stops. An agent poking at a UUID from another tenant gets the same response as a UUID that doesn't exist — no oracle, no leak.

Notice the lookup is by UUID, not auto-increment ID. Public identifiers should be unguessable. An agent (or a prompt-injected one) shouldn't be able to enumerate event/1, event/2, event/3. The internal numeric key never leaves the database.

Authorization: one ability per tool, checked the same way as the web app

Scope keeps you in your tenant. Authorization decides what you can do within it. I gave every tool a single declared ability:

#[Name('event_readiness_check')]
#[Description('Check whether an event is ready to publish. Returns ready=true/false and blocking issues.')]
#[IsReadOnly]
class EventReadinessCheckTool extends McpKitTool
{
    use ResolvesOrgEvents;

    protected function ability(): string
    {
        return 'events.view.details';
    }

    public function handle(Request $request): Response
    {
        $user = $this->authorizedUser($request);

        if ($user === null) {
            return $this->unauthorized();
        }

        $validated = $request->validate([
            'event' => ['required', 'string', 'max:36'],
        ]);

        $event = $this->resolveOrgEvent($user, $validated['event']);

        if ($event === null) {
            return Response::error('Event not found in your organization.');
        }

        // ... do the read-only work
    }
}

A few deliberate choices here.

The ability() method is the tool's contract — it says, in one line, "you need this permission to call me." The base McpKitTool does the gate-check in authorizedUser(), so the permission logic isn't copy-pasted into every handle(). And crucially, it's the same ability string the web app and the underlying action already use. The readiness check leans on events.view.details; the publish flow leans on the same gate the lifecycle action enforces. One permission model, three entry points (web, action, MCP). I'm not maintaining a second, parallel "what can the agent do" matrix that drifts out of sync with the real one — that drift is exactly how an agent ends up more privileged than the human behind it.

The #[IsReadOnly] annotation is a small honesty signal. Read tools and write tools get marked differently, so a client can reason about which calls have side effects. list_events and event_readiness_check are read-only; publish_event is not. It's cheap to annotate and it makes the destructive surface explicit.

And the input still goes through $request->validate(). The agent is an untrusted client like any other — max:36 on a UUID field isn't paranoia, it's the same hygiene you'd apply to a public form request.

The shape that emerged

Once a couple of tools existed, the pattern crystallized and the rest were almost mechanical:

  • List first. list_events is the entry point — it's the only tool that doesn't take a UUID, because it's how the agent gets UUIDs. It's org-filtered the same explicit way, so the agent's whole world is its own tenant from the first call.
  • Resolve through the trait. Every event-scoped tool resolves via resolveOrgEvent. The fence lives in one file.
  • Gate on a real ability. Reuse the app's permission strings, don't invent agent-only ones.
  • Annotate side effects. Read vs write is declared, not implied.

That uniformity matters more than any single tool. When fifteen tools all follow the same four rules, you can audit the rules instead of auditing fifteen handle() methods.

Worth a test

The org-fencing is the kind of thing that's easy to get right today and quietly break in six months when someone "optimizes" a query. So it gets a Pest test that asserts the boundary directly — not "does the happy path work" but "does the wrong tenant get nothing":

it('never resolves an event from another organization', function () {
    $mine = Event::factory()->for($orgA)->create();
    $theirs = Event::factory()->for($orgB)->create();

    $user = User::factory()->for($orgA)->create();

    expect(resolveOrgEvent($user, $mine->uuid))->not->toBeNull()
        ->and(resolveOrgEvent($user, $theirs->uuid))->toBeNull();
});

it('returns null when the user has no organization', function () {
    $user = User::factory()->create(['organization_id' => null]);

    expect(resolveOrgEvent($user, Event::factory()->create()->uuid))
        ->toBeNull();
});

The second case — a user with no org context — is the one people forget. Under token auth you can absolutely end up with an authenticated principal that isn't attached to a tenant, and "no org" must mean "no access," not "all access by accident."

Takeaway

MCP makes it genuinely easy to expose your app to an agent — maybe a little too easy. The mechanics of registering a tool are trivial; the discipline is all in the boundaries. Treat every tool as an untrusted endpoint: explicit tenant scope (never ambient, under token auth), one declared ability per tool that reuses your existing permission model, UUIDs over enumerable IDs, and read/write honesty baked in. Put the fence in one trait so there's a single place to get it right — and a single place to test.

An agent should be able to do everything the human behind it can do, in exactly the tenant they belong to, and nothing more. That's not an AI problem. It's the same multi-tenancy and authorization discipline we've always needed — MCP just removes every excuse for being sloppy about it.