Restify for Laravel for Rust

Restify for Laravel for Rust One definition. Three interfaces.

Write one repository for a model. Restify serves its JSON:API endpoints, describes them in an OpenAPI 3.1 document, and gives AI agents the same operations as MCP tools. One authorize method decides for all three.

A crate for Laravel for Rust, on crates.io as laravel-restify. It is built to answer as Restify for PHP does, so an existing application can move without its clients noticing. Where it stands.

Change the definition Watch the film Read the guides

The definition

A repository lists what a post shows and what clients may search, filter and sort by. Its authorize method says who may do what. Change it below and read what it produces.

It answers requests

JSON:API endpoints for the model, with no routes or handlers to write. Pick a request below. The answer is what the definition allows, and nothing else.

It describes itself

An OpenAPI 3.1 document for API clients and SDK generators, built from the same fields and input structs. There is no second description to keep in sync.

It gives agents tools

Each repository becomes MCP tools. A tool runs the same code as its endpoint, so the same authorize, validation and fields apply to an AI agent.

fields()
listedsearch­ablematch­ablesort­ablehide from index
title
body
votes
created_at
authorize()
Request

This page applies the rules the guides state. It does not run the crate.

01

Start

Build a new backend

Three commands, then one file per model. You write no controllers and no routes.

Create the app and add Restify

Create a Laravel for Rust application:

laravel new my-api --rust

Add the crate. The package is named laravel-restify, and your code imports it as restify:

cargo add laravel-restify

Register the provider in src/app.rs, even before it serves a repository. Restify’s commands come with it, so until then the next command is unknown:

Application::configure()
    .with_providers(|providers| {
        providers.add(restify::Restify::new());
    })

Brief your AI coding agent

laravel restify:install

The command writes two skills into .agents/skills and .claude/skills (where Claude Code finds them as slash commands), and lists them in AGENTS.md. An agent working in the application then knows how a repository is written, and where the guides for your installed version are.

Write one file per model

The file says what clients may send, what a response shows, what is related, and who may do what. This is the comments repository of the example application, src/models/comment.rs: the input that creates a comment, with its validation rules, then the repository’s fields, relationships and authorize.

#[laravel::input(fills = Comment)]
#[validate(authenticated)]
#[derive(Schema)]
pub struct NewComment {
    #[validate(required, exists(Post::id))]
    pub post_id: i64,
    #[validate(required, min_length(2))]
    pub body: String,
}

impl Repository for CommentRepository {
    type Model = Comment;
    type Store = NewComment;
    type Update = EditComment;

    fn fields() -> Vec<Field<Comment>> {
        vec![
            Field::new(Comment::post_id).matchable(),
            Field::new(Comment::body).searchable(),
            Field::new(Comment::created_at),
        ]
    }

    const MCP: Option<McpTools> = Some(McpTools::INDEX.show(true));

    fn related() -> Vec<Related<Comment>> {
        vec![
            Related::through::<UserRepository>(Comment::user, |comment| &comment.user),
            Related::raw(Comment::post),
        ]
    }

    async fn authorize(action: Action, request: &Request, comment: Option<&Comment>) -> laravel::Result<()> {
        match (action, comment) {
            (Action::AllowRestify | Action::Index | Action::Store, _) => Ok(()),
            (Action::Show, Some(comment)) => request.authorize(CommentPolicy::show, comment).await,
            (Action::Update, Some(comment)) => request.authorize(CommentPolicy::update, comment).await,
            (Action::Delete, Some(comment)) => request.authorize(CommentPolicy::delete, comment).await,
            _ => Err(laravel::abort(403)),
        }
    }
}

What that file serves

Register the repository with Restify::new().repository::<CommentRepository>(), and the application answers:

RequestDoes
GET /api/restify/commentsLists a page: ?search=, ?post_id=, ?related=user,post, ?page=, ?perPage=
GET /api/restify/comments/{id}Shows one
POST /api/restify/commentsCreates one
PUT /api/restify/comments/{id}Changes one, checking every field’s rules
PATCH /api/restify/comments/{id}Changes the fields it sends
DELETE /api/restify/comments/{id}Deletes one
laravel restify:openapiPrints the OpenAPI 3.1 document of every endpoint, for API clients and SDK generators
comments-index-tool, comments-show-toolMCP tools: an AI agent lists comments and reads one, under the same authorize

Declare them, and the same file also serves bulk requests, actions and getters, nested routes and file uploads.

02

The whole example

One file per model

A repository is the API of one model. It names the model, the input that creates and updates it, the fields a response shows, which of them clients may search, filter and sort by, and who may do what. You write no routes and no handlers. Registering the repository is enough.

This is the example from the crate’s README: the model, its two input structs, the repository and its registration.

use laravel::model::model;
use laravel::prelude::*;
use laravel::time::Timestamp;
use laravel::validation::Sometimes;
use restify::{Action, Field, McpTools, Repository, Restify, Schema};

#[model]
pub struct Post {
    pub id: i64,
    pub title: String,
    pub body: Option<String>,
    #[default]
    pub votes: i64,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
}

/// What a client sends to create a post. Only these fields can be written.
#[laravel::input(fills = Post)]
#[validate(anyone)]
#[derive(Schema)]
pub struct NewPost {
    /// The post's headline.
    #[validate(required, max_length(255))]
    pub title: String,
    /// The post's text.
    pub body: Option<String>,
}

/// What a client sends to change a post. A field left out keeps its value.
#[laravel::input(fills = Post)]
#[validate(anyone)]
#[derive(Schema)]
pub struct EditPost {
    /// The post's headline.
    #[validate(required, max_length(255))]
    pub title: Sometimes<String>,
    /// The post's text. Send `null` to clear it.
    pub body: Sometimes<Option<String>>,
}

pub struct PostRepository;

impl Repository for PostRepository {
    type Model = Post;
    type Store = NewPost;
    type Update = EditPost;

    /// AI agents may list posts and read one, through the MCP server.
    const MCP: Option<McpTools> = Some(McpTools::INDEX.show(true));

    /// What a post shows, and the columns clients may search, filter and sort by.
    fn fields() -> Vec<Field<Post>> {
        vec![
            Field::new(Post::title).searchable().sortable(),
            Field::new(Post::body).searchable().hide_from_index(),
            Field::new(Post::votes).matchable().sortable(),
            Field::new(Post::created_at),
        ]
    }

    /// Anyone may read posts. Nobody may write them.
    async fn authorize(action: Action, _request: &Request, _post: Option<&Post>) -> laravel::Result<()> {
        match action {
            Action::AllowRestify | Action::Index | Action::Show => Ok(()),
            _ => Err(laravel::abort(403)),
        }
    }
}

pub fn configure() -> laravel::foundation::ApplicationBuilder {
    Application::configure().with_providers(|providers| {
        providers.add(Restify::new().repository::<PostRepository>());
    })
}

That application serves:

RequestDoes
GET /api/restify/postsLists a page: ?search=, ?votes=10, ?-votes=10, ?sort=-votes, ?page=, ?perPage=
GET /api/restify/posts/{id}Shows one
POST /api/restify/postsCreates one
PUT or PATCH /api/restify/posts/{id}Changes one
DELETE /api/restify/posts/{id}Deletes one
POST /mcp/restifyAn MCP server with posts-index, posts-show, posts-store, posts-update and posts-delete tools

A field is one of the model’s typed columns, such as Post::votes. A column that doesn’t exist doesn’t compile. Each value is read with the column’s own type before it reaches the database.

03

Rules

Closed until you open it

A repository refuses every request with 403 until its authorize method allows it. A response shows nothing of the model that no field lists. Clients can write only the fields of the input structs. An API that nobody decided to open stays closed.

Every request, from an application or from an agent, is checked in the same order. The first check that fails answers.

  1. 401 Who is asking. The middleware you give the provider runs before every endpoint and every MCP request.
  2. 403 May they use this repository at all. authorize is asked for Action::AllowRestify before anything is looked up, so a refused request learns nothing of what the repository holds.
  3. 404 Does the record exist. Show, update and delete find the model first.
  4. 403 May they do this. authorize is asked for the action itself, with the model.
  5. 422 Is the input valid. Input is checked against the input struct’s rules.

A list is closed in a quieter way. It searches, filters and sorts only by the fields marked for it, and answers as if any other parameter weren’t there, as Restify for PHP does. The column never reaches the query.

The same request, asked both ways

These go to the example application’s PostRepository: posts behind an API token, where only a post’s author or an admin may change it. An endpoint answers with a status. A tool answers with a result the agent can read, carrying the same status.

  • List posts

    Endpoint

    GET /api/restify/posts?search=rust&sort=-votes
    Authorization: Bearer <token>
    200 { "meta": { "current_page": 1, .. }, "links": { .. }, "data": [ .. ] }

    MCP tool

    posts-index  { "search": "rust", "sort": "-votes" }
    { "isError": false, "structuredContent": { "meta": { .. }, "links": { .. }, "data": [ .. ] } }
  • Ask without a token

    Endpoint

    GET /api/restify/posts
    401 { "message": "Unauthenticated." }

    MCP tool

    POST /mcp/restify   (no Authorization header)
    401. The middleware runs before every MCP request, so no tool runs.
  • Show a post that doesn't exist

    Endpoint

    GET /api/restify/posts/999
    404 { "message": "No query results for model [Post]." }

    MCP tool

    posts-show  { "id": "999" }
    { "isError": true, "content": [{ "type": "text", "text": "An internal server error occurred." }] }
  • Delete someone else's post

    Endpoint

    DELETE /api/restify/posts/1
    { "message": "This action is unauthorized." }

    MCP tool

    posts-delete  { "id": "1" }
    { "isError": true, "content": [{ "type": "text", "text": "This action is unauthorized." }] }
  • Create a post without a title

    Endpoint

    POST /api/restify/posts   { "body": "Text" }
    422 { "message": "The title field is required.", "errors": { "title": ["The title field is required."] } }

    MCP tool

    posts-store  { "body": "Text" }
    { "isError": true, "content": [{ "type": "text", "text": "The title field is required." }] }
  • Filter by a column the repository doesn't mark

    Endpoint

    GET /api/restify/posts?internal_notes=secret
    200 { "meta": { .. }, "links": { .. }, "data": [ .. ] }   the whole list, as if the parameter weren't there

    MCP tool

    tools/list
    posts-index takes search, sort, page, perPage and the columns marked matchable. internal_notes is not among them.

    The column never reaches the query. Restify for PHP does the same, so a client may send extra parameters, such as a cache-buster.

  • Send a field the input doesn't declare

    Endpoint

    POST /api/restify/posts   { "title": "Hello", "is_admin": true }
    201 { "data": { "id": "..", "type": "posts", "attributes": { "title": "Hello", .. } } }

    The endpoint ignores is_admin: it changes nothing unless Store has an is_admin field.

    MCP tool

    posts-store  { "title": "Hello", "is_admin": true }
    { "isError": true, "content": [{ "type": "text", "text": ".." }] }

    The tool's schema refuses fields the struct doesn't declare, so an agent that invents a field gets an error it can read, not a silent success.

04

From PHP

Recorded in PHP, replayed in Rust

41
recordings of the real PHP package
697
requests, replayed in full
4
databases: SQLite, PostgreSQL, MySQL and MariaDB

BinarCode also make Restify for Laravel, the PHP package. The Rust crate has one goal: the same URLs, query parameters, JSON and statuses, so that a team can move an application from PHP to Rust and its frontends, mobile apps and agents keep working unchanged.

Moving an application takes three steps:

  1. In the PHP application, composer require --dev binarcode/laravel-restify-rust-migrate, then php artisan restify:rust-install writes the restify-migrate skill. An AI coding agent can take it from there: type /restify-migrate in Claude Code, or tell another agent “migrate this application to Rust with the restify-migrate skill”. By hand, php artisan restify:export describes the application and php artisan restify:record saves what it really answers.
  2. In a new Laravel for Rust application, restify:import writes the models, repositories, fields, filters and routes in Rust, and MIGRATION.md: a numbered task for each part that is code in PHP, such as the body of a policy.
  3. cargo test --test restify_parity replays PHP’s recorded answers and names every difference. When it passes, point the Rust application at the same database: the tokens and the clients keep working. The whole guide.

The proof is a recording. A blog application on the real PHP package receives a list of requests, and each answer is saved. The Rust application loads the same rows, receives the same requests, and every answer is compared with what PHP said. Any difference fails the test.

ComparedHow
StatusMust be equal.
BodyAs parsed JSON. The order of keys doesn’t matter. The order of items does, and so does the kind of number: 1 is not 1.0.
URLsBy path and query, in the body’s links and in the Location header.
ExceptionsEach one is written down with its reason, and the check fails when a listed exception no longer differs.

Where it stands today

41 recordings, 697 requests in all, replay in full against the Rust version, on SQLite, PostgreSQL, MySQL and MariaDB. They cover lists, search, filters and advanced filters, the filters listing, sorting, grouping, global search, pagination, fields, relationships and nested relationship routes, attaching, detaching and syncing related models, writes, validation, bulk requests, actions, getters, policies, per-repository prefixes, public repositories and middleware, Sanctum tokens, register and login, the profile, soft deletes, and file and image uploads.

A short list of differences is written down where the tests run, each with its reason:

  • Error messages that name a PHP model class: the 404 text, and the 403 text of a refused attach or sync. Rust names the model as it knows it.
  • The text of a 405, and an OPTIONS answer, whose empty body comes without a content type.
  • When a PHP policy lacks a method, PHP’s 403 says so. A Rust repository answers every question in authorize, so it gives a plain refusal.
  • A raw relationship on a list doesn’t load the relationship nested inside it, as PHP does.
  • In the login answer, the authorizedTo… flags are those of a guest in Rust and of the logged-in user in PHP. After register, is_admin is null in PHP and false in Rust.
  • A file field that gets a web address as text instead of a file: PHP saves the address, and Rust refuses it.

The move is also a faster application. A small project tracker was migrated this way and measured against its PHP original: the same data in SQLite on the same disk, a token on every request, 10 connections. PHP ran on nginx and php-fpm with opcache and production settings.

RequestPHPRustRust is
Show one record1,720 a second17,564 a second10.2 times faster
List of 15801 a second3,593 a second4.5 times faster
List of 100 with related data155 a second1,425 a second9.2 times faster
Create a record1,837 a second3,384 a second1.8 times faster
Memory under load384 MiB125 MiBa third

Two answers depend on the database rather than the language: where PostgreSQL puts NULL when sorting, and PostgreSQL refusing to group rows while selecting every column. PHP on PostgreSQL answers as Rust does there.

The MCP tools are recorded too: the same names, the same answers, and a repository turns them on as in PHP. One thing they don’t do: take a file. PHP’s tool can download one from a web address; Rust’s tools leave file fields out. A small Composer package exports a PHP application and records its answers (restify:export, restify:record), and restify:import turns the export into a Rust application, with a task for each part that is code in PHP.

05

Measured

Measured against code written by hand

31–45 MiB
the whole server’s peak memory under load, in every test
¼
of the code of the same endpoints written by hand
33 lines
the Restify repository, which also serves update, delete, bulk requests and the MCP tools

Restify sits on top of Laravel for Rust, which is built on Axum, Tokio and SQLx. To see what Restify itself adds, a benchmark serves the same posts twice: once with endpoints written by hand, once with a Restify repository. Both give the same JSON and run the same database queries.

  • Memory. Under load, the whole server peaked at 31 to 45 MiB in every test. The same as with the endpoints written by hand.
  • Showing or creating one record. No measurable difference from the handler written by hand: any difference was smaller than the run-to-run noise.
  • Database queries. The same on both sides: two for a page, one for a show, one for a create.
  • Code. In the benchmark’s source, the list, show and create written by hand take 135 lines. The Restify repository takes 33 lines, and also serves update, delete, bulk requests and the MCP tools. Both use the same 11-line input struct.
  • Only what you use. The MCP server and the OpenAPI document are Cargo features. An application that doesn’t need one turns it off, and its code leaves the build.

Measured in Docker Desktop on a Mac, with the load tool and the database on the same machine. The numbers mean something only as a comparison between the two sides, not as production figures. No difference smaller than the run-to-run noise is claimed. There are no measurements against Restify for PHP or against any other framework.

The method and every measurement are in the benchmark’s write-up, bench/README.md.

06

Beyond the five

Relationships, actions and bulk requests

Relationships

With ?related=, a client gets a post’s author and comments in the same response. Restify loads each relationship with one query for the whole page, so a list of 15 posts with their authors runs two queries, not sixteen. Only the relationships the repository lists can be loaded. Any other name is ignored.

use restify::{Related, Repository};

impl Repository for PostRepository {
    // ...

    fn related() -> Vec<Related<Post>> {
        vec![
            Related::through::<UserRepository>(Post::user, |post| &post.user),
            Related::through::<CommentRepository>(Post::comments, |post| &post.comments),
            Related::raw(Post::tags),
        ]
    }
}

Actions and getters

Some operations are none of list, show, create, update and delete: “publish this post”, “count the posts”. An action may write and answers POST. A getter only reads and answers GET. Each is an endpoint and an MCP tool, with its own authorize that refuses everything by default.

EndpointMCP tool
Action on one postPOST /api/restify/posts/{id}/actions/publishposts-action-publish
Getter on all postsGET /api/restify/posts/getters/statsposts-getter-stats

Bulk requests, all or nothing

A repository that opts in can create, update or delete many models in one request. Each item goes through the same authorize, validation and hooks as a single request, and all of them run in one database transaction: if one fails, none is saved. An error names the item by its place in the array, from 0:

{
    "message": "A post needs a title.",
    "errors": { "1.title": ["A post needs a title."] }
}
07

Coding agents

Written for the agents that will write with it

Many of the people building with Restify will be AI coding agents. So the guides ship inside the crate and always match the installed version, and one command writes a skill that tells an agent the rules and where the guides are:

laravel restify:install

laravel restify:list --json shows an agent everything an application serves, with the MCP tool names. To give a running agent the tools, point its MCP client at the application. For Claude Code:

claude mcp add --transport http shop https://example.com/mcp/restify --header "Authorization: Bearer <token>"

Mistakes say how to fix them. A compiler error such as “NewPost doesn’t describe itself to AI agents” points to the missing line:

#[laravel::input(fills = Post)]
#[validate(authenticated)]
#[derive(Schema)]
pub struct NewPost { /* .. */ }
08

Status

What is true today

Version 0.2. Open source, on crates.io.

  • On crates.io. Version 0.2 of laravel-restify runs on laravel-rust 0.2, and version 0.1 on laravel-rust 0.1.
  • Open source. The source, the example application, the recordings and the benchmark are in its repository on GitHub, under the MIT licence. The Composer package that exports and records a PHP application, binarcode/laravel-restify-rust-migrate, is on Packagist.
  • It answers as Restify for PHP does, where that is recorded. 41 recordings of the PHP package replay against it, with a short list of documented differences. What they cover, and what differs.
  • The MCP server is built on the official SDK. rmcp, the official Rust SDK for MCP, speaks the protocol. The tools run the same code as the endpoints.
  • Tested as a client would use it. The example application’s tests go through HTTP, on SQLite and on PostgreSQL.

Install it

It needs a Laravel for Rust application with a database driver feature, such as database-postgres, and Rust 1.99 or later. One command adds the crate:

cargo add laravel-restify

Then one line registers a repository:

use restify::Restify;

Application::configure()
    .with_providers(|providers| {
        providers.add(Restify::new().repository::<PostRepository>());
    })
09

Guides

The crate’s own guides

These are the guides that ship inside the crate, copied here as they are today.

Open the guides

For AI tools: llms.txt is a short index, llms-full.txt is every guide in one Markdown file, and each guide is also there as Markdown, such as docs/installation.md.

10

Questions

Short answers

What is Restify for Laravel for Rust?

A Rust crate, laravel-restify, for Laravel for Rust applications. You write one repository per model, and it serves JSON:API endpoints, an OpenAPI 3.1 document and MCP tools for AI agents from it, with the same authorization and validation for all of them.

Can I install it today?

Yes. cargo add laravel-restify adds version 0.2 from crates.io. It needs a Laravel for Rust application on laravel-rust 0.2 with a database driver feature, and Rust 1.99 or later. Restify 0.1 is for laravel-rust 0.1.

Can I move my Restify for PHP application to it?

Yes, with one command and a list of tasks. restify:export describes the PHP application, and restify:import writes the Rust code from it. What is code in PHP, such as the body of a policy method, becomes a numbered task. For the PHP package’s own test application that is 60 tasks. With them done, its 41 recordings replay on SQLite, PostgreSQL, MySQL and MariaDB, apart from a short list of documented differences. The recordings cover lists, filters and advanced filters, global search, grouping, sorting, pagination, relationships, attach, detach and sync, nested routes, writes, validation, bulk requests, actions, getters, per-repository prefixes and middleware, public repositories, Sanctum tokens, soft deletes, and file and image uploads. The MCP tools match PHP’s too.

Do I write routes or handlers?

No. Registering a repository with the Restify provider adds its endpoints and its MCP tools.

Can an AI agent get around my rules?

No. An MCP tool runs the same code as the matching endpoint, so the middleware, authorize, the validation rules and the fields apply to agents exactly as they do to other clients. A refused call comes back as a result the agent can read, with the status the endpoint would answer.

What happens if I forget to write authorize?

Every request is refused with 403. A repository is closed until its authorize method allows an action.

How fast is it?

What was measured is what Restify adds, against the same endpoints written by hand on the same framework. Showing or creating one record, there was no measurable difference. Under load, the whole server peaked at 31 to 45 MiB of memory, the same as the endpoints written by hand, in a quarter of the code. There are no measurements against Restify for PHP or other frameworks. The method and every measurement are in the benchmark’s write-up.

Who makes it?

BinarCode, who also make Restify for Laravel in PHP. It is MIT licensed.