How JsonSchema::rules() works with Laravel AI SDK and MCP tools, what the generated rules look like, and where you still need to check model output yourself.
A developer building MCP tools for an ERP described the bug in a pull request, and it will sound familiar to anyone who has written more than two of these. Every tool has a schema() method that tells the agent what arguments it may send, and a handle() method that validates the same arguments with ordinary Laravel rules. After the third tool there are two copies of every field, and they drift. Someone lowers a max in the rules and forgets the schema. The agent, which only ever reads the schema, keeps sending values that fit the old limit, and the validator rejects them. Nothing crashes. The tool just fails in a way that looks like the model being unreliable, when the real cause is two sources of truth that stopped agreeing.
Laravel 13.43 closes that gap from the schema side. JsonSchema::rules(), contributed by Pushpak Chhajed (#62355), takes an object schema and returns Laravel validation rules, so the same definition that tells the model what to send also checks what arrived. It was backported to 12.x (#62501); a third-party summary puts that in 12.73, so confirm the exact 12.x version in the release notes. A follow-up in the same release (#62496) adds support for exclusiveMinimum and exclusiveMaximum.
It’s a good change, and the PR is candid about its limits. A generated rule set is only as complete as the mapping between JSON Schema and Laravel rules, and model output is untrusted input that can be schema-valid and still wrong. This post covers how it works, what it generates, how to wire it into a tool, and the specific places you still have to check things yourself.
What It Does
JsonSchema::rules() maps schema keywords to native Laravel rules. It is not a JSON Schema validator: nothing new is installed, and what runs at validation time is Laravel’s own validator. The PR says earlier attempts wrapped an external validator and built a schema from rules, and this one deliberately goes the other direction with no new dependency.
use Illuminate\JsonSchema\JsonSchema;
use Illuminate\Support\Facades\Validator;
$schema = JsonSchema::object(fn ($s) => [
'query' => $s->string()->min(3)->max(120)->required(),
'limit' => $s->integer()->min(1)->max(50),
'status' => $s->string()->enum(['open', 'closed'])->required(),
]);
$rules = JsonSchema::rules($schema);
The result has this shape, following the examples in the PR:
// [
// 'query' => ['required', 'string', 'min:3', 'max:120'],
// 'limit' => ['sometimes', <RejectEmptyString rule>, 'integer', 'min:1', 'max:50'],
// 'status' => ['required', 'string', Rule::in(['open', 'closed'])],
// ]
I’m showing the shape, not a guarantee of exact ordering or rule classes, so dump the output for your own schema and read it. Two things in it are worth noticing right away. A property that isn’t required() gets sometimes, so it may be omitted. And that optional integer also carries a rule that rejects an empty string, rather than treating "" as “not provided.”
The rules work anywhere Laravel accepts them. The official validation docs show three entry points:
// 1. Straight into the validator
$validator = Validator::make($request->all(), JsonSchema::rules($schema));
// 2. Inside a form request
public function rules(): array
{
return JsonSchema::rules(JsonSchema::object(fn ($s) => [
'email' => $s->string()->format('email')->required(),
]));
}
// 3. From a raw JSON Schema array, such as an MCP tool's input schema
$rules = JsonSchema::rules([
'type' => 'object',
'properties' => ['id' => ['type' => 'string', 'format' => 'uuid']],
'required' => ['id'],
]);
// ['id' => ['required', 'string', 'uuid']]
The third form is the one that matters for tools, because a schema that arrives as a plain array, from an MCP server or stored JSON, doesn’t have to be rebuilt with the fluent builder first.
How the Mapping Reads
This is my condensed version of the PR’s mapping table. Read the PR for the full list.
| Schema says | Laravel gets | Note |
|---|---|---|
type | string, integer, numeric, boolean, array, list; a null union adds nullable | |
required | required | Nested keys are enforced through the parent’s required_array_keys, so an absent or null parent passes |
enum | in | Array and object values are compared by content |
anyOf | Passes if one branch passes | A sibling enum still applies |
properties, items | Dot-notation keys such as address.city and tags.* | |
additionalProperties: false | array:<keys> | Listed for nested objects |
uniqueItems | distinct | Equal object items also fail |
length, range, count keywords, multipleOf | min, max, multiple_of | |
pattern | regex | With the u flag |
format | email, uri/url, uuid, date, date-time | Any other format is only an annotation and adds no rule |
title, description, default | Nothing |
The last row and the format row are where most of the surprises live. They come up again below.
Wiring It Into an MCP Tool
A Laravel MCP tool declares schema() and implements handle(). The goal is for handle() to derive its rules from the schema that schema() returns, so there’s one definition. Here is a pattern composed from documented pieces. It’s not a documented recipe, and I haven’t run it, so verify it against your laravel/mcp version:
use Illuminate\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Tool;
class SearchInvoices extends Tool
{
public function schema(JsonSchema $schema): array
{
return [
'query' => $schema->string()->min(3)->max(120)->required(),
'limit' => $schema->integer()->min(1)->max(50),
'status' => $schema->string()->enum(['open', 'closed'])->required(),
];
}
public function handle(Request $request): Response
{
// One definition: the schema the model sees is the schema that validates
$validated = $request->validate(
JsonSchema::rules(JsonSchema::object(fn ($s) => $this->schema($s)))
);
return Response::text(
Invoice::search($validated['query'], $validated['limit'] ?? 20)
);
}
}
On failure, an open laravel/mcp issue about this same duplication describes the existing behavior: a ValidationException already becomes a tool error that carries the messages, so the model gets told what was wrong and can try again. Treat that as a design feature, not an afterthought. A message like “The limit field must not be greater than 50” lets the agent correct itself. A generic failure doesn’t.
For the Laravel AI SDK the idea is identical: tools there also declare a schema and a handler, and the PR names laravel/ai as the other package that has been repeating constraints. I’m not showing code because I’d be guessing at the SDK’s request class, and you should check how it exposes the arguments array before wiring Validator::make($arguments, ...). One more thing the PR says: its tests port the full dataset laravel/ai uses to map schemas to rules, so the SDK and the MCP package can delete their own copies. That describes what becomes possible, not something I confirmed has already happened.
Where You Still Have to Check Things Yourself
Everything below follows from one fact: the output is Laravel rules, so Laravel’s behavior applies, not JSON Schema’s. The same fact that makes this convenient makes each of these a place a schema-valid call can still go wrong.
Coercion means types are looser than the schema says. The PR states it directly: "3" passes integer. A model that sends a number as a string, which they do, gets through. And validation doesn’t cast values, so $validated['limit'] is still the string "3". If your handler does anything where "3" and 3 differ, cast explicitly.
A required array or object rejects []. In JSON Schema, required means the key is present, and an empty array is a valid value. Laravel’s required fails on an empty array, and the PR notes the generated rules inherit that. A tool that legitimately accepts “no tags” as [] needs the property to be optional rather than required, or the model’s correct answer gets rejected.
default is not applied. The schema can tell the model a default exists, but the rules add nothing for it, and Laravel validation doesn’t fill in missing values. If limit defaults to 20, your handler has to supply 20, as the ?? 20 above does.
Most format values add no rule. Only email, uri/url, uuid, date and date-time become rules. A schema that declares some other format is documenting it for the model and enforcing nothing. If a format matters to you, add a pattern or your own rule.
Optional properties reject empty strings. For the optional integer in the example, the generated rules include one that rejects "". That’s stricter than a client that sends an empty string to mean “none,” and it’s worth knowing before you debug why an agent’s call failed on a field it left blank.
Nested required keys depend on the parent. Because they’re enforced through the parent’s required_array_keys, an absent or null parent passes, so a missing parent skips its required children entirely.
Extra properties: use the validated data. additionalProperties: false is listed in the mapping for nested objects, and I couldn’t tell from the sources what happens to unexpected keys at the top level. The practical rule doesn’t depend on the answer. Use the array that validate() returns, not $request->all(), and whatever the model invented never reaches your code.
Schema-valid is not the same as allowed. This is the one that matters most for safety, and no schema can express it. A syntactically valid UUID doesn’t mean the record exists, belongs to this user, or can be acted on. Existence, ownership, uniqueness, cross-field rules, and authorization all still run in your handler through exists, policies, and the rest. The schema describes shape. The tool still runs with the user’s authority, and policies still decide what that authority covers.
Test the Inputs a Model Actually Sends
The cheapest protection is a table of the awkward inputs, asserted against your real rules. Run it once and the table tells you what your version does instead of what you assume:
it('handles the inputs a model actually sends', function (array $input, bool $valid) {
$rules = JsonSchema::rules(JsonSchema::object(fn ($s) => [
'query' => $s->string()->min(3)->max(120)->required(),
'limit' => $s->integer()->min(1)->max(50),
'status' => $s->string()->enum(['open', 'closed'])->required(),
]));
expect(Validator::make($input, $rules)->passes())->toBe($valid);
})->with([
'numeric string for an integer' => [['query' => 'abc', 'limit' => '5', 'status' => 'open'], true],
'limit over the maximum' => [['query' => 'abc', 'limit' => 500, 'status' => 'open'], false],
'empty string for optional int' => [['query' => 'abc', 'limit' => '', 'status' => 'open'], false],
'value outside the enum' => [['query' => 'abc', 'status' => 'archived'], false],
'missing required field' => [['limit' => 5, 'status' => 'open'], false],
]);
The first row should pass because of the coercion the PR describes, and the empty-string row should fail given the rule in the generated output. Those two are my expectations from the PR, so treat any disagreement as the useful result, not a failed test.
An Upgrade Note
Laravel News’s write-up says 13.43 also ships several security fixes alongside this feature. I haven’t verified the details beyond that summary, so I’m not listing them here. Read the release notes before deciding to defer the upgrade for the sake of a validation helper.
Where This Fits
Does the tool's input schema already exist (SDK tool, MCP tool, stored JSON)?
├─ No → Write it once with JsonSchema::object(...), derive rules from it
└─ Yes → Is there a second copy of the same constraints in handle()?
├─ Yes → Replace it with JsonSchema::rules($thatSchema) and delete the copy
└─ No → Nothing to remove
After deriving the rules, still write by hand (the schema can't say these):
├─ exists / ownership / uniqueness checks
├─ cross-field rules and business limits
├─ authorization through policies
├─ defaults, and casts for coerced values
└─ rules for any format the schema layer ignores
Always:
└─ Use the validated array, return a useful error message, and
run the awkward-input table against your real rules
The Verdict
JsonSchema::rules() removes a real source of bugs: two copies of the same constraints that were always going to drift, with the model reading one copy and your code enforcing the other. That’s worth adopting for every tool where both exist. What it can’t do is make model output trustworthy. Laravel’s coercion, the [] behavior, the missing default handling and the ignored formats are all places where the generated rules are looser or stricter than the schema the model read. And the most important checks, whether this record exists, whether this user may touch it, whether the combination makes business sense, were never expressible in a schema. Keep one definition, validate against it, then validate against your own domain rules as well. The schema tells the model what to send. It doesn’t tell you what to believe.
