Protecting routes

laravel-rust-mcp-oauth Alpha Laravel for Rust

McpAuthenticate checks the bearer token on your MCP route and gives your tools the grant and the user who approved it.

The middleware

use laravel_rust_mcp_oauth::McpAuthenticate;

McpAuthenticate::<User>::new()
    .allow_guest_methods(["server/discover"]) // JSON-RPC methods that work without a token
    .require_scopes(["mcp"])                   // every request needs these scopes
    .allowed_origins(["https://inspector.example"]) // more browser origins besides APP_URL's

For each request it:

  1. answers OPTIONS itself with 204 and Allow: GET, POST, DELETE, OPTIONS;
  2. refuses a request whose Origin header is present and isn't your APP_URL's origin or an allowed one. Native clients send no Origin and pass. This stops DNS rebinding attacks;
  3. allows a guest method only in an application/json POST with one JSON-RPC 2.0 message. Content type parameters such as charset=utf-8 are allowed. The route still receives the original body;
  4. checks the bearer token, its grant and its user, and asks your can_use hook;
  5. checks the required scopes;
  6. puts the grant and the user in the request, and runs your route.

It checks everything before your MCP server runs. An MCP server turns errors inside a tool into tool results, so a scope check inside a tool couldn't give the client the HTTP 403 it needs to ask for more access.

Its answers

CaseStatusWWW-Authenticate
No token401Bearer resource_metadata="…", scope="mcp offline_access"
Invalid, expired or revoked token, or a user can_use refuses401the same, with error="invalid_token" and a description
A required scope is missing403Bearer error="insufficient_scope", scope="<missing>", resource_metadata="…"
The database can't be read503none; Retry-After: 5

Errors return JSON, {"error": "...", "error_description": "..."}, with Cache-Control: no-store. The 503 matters: a 401 during a database outage would make every assistant throw away its token and ask its user to sign in again.

For OPTIONS with an allowed Origin, the guard echoes the origin and allows the methods in Allow. It allows the headers authorization, content-type, mcp-protocol-version, mcp-session-id and last-event-id, with a 600-second preflight cache lifetime. Other OPTIONS requests receive 204 without CORS headers.

The 401 challenge lists the route's required scopes. When the route has none, it lists only the default scope, the first configured scope. It always includes offline_access once. Set the description of the 401 with MCP_OAUTH_UNAUTHORIZED_MESSAGE.

The grant and the user in your tools

McpGrant and McpUser<U> work in route handlers, including handlers serving rmcp. The middleware is designed for Laravel's first-party MCP server, which is unreleased, and compatibility is still unverified. This example shows how tools are intended to use #[extract] once that server ships.

use laravel_rust_mcp_oauth::{McpGrant, McpUser};

#[mcp::tool(read_only)]
pub async fn list_projects(#[extract] user: McpUser<User>, #[extract] grant: McpGrant) -> laravel::Result<Vec<Project>> {
    // grant.id(), grant.client_id(), grant.client_family(), grant.scopes(), grant.can("mcp:write")
    Project::for_owner(&user).await
}
  • McpUser<U> is the user the middleware already checked. It costs no extra query.
  • grant.client_family() is an analytics label from a known CIMD client ID or selected known callback. Other clients are labeled other. Use grant.id() or the authenticated user for enforcement such as rate limits.
  • On a route without McpAuthenticate both extractors fail with a 500 that names the middleware.

Tools for some scopes only

In the proposed first-party MCP API, when hides a tool unless its condition passes. This example shows the intended usage with a grant once the server ships.

#[mcp::tool(when = can_write)]
pub async fn save_project(#[extract] user: McpUser<User>, name: String) -> laravel::Result<String> { /* ... */ }

async fn can_write(grant: McpGrant) -> laravel::Result<bool> {
    Ok(grant.can("mcp:write"))
}

A hidden tool answers a direct call with JSON-RPC -32602, not an HTTP 403. When a missing scope must make the client ask for more access, put it in require_scopes instead.

Auth<User>

On Laravel for Rust 0.2 a package can't mark a request as authenticated, so Auth<User> doesn't see the MCP user yet. Use McpUser<U>. Once a framework release lets packages set the request user (laravel/rust-framework#340), McpAuthenticate will set it too.

McpTokens<U> is also available as a request guard for routes with no guest methods. A token store outage returns HTTP 503 with Retry-After: 5.

route.middleware(Authenticate::via::<McpTokens<User>>())

Suspending users

The can_use hook runs on every protected request, so a suspended user's assistants stop working at once:

McpOAuthServiceProvider::<model::Users<User>>::new()
    .can_use(|user: User| async move { Ok(!user.suspended) })

Token and grant are read from the database's writer connection, so a revocation is seen at once even with read replicas. Your user provider may read from a replica; if suspension must take effect at once, read it from the writer in can_use.