Docs / Agents and tooling
MCP
the tools AI agents get, and how to connect an agent.
Introduction #
Restify serves a Model Context Protocol server at POST /mcp/restify. AI agents use it to list, read, create, change and delete your records, and to run your actions and getters.
It answers as Restify for PHP's MCP server does: the same tool names, arguments, hints and results. An MCP client set up for a PHP Restify application keeps working against a Rust one.
A tool runs the same code as the matching endpoint. authorize, query, the validation rules and the fields apply to agents exactly as they do to other clients.
Middleware apply too, but differently. The server's route is behind the provider's middleware, so Restify::authenticate and Restify::middleware run on every MCP request. A repository's own middleware() runs before each of its tools, as a check: it may refuse the tool or change the request, but code it runs after next.run(request) doesn't run there. The global-search tool runs the middleware of each repository it searches, and one refusal refuses the whole search. See Where the middleware run.
Nothing is served until you allow it. A repository opts in with const MCP.
The server is the crate's mcp feature, on by default. An application that serves no agents may turn it off to leave out its code and the rmcp crate: see Choosing features.
Letting agents use a repository #
Set const MCP on the repository. McpTools::INDEX allows the list only, which is what PHP's HasMcpTools trait allows by default. McpTools::ALL allows everything:
impl Repository for PostRepository {
// ...
/// Agents may do everything with posts that the endpoints allow.
const MCP: Option<McpTools> = Some(McpTools::ALL);
}
To allow some operations, turn them on with McpTools::INDEX and the method named after each operation:
impl Repository for CommentRepository {
// ...
/// Agents may list comments and read one.
const MCP: Option<McpTools> = Some(McpTools::INDEX.show(true));
}
| Field | Allows | PHP method |
|---|---|---|
index | The list | mcpAllowsIndex |
show | One record | mcpAllowsShow |
store | Creating | mcpAllowsStore |
update | Changing | mcpAllowsUpdate |
delete | Deleting | mcpAllowsDelete |
actions | Each action | mcpAllowsActions |
getters | Each getter | mcpAllowsGetters |
A repository without const MCP has no tools. Its relationships are also left out of what the tools of other repositories return.
The repository you pass to Restify::profile also gets a profile tool, when it sets const MCP.
To give agents fewer fields than other clients, use hide_from_mcp on a field, or return other fields for View::McpIndex and View::McpShow from fields_for. See Fields.
Choosing a mode #
The server lists its tools in one of two ways, as PHP's mcp.mode does. Set RESTIFY_MCP_MODE:
| Mode | tools/list shows | Best for |
|---|---|---|
wrapper, the default | global-search, and four tools that find and run every operation | Many repositories: the agent's tool list stays short |
direct | global-search, and one tool per operation of each repository | Few repositories: the agent sees every operation at once |
Both modes serve the same operations to the same users, and both run the same code.
Read-only mode #
Set RESTIFY_MCP_READ_ONLY=true to let agents read but never write, as PHP's mcp.read_only does. The tools that create, update or delete, and every action, are no longer served:
- In
directmode, they aren't listed, and calling one answers as an unknown tool. - In
wrappermode,discover-repositoriesandget-repository-operationsdon't show them.get-operation-detailsanswersOPERATION_DETAILS_ERROR, andexecute-operationanswersAUTHORIZATION_ERROR.
Getters still run: they only read.
The tools in direct mode #
For a repository named posts, after global-search:
| Tool | Does | Arguments | Hint |
|---|---|---|---|
posts-index-tool | Lists a page | page, perPage, include, search, sort, and each filter column | readOnlyHint |
posts-show-tool | Returns one | id, include | readOnlyHint |
posts-store-tool | Creates one | The fields of Store, include | none |
posts-update-tool | Changes one | id, the fields of Update, include | idempotentHint |
posts-delete-tool | Deletes one | id | destructiveHint, idempotentHint |
posts-{key}-action-tool | Runs an action | resources for an action on the list, id for one on a single record, and the fields of its input | openWorldHint, and destructiveHint set to the action's DESTRUCTIVE |
posts-{key}-getter-tool | Runs a getter | id for a getter on a single record, and the fields of its input | readOnlyHint |
users-profile-tool | Returns the logged-in user's profile | include | readOnlyHint |
An action's tool says whether it destroys data: destructiveHint is true when the action sets const DESTRUCTIVE: bool = true, and false otherwise. Restify for PHP leaves the hint out, and the protocol reads a missing destructiveHint as true, so to an agent every PHP action looks destructive. This is a deliberate difference. The wrapper tools show the same hints under annotations.
Each tool's title is the repository's name and the operation, such as Posts Index. An action or getter's title is its name. The profile tool's title is Profile Tool.
The list arguments mean what the query string parameters mean in Filtering. include names relationships, as ?related= does in Relationships. A repository that declares no sortable field may still be sorted by its key, such as sort=posts.id. The schemas of the store and update tools come from #[derive(Schema)] on the input structs, as Writing describes.
An action or getter whose can_see refuses the user isn't listed for that user, and calling it answers as an unknown tool.
To see the tools an application serves, run laravel restify:list --json.
The tools in wrapper mode #
After global-search:
| Tool | Does | Arguments |
|---|---|---|
discover-repositories | Lists the repositories the user may use, with their operations | search, optional |
get-repository-operations | Lists one repository's operations, actions and getters | repository |
get-operation-details | Returns one operation's arguments as a JSON Schema, with examples | repository, operation_type, and operation_name for an action or getter |
execute-operation | Runs one operation | repository, operation_type, operation_name for an action or getter, and parameters |
operation_type is one of index, show, store, update, delete, profile, action and getter. operation_name is the action or getter's key, such as publish-posts-action. parameters holds the arguments that the matching direct-mode tool takes.
For example, an agent lists posts with:
{
"repository": "posts",
"operation_type": "index",
"parameters": { "perPage": 5, "sort": "-votes" }
}
Searching every repository #
Both modes list global-search first, as PHP does. It runs the same search as GET /api/restify/search, described in Global search, with the agent's search argument:
{ "search": "rust" }
It answers with the results, how many there are, and the repositories it searched. Shortened, from the example app:
{
"results": [
{ "repositoryName": "posts", "repositoryTitle": "Posts", "title": "Rust ownership explained",
"subTitle": "20 votes", "repositoryId": 4, "link": "/api/restify/posts/4" }
],
"total": 1,
"searched_repositories": [{ "name": "posts", "title": "Posts" }]
}
The tool doesn't need const MCP. It searches exactly the repositories that Restify::global_search::<R>() added, which also answer /search. So the tool is always listed, but it finds nothing until a repository is added. This differs from PHP, where every repository is searched unless it opts out. The limit argument is accepted and ignored, as in PHP: each repository returns at most its GlobalSearch::RESULTS. The tool reads, so read-only mode keeps it.
What a tool returns #
A successful call returns JSON twice: as structuredContent, and as the text of its one content block. global-search is the one exception: as in PHP, it returns the JSON only as text.
| Operation | Returns |
|---|---|
| List | The same document as the endpoint, with data, meta and links. The page URLs in links and meta.path are the MCP server's, such as https://example.com/mcp/restify?page=2, as in PHP: they lead nowhere, so page with the page argument |
| Show | The resource itself: id, type, attributes, relationships and meta, without the data key |
| Create, update | { "data": { ... } }, with only the attributes the input may write, and the relationships include names |
| Delete | { "id": "1", "deleted": true }, with the id as the agent sent it |
| Action | { "success": true, "action": "publish-posts-action", "result": { ... } }, where result is what handle answered |
| Getter | { "success": true, "getter": "stats", "result": { ... } } |
| Profile | The users list, as the list tool returns it |
An action whose can_run refuses the user is not a failed call. It returns { "error": "...", "action": "publish-posts-action" } with isError: false.
The wrapper tools return what the matching direct-mode tool returns. discover-repositories, get-repository-operations and get-operation-details return JSON that lists what they found and a next_steps list for the agent.
When a call fails #
A failed call is a result with isError: true and one text block, so the agent can read the reason and correct itself.
In direct mode, the text is what Laravel's MCP server says for the error:
| Error | Text |
|---|---|
| Invalid input | Every validation message, joined with spaces, such as A post needs a title. The votes field must be at least 0. |
Refused by authorize or a policy | This action is unauthorized. |
| No logged-in user | Unauthenticated. |
| Anything else, a missing record included | An internal server error occurred. The details are in the application's log |
In wrapper mode, the text is a JSON object with an error message and a code. A validation error also has errors, the messages of each field:
{
"error": "Validation failed",
"code": "VALIDATION_ERROR",
"errors": { "title": ["A post needs a title."] }
}
| Code | Means |
|---|---|
MISSING_PARAMETER | repository, operation_type or operation_name is missing |
INVALID_REPOSITORY | The repository doesn't exist, doesn't set const MCP, or the user may use none of its operations |
INVALID_OPERATION | The repository doesn't serve that operation to this user, or operation_type is unknown. An unknown type, action or getter is answered with the names that are valid |
INVALID_PARAMETERS | parameters isn't an object |
VALIDATION_ERROR | The input is invalid |
AUTHORIZATION_ERROR | The user may not run the operation, or read-only mode refuses it |
NOT_FOUND | The record doesn't exist |
EXECUTION_ERROR | Anything else. The details are in the application's log |
OPERATION_DETAILS_ERROR | get-operation-details failed, or read-only mode refuses the operation |
For example, operation_type: "export" answers Unknown operation_type "export". Valid operation types: index, show, ..., and an action the user may not run answers Unknown action "archive-posts-action" on "posts". Valid action names: publish-posts-action, export-posts-action., in the same words as Restify for PHP.
Behaviour kept from Restify for PHP #
Agents written for PHP Restify rely on these, so the crate keeps them:
- An action on the list reads its records from
repositories. Its schema asks forresources, but the tool ignores that argument. Withoutrepositories, the action runs on no record.repositoriesmay be a list of ids or a JSON text of one, such as"[1, 2]". - The profile tool returns the users list, not only the logged-in user. It runs the list with the user's id as an argument that the list doesn't read. It passes the agent's other arguments on to the list too. It exists whenever the profile's repository sets
const MCP, even whenMcpTools.indexisfalse. It asksAction::Indexand shows what the list would show this user. So it reveals nothing the users list doesn't, but an agent may see every user. Safe setup: narrow the users inUserRepository::queryforAction::Index, such as to the user alone for users who aren't admins. Or don't give the user repositoryconst MCP. global-searchsearches every repository added withRestify::global_search, including those withoutconst MCP, and its description names their searchable columns. Safe setup: add a repository to the global search only if agents may read its rows. Rows are still filtered byAllowRestify,queryandShowfor each request.- In
directmode,tools/listlists every repository's tools, including those whoseAction::AllowRestifyrefuses the user. A listed tool only shows names and input schemas. Calling it still asksAllowRestifyand refuses. Safe setup: keep a repository that some users may never use out of the MCP server (noconst MCP), or usewrappermode, whosediscover-repositoriesleaves those repositories out. - The update tool changes a record as
PUTdoes. Its schema marks the fields that a full update needs as required, and leaving one out is a validation error. - A missing record is an internal error in direct mode, not a "not found" error.
- The input ignores arguments it doesn't declare, as the endpoints do.
Connecting an agent #
The server speaks Streamable HTTP. Point an MCP client at the application's URL and send the API token as a bearer token. For Claude Code:
claude mcp add --transport http shop https://example.com/mcp/restify --header "Authorization: Bearer <token>"
Change the path with Restify::new().mcp("/mcp/shop"), and turn the server off with .without_mcp().
Calling the MCP server from a browser #
The server refuses a request whose Origin header names another site, with 403, as the MCP specification requires of a Streamable HTTP server. A browser sends that header, so this protects a server on a developer's machine from a web page in their browser, which could otherwise reach it through DNS rebinding. Agents and other clients that aren't browsers send no Origin, and pass.
The server's own origin passes: the scheme, host and port of the request, such as https://example.com. A page anywhere else, such as a frontend on http://localhost:5173 calling an API on http://localhost:8000, gets:
{ "jsonrpc": "2.0", "error": { "code": -32600, "message": "The request's origin isn't allowed." } }
To let your own frontend call the server, list its origin in the framework's CORS settings, src/config/cors.rs, and add the server's path to paths. The browser needs that anyway, for the preflight request it sends before a POST with Content-Type: application/json. The server accepts every origin that origins lists, with * as a wildcard, and every origin that origin_patterns matches, when a pattern of paths matches its path. The example app's src/config/cors.rs is the starter's, with mcp/* and two origins:
use laravel::config;
use laravel::config::cors::{Allowed, Cors};
use laravel::time::ToSpan;
#[config::section]
fn cors() -> Cors {
Cors {
paths: vec!["api/*".to_owned(), "mcp/*".to_owned()],
methods: Allowed::Any,
origins: Allowed::only(["http://localhost:5173", "https://*.example.org"]),
origin_patterns: Vec::new(),
headers: Allowed::Any,
exposed_headers: Vec::new(),
max_age: Some(0.seconds().into()),
credentials: false,
}
}
Allowed::Any, the framework's default, lists no origin, so it doesn't open the server: list each origin. An origin listed only for api/* doesn't open it either. Nothing else changes for those requests: the token, the middleware and authorize apply as for any client. The framework's guide on CORS describes the section.
Writing for agents #
An agent knows only what the tools tell it. Three habits make a repository easy for an agent to use correctly:
- Document every input field with a doc comment. It becomes the field's description.
- Put rules in
#[validate(..)], not in a hook. A rule the schema shows is one the agent follows the first time, and a validation error names the field to fix. - Mark the fields an agent will want
searchable,matchableandsortable. An agent can't filter by a column the repository doesn't mark.
The protocol #
The server is built on rmcp, the official Rust SDK for MCP. It speaks Streamable HTTP and follows what that SDK implements.
- Its name in
initializeisLaravel Restify, with PHP's instructions. Its version is the crate's. - It answers
server/discover,initialize,ping,tools/listandtools/call. Itsinitializeannounces tools, resources and prompts, each withlistChanged: false, as PHP's server does, but it has no resources or prompts:resources/listandprompts/listanswer empty lists. PHP's server has no prompts either, and lists one resource,file://instructions/application-info.md, a text about the application and its versions, which this server doesn't serve. - It speaks every protocol version from
2024-11-05to the current2026-07-28. A2026-07-28client names the version in each request. An older client agrees on it withinitialize, which answers with the client's version when the server knows it, and2025-11-25otherwise. - Each request is independent: there are no sessions, and each answer is one JSON object. The server sends no requests of its own.
- A client must accept both
application/jsonandtext/event-stream(406otherwise) and sendContent-Type: application/json(415otherwise). - A
2026-07-28request must repeat its version, method and tool name in theMCP-Protocol-Version,Mcp-MethodandMcp-Nameheaders. A header that doesn't match the body is refused with400and error-32020. - A request whose
Originheader names another site is refused with403, unless the framework's CORS settings list that origin for the server's path. See Calling the MCP server from a browser. - An unknown tool, or one the user may not use, answers JSON-RPC error
-32602with the messageTool [name] not found., with HTTP status200. PHP sends the same error with status400. An unknown method answers-32601, with HTTP status404for a2026-07-28request.
Laravel is adding MCP servers to the framework itself. When that ships, Restify will register its tools with it and this server will go away. The tools, their names and their results will stay the same.