Skip to content

Commit e601c68

Browse files
committed
adds Response::json
1 parent 0865174 commit e601c68

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

src/Response.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace Laravel\Mcp;
66

7+
use JsonException;
78
use Laravel\Mcp\Enums\Role;
89
use Laravel\Mcp\Exceptions\NotImplementedException;
910
use Laravel\Mcp\Server\Content\Blob;
@@ -34,6 +35,21 @@ public static function text(string $text): static
3435
return new static(new Text($text));
3536
}
3637

38+
/**
39+
* @internal
40+
*
41+
* @param array<string, mixed> $content
42+
*
43+
* @throws JsonException
44+
*/
45+
public static function json(array $content): static
46+
{
47+
return static::text(json_encode(
48+
$content,
49+
JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT,
50+
));
51+
}
52+
3753
public static function blob(string $content): static
3854
{
3955
return new static(new Blob($content));

tests/Unit/ResponseTest.php

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,3 +74,51 @@
7474
expect($assistantResponse->role())->toBe(Role::ASSISTANT);
7575
expect($assistantResponse->isError())->toBeTrue();
7676
});
77+
78+
it('creates a json response', function (): void {
79+
$data = ['key' => 'value', 'number' => 123];
80+
$response = Response::json($data);
81+
82+
expect($response->content())->toBeInstanceOf(Text::class);
83+
expect($response->isNotification())->toBeFalse();
84+
expect($response->isError())->toBeFalse();
85+
expect($response->role())->toBe(Role::USER);
86+
87+
$content = $response->content();
88+
expect((string) $content)->toBe(json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
89+
});
90+
91+
it('handles nested arrays in json response', function (): void {
92+
$data = [
93+
'user' => [
94+
'name' => 'John Doe',
95+
'email' => '[email protected]',
96+
'roles' => ['admin', 'developer']
97+
],
98+
'active' => true
99+
];
100+
$response = Response::json($data);
101+
102+
expect($response->content())->toBeInstanceOf(Text::class);
103+
104+
$content = $response->content();
105+
expect((string) $content)->toBe(json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
106+
});
107+
108+
it('throws JsonException for invalid json data', function (): void {
109+
$data = ['invalid' => INF];
110+
111+
expect(function () use ($data): void {
112+
Response::json($data);
113+
})->toThrow(JsonException::class);
114+
});
115+
116+
it('handles empty array in json response', function (): void {
117+
$data = [];
118+
$response = Response::json($data);
119+
120+
expect($response->content())->toBeInstanceOf(Text::class);
121+
122+
$content = $response->content();
123+
expect((string) $content)->toBe(json_encode($data, JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT));
124+
});

0 commit comments

Comments
 (0)