laravel-rust-mcp
README.md
# Laravel Rust MCP Access
MCP for applications built with [Laravel for Rust](https://laravel.com/rust/docs): clients such as Claude Code sign in with a personal token and act as its user. A token never does more than its user, reaches only the areas its owner chose, and every call that changes something is logged.
This is a community package. It is not made, maintained or endorsed by Laravel. Deutsch: [README.de.md](https://github.com/bastianhenneberg/laravel-rust-mcp-access/blob/main/README.de.md).
```rust,ignore
use laravel_rust_mcp_access::{Area, McpAccessServiceProvider};
pub const NOTES: Area = Area::new("notes", "Notes");
providers.add(McpAccessServiceProvider::new([NOTES], tools()));
routing.api(laravel_rust_mcp_access::routes::<User>).api_prefix("");
```
- **A token is its user.** It reaches only the areas its owner chose, and in those only what the user may do there themselves, which your application decides with its own permissions.
- **Safe tokens.** Stored as SHA-256 hashes, compared in constant time, with an expiry, optionally only for reading, at most 20 working ones per holder.
- **Tools are your pages.** Each tool does what a page of your application does, through the same code and the same policy.
- **Everything that changes is logged,** in the same transaction, without passwords, keys and other secrets.
- **Switches for the installation.** MCP as a whole, and each area on, reading only or off, on the package's settings page, as JSON or in the console.
- **Everyone's tokens at a glance.** Pages with every token and the log, filtered, sorted and paged by the server, showing each person only the holders your application lets them see.
## Requirements
- Rust 1.99 or newer
- `laravel-rust` 0.2 with a database driver, and the `features` table (`laravel::feature::table!()`), where the switches are kept
- A `users` table, or whatever holds your tokens. The tests run on PostgreSQL.
| Feature | Default | What it does |
| --- | --- | --- |
| `ui` | no | The settings page, rendered with Inertia, and `laravel mcp-access:ui`. Without it the same routes answer JSON. |
## 1. Install
```sh
cargo add laravel-rust-mcp-access # the endpoint, tokens, log and JSON routes
cargo add laravel-rust-mcp-access --features ui # with the pages
```
With `ui`, run `laravel mcp-access:ui` afterwards: it writes the pages into `resources/js` (see [Pages](#pages)).
The pages are built from your application's [shadcn/ui](https://ui.shadcn.com) components `badge`, `button`, `checkbox`, `dialog`, `field`, `input`, `label`, `radio-group` and `switch`. While one is missing, the command writes nothing and names the ones to add:
```sh
npx shadcn@latest add badge button checkbox dialog field input label radio-group switch
```
## 2. Register the provider
Declare the areas a token may be limited to, in the order your pages show them, and hand them to the provider with your tools:
```rust,ignore
use laravel_rust_mcp_access::{Area, McpAccessServiceProvider};
pub const NOTES: Area = Area::new("notes", "Notes");
// A token reaches this one only when its owner ticks it...
pub const ADMIN: Area = Area::new("admin", "Administration").opt_in();
Application::configure()
.with_providers(|providers| {
providers.add(McpAccessServiceProvider::new([NOTES, ADMIN], tools()));
})
```
The labels may be keys of your translations. `secret_fields(["iban"])` keeps more fields out of the log, `max_tokens_per_holder(5)` changes the limit of 20.
## 3. Migrate
```sh
laravel migrate
```
This creates `mcp_tokens` and `mcp_actions`.
## 4. Connect users
Implement `McpHolder` for whoever holds tokens, usually your user model:
```rust,ignore
use laravel_rust_mcp_access::{Area, McpHolder, USER};
impl McpHolder for User {
async fn mcp_holder(kind: &str, id: i64) -> laravel::Result<Option<Self>> {
if kind != USER {
return Ok(None);
}
User::query().find(id).await
}
fn mcp_holder_id(&self) -> i64 {
self.id
}
fn holder_name(&self) -> String {
self.name.clone()
}
// Checked on every request: whatever keeps the user out of the browser keeps their tokens out too.
fn may_use_mcp(&self) -> impl Future<Output = laravel::Result<bool>> + Send {
std::future::ready(Ok(self.is_active))
}
fn reaches(&self, area: &Area) -> impl Future<Output = laravel::Result<bool>> + Send {
std::future::ready(Ok(*area != ADMIN || self.is_admin))
}
}
```
`speaking`, `translate` and `translate_errors` are optional: they run a request in the user's language and translate the package's texts (keys such as `mcp-access.not_found`) and validation messages.
Tokens and log entries keep the holder's kind and key rather than a foreign key, so the log stays readable after an account is gone. Delete an account's tokens with it: call `revoke_all_of(USER, &ids)` wherever accounts are deleted.
Users needn't be the only holders. Another kind, such as a service account that works only through tokens, implements `McpHolder` too, with its own `holder_kind` and `mcp_holder` answering only for that kind. An enum over both kinds, implementing `McpHolder` by asking whichever it is, is then what the endpoint and the tools work with (`routes::<Actor>`, `Tool<Actor>`).
## 5. What only your application knows
Your tools, who may look after MCP, and whose tokens they see. Mount the endpoint among the API routes, which keep no session and check no CSRF token, and the token pages and the settings under the prefixes and behind the guards of your choice:
```rust,ignore
.with_routing(|routing, _| {
routing.api(laravel_rust_mcp_access::routes::<User>).api_prefix("");
routing.web(|route| {
route
.prefix("/admin")
.middleware(RequirePermission::<User>::new(MANAGE_MCP))
.group(laravel_rust_mcp_access::admin_routes);
route
.prefix("/super-admin")
.middleware(ensure_super_admin)
.group(laravel_rust_mcp_access::settings_routes);
});
})
```
Whose tokens and log entries each person on the token pages sees, and whose tokens they may revoke, your application answers through `McpAdministration` (see [Looking after tokens](#looking-after-tokens)). An application whose only holders are its users and where everyone looks after just their own tokens hands in `OwnTokens`:
```rust,ignore
McpAccessServiceProvider::new([NOTES], tools()).administered_by(OwnTokens::<User>::new())
```
Without either, the token pages show nothing.
## 6. Switch it on
The endpoint answers while the feature flag `mcp-access` is on, and it is from the start. Switched off, the endpoint answers `404`, as a path that doesn't exist, and no tool answers; tokens are kept and work again once it is back on:
```rust,ignore
laravel::feature::deactivate(laravel_rust_mcp_access::endpoint).await?;
```
`laravel mcp-access:disable` and `laravel mcp-access:enable` do the same, and so does the settings page. The pages for looking after tokens and the settings are not behind the switch: tokens can still be revoked while MCP is off, and MCP switched on again.
Apart from the switch, the settings keep each area on, to reading only, or off (`McpSettings`, stored under `mcp-access.areas`). Switching MCP off and on again leaves them as they were.
`laravel_rust_mcp_access::menu()` lists the package's pages you mounted, for your menu, with their label key, link and flag. Show each to whoever passes the guard you mounted it behind.
## Pages
With the `ui` feature the pages come with the crate. Run `laravel mcp-access:ui` after installing and after every update: it writes them to `resources/js/pages/vendor/mcp-access` and `resources/js/vendor/mcp-access`, replacing what an earlier version wrote, and Vite builds them with your own pages. Check the files in.
The command replaces and removes only files that start with its line `// Generated by laravel-rust-mcp-access …`. A file of your own where a page goes, or a symbolic link on the way, stops it before it writes anything, with a message naming the path; a file of your own in those folders stays where it is.
So that no update goes unnoticed, add a test:
```rust,ignore
#[test]
fn the_pages_of_the_packages_are_current() {
laravel_rust_mcp_access::assert_ui_current("resources/js");
}
```
Until the copy matches the crate, it fails with a message that names the files and ends in ``Run `laravel mcp-access:ui`.``
The pages import shadcn/ui's components from `@/components/ui`, where shadcn puts them in every application, and bring their own page header, form sections and dialogs. Their lists are drawn by your application's table, so they look like all of your lists: render the package's pages and components inside `McpAccessUi` and hand it your table.
```tsx
import { McpAccessUi } from '@/vendor/mcp-access/ui';
<McpAccessUi DataTable={DataTable}>{page}</McpAccessUi>
```
`DataTable` takes `McpTableProps` from the same file: columns, rows, a label, the text for no rows, and with `query` and `pages` the server sorts, filters and pages the list. Its `filters` come as data, `McpTableFilter`, a choice among options or a day, so your table draws them with its own filter controls. The pages also need `react` 19 and `@inertiajs/react` 3.
After a change the package flashes a toast, `flash.toast`, whose `message` is a key of its wording, such as `mcp-access.tokens.revoked`. A toast shows on whichever page the change leads to, so the wording of the toasts alone is in `@/vendor/mcp-access/toasts` (`toasts`, by language), small enough to load with every page; the rest of the wording comes with the pages. Look a toast's key up there when your translations have none.
Besides the pages for the tokens, the log and the settings, `vendor/mcp-access/components/McpTokens` has `McpTokensSection`, a user's own tokens with a dialog for a new one and the new token shown once, and `McpTokenList` for an administrator's list. `vendor/mcp-access/components/McpActions` has `McpActionLog`, the log of what tokens did, and `McpActionsSection`, a user's own last entries. The package brings its wording in German and English (`vendor/mcp-access/i18n`); any text can be overridden under the same key in the translations your pages share.
## The endpoint
`POST /mcp` speaks Streamable HTTP without sessions and always answers with JSON. It offers `tools/list` and `tools/call` in protocol version 2026-07-28 and, for older clients, in 2025-11-25 and 2025-06-18. Each request is checked by the rules of its version:
- 2026-07-28 (`server/discover`): each request names its version and the client's capabilities in `_meta`, and its headers `MCP-Protocol-Version`, `Mcp-Method` and, for `tools/call`, `Mcp-Name` (plain or as `=?base64?…?=`) say what the body says, each sent once. Otherwise it gets `400`: `-32020` for a header, `-32602` for `_meta`. Every result names the server in `_meta` as your application's `APP_NAME`, and `tools/list` may be kept only by this token's client and not past the moment (`ttlMs: 0`, `cacheScope: "private"`), because the areas and switches decide what is in it.
- 2025-11-25 and 2025-06-18 begin with `initialize`; every request after it names its version in `MCP-Protocol-Version`.
- A version the server doesn't speak gets `400` with `-32022`, the versions it speaks and the one requested. A body that isn't JSON gets `400` with `-32700`.
- A missing, wrong or expired token, or a user who may no longer use MCP, gets `401` with `WWW-Authenticate: Bearer realm="mcp"`, the same for every reason. Failed attempts are limited to 30 a minute per address.
- A token makes up to 50 requests a minute, the whole minute at once if need be; past that it gets `429` with `Retry-After`, the seconds until it may go on. Bodies are limited to 256 KB, and a browser's request from another origin gets `403`.
- A tool the token may not use answers exactly like one that doesn't exist.
## Tools
A tool implements `Tool<User>`: its name (`area_action`), its area, its `Effect`, a description in the user's language, the JSON Schema of its arguments, and `call`. Check the same policy as the page's handler before reading the arguments, then read them with `arguments::<T>()`, which applies `T`'s rules as a form would (rules that need a request, such as `current_password`, don't run). Errors become the client's answer: `404` as "not found", `403` as a missing permission, `InvalidInput` as the messages by field, anything else as an internal error, which is reported and not shown.
The effect is what a call does: `Effect::Reads`, `Creates` (something new on every call, such as a record or a mail), `Updates` (sets something to what the arguments say) or `Deletes`. Tokens that may only read see only tools that read, every call of the others is logged, and clients learn from it whether a tool is read-only, may overwrite or remove something, and may be called twice safely (`readOnlyHint`, `destructiveHint`, `idempotentHint`), so they ask the user only when it matters.
`call` also gets the request the call came in, as `McpRequest`. Its `extract::<T>()` gives what a handler would get as a parameter of type `T`, such as `Passwords<User>` to send a link.
## The log
A tool that does more than read runs in a transaction together with its entry in `mcp_actions` (`McpAction`), and a call that fails is logged after the rollback. The entry keeps only the arguments the tool's schema declares, without secrets, after Rails' `filter_parameters` and the OWASP Logging Cheat Sheet. A field is secret, whatever the case, when its name contains `passw`, `passphrase`, `secret`, `token`, `crypt`, `credential`, `authorization`, `bearer`, `cookie` or `certificate`; when one of its words is `pwd`, `apikey`, `otp`, `totp`, `pin`, `jwt`, `salt`, `ssn`, `cvv`, `cvc`, `sid`, `dsn` or `mnemonic`; when it ends in the word `key` or `code` (`api_key`, `privateKey`, `recovery_codes`), but not after a word such as `primary`, `sort`, `zip` or `status`; or when it names a session (`session`, `session_id`, but not `session_count`). Its texts and numbers become `[removed]`, nested ones included, while `true`, `false` and `null` stay, so a switch such as `password_reset` still shows. Long texts are shortened and anything above 4 KB is replaced by its size. Call `prune(before)` from a scheduled task to delete the entries made before `before`; one made exactly then stays.
A change a person makes in the browser to a holder who works only through tokens belongs in the same log, so that it tells the whole story of that holder: `record_from_browser(&me, &holder, "service_accounts_update", arguments)` writes an entry with the source `Web`, no token, and `me` under `by` in its arguments.
## Looking after tokens
The token pages ask your application, through the `McpAdministration` you hand to `administered_by`, before they read any filter or touch any token:
```rust,ignore
impl McpAdministration for Administration {
type Admin = User;
async fn visible(&self, admin: &User) -> laravel::Result<Visible> {
// Everyone's but the super admins', within the list's own query...
let hidden = User::query().filter(User::is_super_admin.eq(true)).select_column(User::id);
Ok(Visible::Except(vec![HolderIds::new(USER, hidden)]))
}
async fn describe(
&self,
admin: &User,
holders: Vec<Holder>,
asking: Asking,
) -> laravel::Result<HashMap<Holder, Described>> {
// The holders still there that `admin` may see: their name, where to see them, and whether
// `admin` may revoke their tokens...
}
}
```
- `visible` says whose tokens and entries a person may learn of: `Everyone`, everyone's `Except` holders a query selects, or `Only` some. The lists, their counts and their filters leave out everyone else.
- `describe` names the holders on a page. One it leaves out is left out of the page, and revoking its tokens, or asking for it by id, answers `404`; one it describes with `may_revoke: false` shows without the button, and revoking answers `403`. Whether they may revoke is only asked with `Asking::Revoking`: the log asks `Asking::Names` and needn't pay for it.
- `may_name_without_tokens`, `kind_label`, `made_by` and `revoked` have defaults: a filter keeps a holder's name only while it holds a token, a holder has no kind next to its name, the log shows who changed something in the browser by their name, and nothing happens after revoking.
A holder appears in URLs and filters as `<kind>:<id>`, such as `user:5`.
## Tokens
`issue(&user, NewToken { .. })` makes a token and returns it once in plain text as `cm_<id>_<secret>`. Prove first that whoever asks is the user, such as with their password. The errors of `issue` are the texts `AREAS_REQUIRED`, `AREA_CLOSED` and `TOO_MANY_TOKENS`; translate them by these texts. `tokens_of(&user)` lists a user's tokens, and `ListedToken` is a token as a page shows it, with the URL that revokes it.
## The routes
| Method | Path | With `ui` | As JSON |
| --- | --- | --- | --- |
| POST | `/mcp` | – | the endpoint, among the API routes |
| GET | `/mcp/settings` | the settings page | the switches and every area with its state |
| PUT | `/mcp/settings` | back to the page | the switches as stored |
| GET | `/mcp/tokens` | everyone's tokens | the tokens with their filters and pages |
| DELETE | `/mcp/tokens/{mcp_token}` | back, with a toast | 204 |
| DELETE | `/mcp/holders/{kind}/{id}/tokens` | back, with a toast | 204 |
| GET | `/mcp/actions` | the log | the entries with their filters and pages |
`routes` mounts `/mcp`, `admin_routes` the token pages and `settings_routes` the settings.
`/mcp/settings` takes `{ "enabled": true, "areas": { "notes": "read_only" } }`; an area not named is on, a name no area has is ignored. A client that asks for JSON (`Accept: application/json`) always gets JSON.
## Console
| Command | What it does |
| --- | --- |
| `laravel mcp-access:issue-token <user> <name> --area <area>… [--expires month\|quarter\|year\|never] [--read-only]` | Issues a token to a user and prints it once. |
| `laravel mcp-access:tokens [--user <user>]` | Lists the tokens, newest first. |
| `laravel mcp-access:revoke-token <id>` | Revokes a token. |
| `laravel mcp-access:log [--limit <n>]` | Shows the latest entries of the log. |
| `laravel mcp-access:enable` / `laravel mcp-access:disable` | Switches MCP on or off. |
| `laravel mcp-access:ui` | Writes the pages into `resources/js` (with `ui`). |
A token issued in the console reaches no more than its user may, like one issued on a page.
## Without Inertia
Leave the `ui` feature off: the endpoint and its tools don't need it, the routes of the settings and of looking after tokens answer JSON (see [The routes](#the-routes)), and the core's Rust functions serve pages of your own. A user's tokens, in a plain HTML view `resources/views/tokens/index.html`, and a new one shown once:
```rust,ignore
use laravel::auth::Auth;
use laravel::prelude::*;
use laravel::view::{View, data, view};
use laravel_rust_mcp_access::{Expiry, NewToken, issue, tokens_of};
pub async fn index(auth: Auth<User>) -> laravel::Result<View> {
let me = auth.user().await?.or_abort(401)?;
let tokens = tokens_of(&me).await?;
Ok(view("tokens.index", data! { tokens }))
}
pub async fn store(auth: Auth<User>) -> laravel::Result<View> {
let me = auth.user().await?.or_abort(401)?;
let new = NewToken { name: "Laptop".into(), expiry: Expiry::Quarter, read_only: true, areas: vec!["notes".into()] };
// The secret is in `plain` this once and never again.
let issued = issue(&me, new).await?;
Ok(view("tokens.created", data! { plain => issued.plain }))
}
```
For everyone's tokens and the log, `oversight::tokens::list` and `oversight::actions::list` take the `Visible` your `McpAdministration` answers and a filter, as the pages do.
## Updating
After `cargo update`, run `laravel mcp-access:ui` with `ui`, so the pages in `resources/js` match the new version; `assert_ui_current` fails until you do.
## Limitations
- **A soft token limit.** Counting and creating take no lock, so two requests at the same moment may end one over the limit. It is there to stop tokens piling up, not to count them exactly.
- **No sessions, no notifications.** The endpoint answers each request on its own; it sends nothing unasked.
## Developing
```sh
cargo clippy --all-targets --all-features --locked -- -D warnings
cargo test --all-features --locked # needs PostgreSQL at DATABASE_URL
cargo test --no-default-features --locked # without the pages
cargo deny check
scripts/rust-like-ci.sh # CI's Rust jobs with the Rust CI pins, in Docker, with its own PostgreSQL
npm ci && npm run types:check && npm run check && npm test # the pages, against stand-ins for shadcn/ui
```
## License
MIT. See `LICENSE`.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues