# Protecting routes (laravel-rust-mcp-oauth)

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

- Package: laravel-rust-mcp-oauth (Laravel for Rust, alpha), crates: `laravel-rust-mcp-oauth`
- Maintenance: active; Latest release: 0.1.0 (2026-12-05); Framework: laravel-rust 0.2.x; MSRV: Rust 1.99 or later; Licence: MIT
- Links: [Repository](https://github.com/bowerbird-si/laravel-rust-mcp-oauth), [crates.io](https://crates.io/crates/laravel-rust-mcp-oauth/0.1.0), [docs.rs](https://docs.rs/laravel-rust-mcp-oauth/0.1.0), [Changelog](https://oss.bowerbird.si/mcp-oauth/docs/changelog/), [Contributing](https://github.com/bowerbird-si/laravel-rust-mcp-oauth/blob/8b1d066397c9f1a1cf02d444a910a1c65585c159/CONTRIBUTING.md), [Security policy](https://github.com/bowerbird-si/laravel-rust-mcp-oauth/blob/8b1d066397c9f1a1cf02d444a910a1c65585c159/SECURITY.md)
- Based on: [Laravel MCP](https://github.com/laravel/mcp): The public flow of Mcp::oauthRoutes(): discovery, client registration, an approval screen in your app and bearer tokens for the MCP server.; [Laravel Passport](https://github.com/laravel/passport): The authorization server Laravel MCP builds on. This crate needs no Passport, supports Client ID Metadata Documents and uses opaque, hashed tokens instead of JWTs.; [MCP authorization specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization): The sign-in flow MCP clients expect, with Client ID Metadata Documents preferred over dynamic registration.
- Community package, not affiliated with Laravel.
- HTML version: https://oss.bowerbird.si/mcp-oauth/docs/protecting-routes/
- Source: https://github.com/bowerbird-si/laravel-rust-mcp-oauth/blob/8b1d066397c9f1a1cf02d444a910a1c65585c159/docs/protecting-routes.md

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

## The middleware

```rust
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

| Case | Status | `WWW-Authenticate` |
| --- | --- | --- |
| No token | 401 | `Bearer resource_metadata="…", scope="mcp offline_access"` |
| Invalid, expired or revoked token, or a user `can_use` refuses | 401 | the same, with `error="invalid_token"` and a description |
| A required scope is missing | 403 | `Bearer error="insufficient_scope", scope="<missing>", resource_metadata="…"` |
| The database can't be read | 503 | none; `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](https://github.com/laravel/rust-framework/pull/321), which is unreleased, and compatibility is still unverified. This example shows how tools are intended to use `#[extract]` once that server ships.

```rust
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.

```rust
#[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`.

```rust
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:

```rust
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`.
