Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,48 @@ public function validate(array $rules, array $messages = [], array $attributes =
return Validator::validate($this->all(), $rules, $messages, $attributes);
}

/**
* Get custom rules for validator errors.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [];
}

/**
* Get custom messages for validator errors.
*
* @return array<string, string>
*/
public function messages(): array
{
return [];
}

/**
* Get custom attributes for validator errors.
*
* @return array<string, string>
*/
public function attributes(): array
{
return [];
}

/**
* Get the validated data from the request.
*
* @return array<string, mixed>
*
* @throws ValidationException
*/
public function validated(): array
{
return $this->validate($this->rules(), $this->messages(), $this->attributes());
}

public function user(?string $guard = null): ?Authenticatable
{
$auth = Container::getInstance()->make('auth');
Expand Down
71 changes: 71 additions & 0 deletions tests/Feature/CustomRequestValidationTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
<?php

use Laravel\Mcp\Request;
use Laravel\Mcp\Server;
use Laravel\Mcp\Server\Tool;

class GreetingRequest extends Request
{
public function rules(): array
{
return [
'name' => 'required|string',
];
}

public function messages(): array
{
return [
'name.required' => 'The :attribute field is required.',
'name.string' => 'The :attribute must be a string.',
];
}

public function attributes(): array
{
return [
'name' => 'Name',
];
}
}

class GreetingServer extends Server
{
protected array $tools = [
Greet::class,
];
}

class Greet extends Tool
{
public function handle(GreetingRequest $request): string
{
$validated = $request->validated();
$name = $validated['name'];

return "Hello, {$name}!";
}
}

it('returns empty arrays for default validation helpers', function (): void {
$request = new Request;

expect($request->rules())->toBe([]);
expect($request->messages())->toBe([]);
expect($request->attributes())->toBe([]);
expect($request->validated())->toBe([]);
});

it('can use the custom request validation', function (): void {
$response = GreetingServer::tool(Greet::class, [
'name' => 'World',
]);

$response->assertSee('Hello, World!');
});

it('can throw validation errors when required fields are missing', function (): void {
$response = GreetingServer::tool(Greet::class, []);

$response->assertHasErrors(['name' => 'The Name field is required.']);
});