[Schema][Server] Harden sampling tools against the spec (#420)
* harden sampling tools against the spec Report tool-flow violations as -32602 instead of dropping the request, accept resource_link in tool results, gate tools on sampling.tools, and reject empty content. * normalize keyed content arrays to lists array_filter() and friends preserve keys, and a keyed array serializes as a JSON object instead of the content-block array the schema requires.
This commit is contained in:
parent
becce29c41
commit
43815e38a8
10 changed files with 1212 additions and 167 deletions
114
tests/Unit/Client/Handler/Request/SamplingRequestHandlerTest.php
Normal file
114
tests/Unit/Client/Handler/Request/SamplingRequestHandlerTest.php
Normal file
|
|
@ -0,0 +1,114 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the official PHP MCP SDK.
|
||||
*
|
||||
* A collaboration between Symfony and the PHP Foundation.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Mcp\Tests\Unit\Client\Handler\Request;
|
||||
|
||||
use Mcp\Client\Handler\Request\SamplingCallbackInterface;
|
||||
use Mcp\Client\Handler\Request\SamplingRequestHandler;
|
||||
use Mcp\Schema\Content\SamplingMessage;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Content\ToolResultContent;
|
||||
use Mcp\Schema\Content\ToolUseContent;
|
||||
use Mcp\Schema\Enum\Role;
|
||||
use Mcp\Schema\JsonRpc\Error;
|
||||
use Mcp\Schema\JsonRpc\Response;
|
||||
use Mcp\Schema\Request\CreateSamplingMessageRequest;
|
||||
use Mcp\Schema\Result\CreateSamplingMessageResult;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
class SamplingRequestHandlerTest extends TestCase
|
||||
{
|
||||
public function testHandleReturnsResponseForValidToolFlow(): void
|
||||
{
|
||||
$handler = new SamplingRequestHandler($this->callbackReturningText());
|
||||
|
||||
$request = $this->requestFor([
|
||||
new SamplingMessage(Role::User, new TextContent('Weather in Paris?')),
|
||||
new SamplingMessage(Role::Assistant, new ToolUseContent('call-1', 'weather', ['city' => 'Paris'])),
|
||||
new SamplingMessage(Role::User, new ToolResultContent('call-1', [new TextContent('18 C')])),
|
||||
]);
|
||||
|
||||
$response = $handler->handle($request);
|
||||
|
||||
$this->assertInstanceOf(Response::class, $response);
|
||||
$this->assertSame($request->getId(), $response->id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The spec asks for -32602 on both of these, and the callback must not run.
|
||||
*
|
||||
* @return iterable<string, array{SamplingMessage[], string}>
|
||||
*/
|
||||
public static function provideToolFlowViolations(): iterable
|
||||
{
|
||||
yield 'tool results mixed with other content' => [
|
||||
[
|
||||
new SamplingMessage(Role::Assistant, new ToolUseContent('call-1', 'weather', [])),
|
||||
new SamplingMessage(Role::User, [
|
||||
new ToolResultContent('call-1', [new TextContent('18 C')]),
|
||||
new TextContent('and also...'),
|
||||
]),
|
||||
],
|
||||
'Tool results mixed with other content.',
|
||||
];
|
||||
|
||||
yield 'tool result missing' => [
|
||||
[new SamplingMessage(Role::Assistant, new ToolUseContent('call-1', 'weather', []))],
|
||||
'Tool result missing in request.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param SamplingMessage[] $messages
|
||||
*/
|
||||
#[DataProvider('provideToolFlowViolations')]
|
||||
public function testHandleRejectsToolFlowViolationsWithInvalidParams(array $messages, string $expectedMessage): void
|
||||
{
|
||||
$callback = new class implements SamplingCallbackInterface {
|
||||
public bool $invoked = false;
|
||||
|
||||
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
|
||||
{
|
||||
$this->invoked = true;
|
||||
|
||||
throw new \LogicException('The callback must not run for an invalid request.');
|
||||
}
|
||||
};
|
||||
|
||||
$request = $this->requestFor($messages);
|
||||
$response = (new SamplingRequestHandler($callback))->handle($request);
|
||||
|
||||
$this->assertInstanceOf(Error::class, $response);
|
||||
$this->assertSame(Error::INVALID_PARAMS, $response->code);
|
||||
$this->assertSame($expectedMessage, $response->message);
|
||||
$this->assertSame($request->getId(), $response->id);
|
||||
$this->assertFalse($callback->invoked);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param SamplingMessage[] $messages
|
||||
*/
|
||||
private function requestFor(array $messages): CreateSamplingMessageRequest
|
||||
{
|
||||
return (new CreateSamplingMessageRequest($messages, 150))->withId('sampling-1');
|
||||
}
|
||||
|
||||
private function callbackReturningText(): SamplingCallbackInterface
|
||||
{
|
||||
return new class implements SamplingCallbackInterface {
|
||||
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
|
||||
{
|
||||
return new CreateSamplingMessageResult(Role::Assistant, new TextContent('Paris is warm.'), 'test-model');
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the official PHP MCP SDK.
|
||||
*
|
||||
* A collaboration between Symfony and the PHP Foundation.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Mcp\Tests\Unit\Schema;
|
||||
|
||||
use Mcp\Schema\ClientCapabilities;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ClientCapabilitiesSamplingTest extends TestCase
|
||||
{
|
||||
public function testSamplingSubCapabilitiesRoundTrip(): void
|
||||
{
|
||||
$capabilities = new ClientCapabilities(sampling: true, samplingContext: true, samplingTools: true);
|
||||
$serialized = $capabilities->jsonSerialize();
|
||||
|
||||
$this->assertObjectHasProperty('context', $serialized['sampling']);
|
||||
$this->assertObjectHasProperty('tools', $serialized['sampling']);
|
||||
|
||||
$hydrated = ClientCapabilities::fromArray(json_decode(json_encode($serialized, \JSON_THROW_ON_ERROR), true, flags: \JSON_THROW_ON_ERROR));
|
||||
$this->assertTrue($hydrated->sampling);
|
||||
$this->assertTrue($hydrated->samplingContext);
|
||||
$this->assertTrue($hydrated->samplingTools);
|
||||
}
|
||||
|
||||
public function testSamplingSubCapabilitiesAreHydratedFromObject(): void
|
||||
{
|
||||
$sampling = new \stdClass();
|
||||
$sampling->context = new \stdClass();
|
||||
$sampling->tools = new \stdClass();
|
||||
|
||||
$capabilities = ClientCapabilities::fromArray(['sampling' => $sampling]);
|
||||
|
||||
$this->assertTrue($capabilities->sampling);
|
||||
$this->assertTrue($capabilities->samplingContext);
|
||||
$this->assertTrue($capabilities->samplingTools);
|
||||
}
|
||||
}
|
||||
|
|
@ -68,4 +68,47 @@ class ClientCapabilitiesTest extends TestCase
|
|||
$this->assertTrue($restored->roots);
|
||||
$this->assertTrue($restored->rootsListChanged);
|
||||
}
|
||||
|
||||
public function testRoundTripPreservesSamplingSubCapabilities(): void
|
||||
{
|
||||
$capabilities = new ClientCapabilities(sampling: true, samplingContext: true, samplingTools: true);
|
||||
|
||||
$serialized = $capabilities->jsonSerialize();
|
||||
$this->assertObjectHasProperty('context', $serialized['sampling']);
|
||||
$this->assertObjectHasProperty('tools', $serialized['sampling']);
|
||||
|
||||
$restored = ClientCapabilities::fromArray(json_decode(json_encode($capabilities), true));
|
||||
|
||||
$this->assertTrue($restored->sampling);
|
||||
$this->assertTrue($restored->samplingContext);
|
||||
$this->assertTrue($restored->samplingTools);
|
||||
}
|
||||
|
||||
public function testPlainSamplingLeavesSubCapabilitiesOff(): void
|
||||
{
|
||||
$capabilities = new ClientCapabilities(sampling: true);
|
||||
|
||||
$serialized = $capabilities->jsonSerialize();
|
||||
$this->assertObjectNotHasProperty('context', $serialized['sampling']);
|
||||
$this->assertObjectNotHasProperty('tools', $serialized['sampling']);
|
||||
|
||||
$restored = ClientCapabilities::fromArray(json_decode(json_encode($capabilities), true));
|
||||
|
||||
$this->assertTrue($restored->sampling);
|
||||
$this->assertFalse($restored->samplingContext);
|
||||
$this->assertFalse($restored->samplingTools);
|
||||
}
|
||||
|
||||
public function testSamplingSubCapabilitiesAreHydratedFromObject(): void
|
||||
{
|
||||
$sampling = new \stdClass();
|
||||
$sampling->context = new \stdClass();
|
||||
$sampling->tools = new \stdClass();
|
||||
|
||||
$capabilities = ClientCapabilities::fromArray(['sampling' => $sampling]);
|
||||
|
||||
$this->assertTrue($capabilities->sampling);
|
||||
$this->assertTrue($capabilities->samplingContext);
|
||||
$this->assertTrue($capabilities->samplingTools);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
125
tests/Unit/Schema/Content/SamplingMessageTest.php
Normal file
125
tests/Unit/Schema/Content/SamplingMessageTest.php
Normal file
|
|
@ -0,0 +1,125 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the official PHP MCP SDK.
|
||||
*
|
||||
* A collaboration between Symfony and the PHP Foundation.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Mcp\Tests\Unit\Schema\Content;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Content\SamplingMessage;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Content\ToolResultContent;
|
||||
use Mcp\Schema\Content\ToolUseContent;
|
||||
use Mcp\Schema\Enum\Role;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class SamplingMessageTest extends TestCase
|
||||
{
|
||||
public function testToolLoopMessagesRoundTrip(): void
|
||||
{
|
||||
$assistant = SamplingMessage::fromArray([
|
||||
'role' => 'assistant',
|
||||
'_meta' => ['provider' => 'test'],
|
||||
'content' => [
|
||||
['type' => 'text', 'text' => 'I will check.'],
|
||||
['type' => 'tool_use', 'id' => 'call-1', 'name' => 'weather', 'input' => ['city' => 'Paris']],
|
||||
],
|
||||
]);
|
||||
$user = SamplingMessage::fromArray([
|
||||
'role' => 'user',
|
||||
'content' => [[
|
||||
'type' => 'tool_result',
|
||||
'toolUseId' => 'call-1',
|
||||
'content' => [['type' => 'text', 'text' => '21 C']],
|
||||
'structuredContent' => ['temperature' => 21],
|
||||
]],
|
||||
]);
|
||||
|
||||
$this->assertInstanceOf(ToolUseContent::class, $assistant->content[1]);
|
||||
$this->assertSame(['provider' => 'test'], $assistant->meta);
|
||||
$this->assertSame(['provider' => 'test'], $assistant->jsonSerialize()['_meta']);
|
||||
$this->assertInstanceOf(ToolResultContent::class, $user->content[0]);
|
||||
$this->assertSame(['temperature' => 21], $user->content[0]->structuredContent);
|
||||
|
||||
$this->assertEquals($assistant, SamplingMessage::fromArray(json_decode(json_encode($assistant), true)));
|
||||
$this->assertEquals($user, SamplingMessage::fromArray(json_decode(json_encode($user), true)));
|
||||
}
|
||||
|
||||
public function testSingleContentBlockKeepsItsShape(): void
|
||||
{
|
||||
$message = SamplingMessage::fromArray(['role' => 'user', 'content' => ['type' => 'text', 'text' => 'hi']]);
|
||||
|
||||
$this->assertInstanceOf(TextContent::class, $message->content);
|
||||
$this->assertSame('{"role":"user","content":{"type":"text","text":"hi"}}', json_encode($message));
|
||||
$this->assertCount(1, $message->getContentBlocks());
|
||||
}
|
||||
|
||||
public function testSingleElementListKeepsItsShape(): void
|
||||
{
|
||||
$message = SamplingMessage::fromArray(['role' => 'user', 'content' => [['type' => 'text', 'text' => 'hi']]]);
|
||||
|
||||
$this->assertIsArray($message->content);
|
||||
$this->assertSame('{"role":"user","content":[{"type":"text","text":"hi"}]}', json_encode($message));
|
||||
$this->assertCount(1, $message->getContentBlocks());
|
||||
}
|
||||
|
||||
/**
|
||||
* The tool-flow rules span the whole message list, so a single message is never
|
||||
* rejected for carrying the "wrong" block — see CreateSamplingMessageRequestTest.
|
||||
*/
|
||||
public function testToolBlocksAreAcceptedRegardlessOfRole(): void
|
||||
{
|
||||
$message = new SamplingMessage(Role::User, new ToolUseContent('call-1', 'weather', []));
|
||||
|
||||
$this->assertInstanceOf(ToolUseContent::class, $message->content);
|
||||
}
|
||||
|
||||
public function testFilteredContentStillSerializesAsAnArray(): void
|
||||
{
|
||||
$blocks = [new TextContent('thinking'), new ToolUseContent('call-1', 'weather', [])];
|
||||
|
||||
// array_filter() preserves keys, so this list starts at index 1.
|
||||
$toolUses = array_filter($blocks, static fn ($block): bool => $block instanceof ToolUseContent);
|
||||
$message = new SamplingMessage(Role::Assistant, $toolUses);
|
||||
|
||||
$this->assertSame(
|
||||
'{"role":"assistant","content":[{"type":"tool_use","id":"call-1","name":"weather","input":{}}]}',
|
||||
json_encode($message),
|
||||
);
|
||||
}
|
||||
|
||||
public function testEmptyContentListIsRejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
new SamplingMessage(Role::User, []);
|
||||
}
|
||||
|
||||
public function testEmptyContentListIsRejectedWhenHydrating(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
SamplingMessage::fromArray(['role' => 'user', 'content' => []]);
|
||||
}
|
||||
|
||||
public function testUnknownContentTypeIsRejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
SamplingMessage::fromArray(['role' => 'user', 'content' => ['type' => 'nope']]);
|
||||
}
|
||||
|
||||
public function testUnknownRoleIsRejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
/* @phpstan-ignore argument.type */
|
||||
SamplingMessage::fromArray(['role' => 'system', 'content' => ['type' => 'text', 'text' => 'hi']]);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,76 +0,0 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the official PHP MCP SDK.
|
||||
*
|
||||
* A collaboration between Symfony and the PHP Foundation.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Mcp\Tests\Unit\Schema\Content;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Content\SamplingMessage;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Content\ToolResultContent;
|
||||
use Mcp\Schema\Content\ToolUseContent;
|
||||
use Mcp\Schema\Enum\Role;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class SamplingToolContentTest extends TestCase
|
||||
{
|
||||
public function testToolLoopMessagesRoundTrip(): void
|
||||
{
|
||||
$assistant = SamplingMessage::fromArray([
|
||||
'role' => 'assistant',
|
||||
'_meta' => ['provider' => 'test'],
|
||||
'content' => [
|
||||
['type' => 'text', 'text' => 'I will check.'],
|
||||
['type' => 'tool_use', 'id' => 'call-1', 'name' => 'weather', 'input' => ['city' => 'Paris']],
|
||||
],
|
||||
]);
|
||||
$user = SamplingMessage::fromArray([
|
||||
'role' => 'user',
|
||||
'content' => [[
|
||||
'type' => 'tool_result',
|
||||
'toolUseId' => 'call-1',
|
||||
'content' => [['type' => 'text', 'text' => '21 C']],
|
||||
'structuredContent' => ['temperature' => 21],
|
||||
]],
|
||||
]);
|
||||
|
||||
$this->assertInstanceOf(ToolUseContent::class, $assistant->content[1]);
|
||||
$this->assertSame(['provider' => 'test'], $assistant->meta);
|
||||
$this->assertSame(['provider' => 'test'], $assistant->jsonSerialize()['_meta']);
|
||||
$this->assertInstanceOf(ToolResultContent::class, $user->content[0]);
|
||||
$this->assertSame(['temperature' => 21], $user->content[0]->structuredContent);
|
||||
$textContent = $user->content[0]->content[0];
|
||||
$this->assertInstanceOf(TextContent::class, $textContent);
|
||||
$this->assertSame('21 C', $textContent->text);
|
||||
}
|
||||
|
||||
public function testToolUseIsRejectedInUserMessage(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
new SamplingMessage(Role::User, new ToolUseContent('call-1', 'weather', []));
|
||||
}
|
||||
|
||||
public function testToolResultCannotBeMixedWithOtherContent(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
new SamplingMessage(Role::User, [
|
||||
new ToolResultContent('call-1', [new TextContent('done')]),
|
||||
new TextContent('extra'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function testToolResultRejectsNonStandardContentBlocks(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
new ToolResultContent('call-1', [
|
||||
new SamplingMessage(Role::User, new TextContent('not a tool result content block')),
|
||||
]);
|
||||
}
|
||||
}
|
||||
119
tests/Unit/Schema/Content/ToolResultContentTest.php
Normal file
119
tests/Unit/Schema/Content/ToolResultContentTest.php
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the official PHP MCP SDK.
|
||||
*
|
||||
* A collaboration between Symfony and the PHP Foundation.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Mcp\Tests\Unit\Schema\Content;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Content\EmbeddedResource;
|
||||
use Mcp\Schema\Content\ResourceLink;
|
||||
use Mcp\Schema\Content\SamplingMessage;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Content\ToolResultContent;
|
||||
use Mcp\Schema\Enum\Role;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ToolResultContentTest extends TestCase
|
||||
{
|
||||
public function testRoundTrip(): void
|
||||
{
|
||||
$content = ToolResultContent::fromArray([
|
||||
'type' => 'tool_result',
|
||||
'toolUseId' => 'call-1',
|
||||
'content' => [['type' => 'text', 'text' => '21 C']],
|
||||
'structuredContent' => ['temperature' => 21],
|
||||
'isError' => true,
|
||||
'_meta' => ['provider' => 'test'],
|
||||
]);
|
||||
|
||||
$this->assertSame('tool_result', $content->type);
|
||||
$this->assertSame('call-1', $content->toolUseId);
|
||||
$this->assertSame(['temperature' => 21], $content->structuredContent);
|
||||
$this->assertTrue($content->isError);
|
||||
$this->assertSame(['provider' => 'test'], $content->meta);
|
||||
|
||||
$textContent = $content->content[0];
|
||||
$this->assertInstanceOf(TextContent::class, $textContent);
|
||||
$this->assertSame('21 C', $textContent->text);
|
||||
|
||||
$restored = ToolResultContent::fromArray(json_decode(json_encode($content), true));
|
||||
$this->assertEquals($content, $restored);
|
||||
}
|
||||
|
||||
public function testIsErrorIsOmittedWhenFalse(): void
|
||||
{
|
||||
$content = new ToolResultContent('call-1', [new TextContent('ok')]);
|
||||
|
||||
$serialized = $content->jsonSerialize();
|
||||
|
||||
$this->assertArrayNotHasKey('isError', $serialized);
|
||||
$this->assertArrayNotHasKey('structuredContent', $serialized);
|
||||
$this->assertArrayNotHasKey('_meta', $serialized);
|
||||
$this->assertFalse(ToolResultContent::fromArray(json_decode(json_encode($content), true))->isError);
|
||||
}
|
||||
|
||||
public function testAcceptsEveryCallToolResultContentBlock(): void
|
||||
{
|
||||
$content = ToolResultContent::fromArray([
|
||||
'toolUseId' => 'call-1',
|
||||
'content' => [
|
||||
['type' => 'text', 'text' => 'a'],
|
||||
['type' => 'image', 'data' => base64_encode('img'), 'mimeType' => 'image/png'],
|
||||
['type' => 'audio', 'data' => base64_encode('snd'), 'mimeType' => 'audio/wav'],
|
||||
['type' => 'resource_link', 'uri' => 'file:///report.txt', 'name' => 'report'],
|
||||
['type' => 'resource', 'resource' => ['uri' => 'file:///a.txt', 'mimeType' => 'text/plain', 'text' => 'a']],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertInstanceOf(ResourceLink::class, $content->content[3]);
|
||||
$this->assertInstanceOf(EmbeddedResource::class, $content->content[4]);
|
||||
}
|
||||
|
||||
public function testFilteredContentStillSerializesAsAnArray(): void
|
||||
{
|
||||
$blocks = [new TextContent('drop me'), new TextContent('keep me')];
|
||||
|
||||
// array_filter() preserves keys, so this list starts at index 1.
|
||||
$kept = array_filter($blocks, static fn (TextContent $block): bool => 'keep me' === $block->text);
|
||||
$content = new ToolResultContent('call-1', $kept);
|
||||
|
||||
$this->assertSame(
|
||||
'{"type":"tool_result","toolUseId":"call-1","content":[{"type":"text","text":"keep me"}]}',
|
||||
json_encode($content),
|
||||
);
|
||||
}
|
||||
|
||||
public function testRejectsNonStandardContentBlocks(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
/* @phpstan-ignore argument.type */
|
||||
new ToolResultContent('call-1', [
|
||||
new SamplingMessage(Role::User, new TextContent('not a tool result content block')),
|
||||
]);
|
||||
}
|
||||
|
||||
public function testRejectsUnsupportedContentType(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
ToolResultContent::fromArray([
|
||||
'toolUseId' => 'call-1',
|
||||
'content' => [['type' => 'tool_use', 'id' => 'x', 'name' => 'y', 'input' => []]],
|
||||
]);
|
||||
}
|
||||
|
||||
public function testRejectsMissingToolUseId(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
ToolResultContent::fromArray(['content' => []]);
|
||||
}
|
||||
}
|
||||
80
tests/Unit/Schema/Content/ToolUseContentTest.php
Normal file
80
tests/Unit/Schema/Content/ToolUseContentTest.php
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the official PHP MCP SDK.
|
||||
*
|
||||
* A collaboration between Symfony and the PHP Foundation.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Mcp\Tests\Unit\Schema\Content;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Content\ToolUseContent;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ToolUseContentTest extends TestCase
|
||||
{
|
||||
public function testRoundTrip(): void
|
||||
{
|
||||
$content = ToolUseContent::fromArray([
|
||||
'type' => 'tool_use',
|
||||
'id' => 'call-1',
|
||||
'name' => 'weather',
|
||||
'input' => ['city' => 'Paris'],
|
||||
'_meta' => ['provider' => 'test'],
|
||||
]);
|
||||
|
||||
$this->assertSame('tool_use', $content->type);
|
||||
$this->assertSame('call-1', $content->id);
|
||||
$this->assertSame('weather', $content->name);
|
||||
$this->assertSame(['city' => 'Paris'], $content->input);
|
||||
$this->assertSame(['provider' => 'test'], $content->meta);
|
||||
|
||||
$this->assertSame(
|
||||
'{"type":"tool_use","id":"call-1","name":"weather","input":{"city":"Paris"},"_meta":{"provider":"test"}}',
|
||||
json_encode($content),
|
||||
);
|
||||
}
|
||||
|
||||
public function testEmptyInputSerializesAsObject(): void
|
||||
{
|
||||
$content = new ToolUseContent('call-1', 'ping', []);
|
||||
|
||||
$this->assertSame('{"type":"tool_use","id":"call-1","name":"ping","input":{}}', json_encode($content));
|
||||
}
|
||||
|
||||
public function testEmptyInputSurvivesRoundTrip(): void
|
||||
{
|
||||
$decoded = json_decode(json_encode(new ToolUseContent('call-1', 'ping', [])), true);
|
||||
|
||||
$this->assertSame([], ToolUseContent::fromArray($decoded)->input);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return iterable<string, array{array<string, mixed>}>
|
||||
*/
|
||||
public static function provideInvalidData(): iterable
|
||||
{
|
||||
yield 'missing id' => [['name' => 'weather', 'input' => []]];
|
||||
yield 'non-string id' => [['id' => 1, 'name' => 'weather', 'input' => []]];
|
||||
yield 'missing name' => [['id' => 'call-1', 'input' => []]];
|
||||
yield 'non-string name' => [['id' => 'call-1', 'name' => 1, 'input' => []]];
|
||||
yield 'missing input' => [['id' => 'call-1', 'name' => 'weather']];
|
||||
yield 'non-array input' => [['id' => 'call-1', 'name' => 'weather', 'input' => 'nope']];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
#[DataProvider('provideInvalidData')]
|
||||
public function testInvalidDataIsRejected(array $data): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
ToolUseContent::fromArray($data);
|
||||
}
|
||||
}
|
||||
|
|
@ -14,6 +14,8 @@ namespace Mcp\Tests\Unit\Schema\Request;
|
|||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Content\SamplingMessage;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Content\ToolResultContent;
|
||||
use Mcp\Schema\Content\ToolUseContent;
|
||||
use Mcp\Schema\Enum\Role;
|
||||
use Mcp\Schema\Enum\ToolChoiceMode;
|
||||
use Mcp\Schema\Request\CreateSamplingMessageRequest;
|
||||
|
|
@ -70,4 +72,123 @@ final class CreateSamplingMessageRequestTest extends TestCase
|
|||
$this->assertSame('weather', $hydrated->tools[0]->name);
|
||||
$this->assertSame(ToolChoiceMode::Required, $hydrated->toolChoice->mode);
|
||||
}
|
||||
|
||||
public function testValidToolFlowPasses(): void
|
||||
{
|
||||
$this->expectNotToPerformAssertions();
|
||||
|
||||
$this->requestFor([
|
||||
new SamplingMessage(Role::User, new TextContent('Weather in Paris and London?')),
|
||||
new SamplingMessage(Role::Assistant, [
|
||||
new ToolUseContent('call-1', 'weather', ['city' => 'Paris']),
|
||||
new ToolUseContent('call-2', 'weather', ['city' => 'London']),
|
||||
]),
|
||||
new SamplingMessage(Role::User, [
|
||||
new ToolResultContent('call-1', [new TextContent('18 C')]),
|
||||
new ToolResultContent('call-2', [new TextContent('15 C')]),
|
||||
]),
|
||||
new SamplingMessage(Role::Assistant, new TextContent('Paris is warmer.')),
|
||||
])->validateToolFlow();
|
||||
}
|
||||
|
||||
public function testToolResultsMixedWithOtherContentAreRejected(): void
|
||||
{
|
||||
$request = $this->requestFor([
|
||||
new SamplingMessage(Role::Assistant, new ToolUseContent('call-1', 'weather', [])),
|
||||
new SamplingMessage(Role::User, [
|
||||
new ToolResultContent('call-1', [new TextContent('18 C')]),
|
||||
new TextContent('and also...'),
|
||||
]),
|
||||
]);
|
||||
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Tool results mixed with other content.');
|
||||
|
||||
$request->validateToolFlow();
|
||||
}
|
||||
|
||||
public function testToolUseInUserMessageIsRejected(): void
|
||||
{
|
||||
$request = $this->requestFor([
|
||||
new SamplingMessage(Role::User, new ToolUseContent('call-1', 'weather', [])),
|
||||
]);
|
||||
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('ToolUseContent is only valid in assistant sampling messages.');
|
||||
|
||||
$request->validateToolFlow();
|
||||
}
|
||||
|
||||
public function testToolResultInAssistantMessageIsRejected(): void
|
||||
{
|
||||
$request = $this->requestFor([
|
||||
new SamplingMessage(Role::Assistant, new ToolResultContent('call-1', [new TextContent('18 C')])),
|
||||
]);
|
||||
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('ToolResultContent is only valid in user sampling messages.');
|
||||
|
||||
$request->validateToolFlow();
|
||||
}
|
||||
|
||||
public function testUnansweredToolUseIsRejected(): void
|
||||
{
|
||||
$request = $this->requestFor([
|
||||
new SamplingMessage(Role::Assistant, [
|
||||
new ToolUseContent('call-1', 'weather', []),
|
||||
new ToolUseContent('call-2', 'weather', []),
|
||||
]),
|
||||
new SamplingMessage(Role::User, [new ToolResultContent('call-1', [new TextContent('18 C')])]),
|
||||
]);
|
||||
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Tool result missing in request.');
|
||||
|
||||
$request->validateToolFlow();
|
||||
}
|
||||
|
||||
public function testTrailingToolUseIsRejected(): void
|
||||
{
|
||||
$request = $this->requestFor([
|
||||
new SamplingMessage(Role::Assistant, new ToolUseContent('call-1', 'weather', [])),
|
||||
]);
|
||||
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Tool result missing in request.');
|
||||
|
||||
$request->validateToolFlow();
|
||||
}
|
||||
|
||||
public function testToolUseFollowedByPlainMessageIsRejected(): void
|
||||
{
|
||||
$request = $this->requestFor([
|
||||
new SamplingMessage(Role::Assistant, new ToolUseContent('call-1', 'weather', [])),
|
||||
new SamplingMessage(Role::User, new TextContent('never mind')),
|
||||
]);
|
||||
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Tool result missing in request.');
|
||||
|
||||
$request->validateToolFlow();
|
||||
}
|
||||
|
||||
public function testUnsolicitedToolResultIsRejected(): void
|
||||
{
|
||||
$request = $this->requestFor([
|
||||
new SamplingMessage(Role::User, new ToolResultContent('call-9', [new TextContent('18 C')])),
|
||||
]);
|
||||
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Tool result "call-9" does not answer a preceding tool use.');
|
||||
|
||||
$request->validateToolFlow();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param SamplingMessage[] $messages
|
||||
*/
|
||||
private function requestFor(array $messages): CreateSamplingMessageRequest
|
||||
{
|
||||
return new CreateSamplingMessageRequest($messages, 150);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,8 +11,10 @@
|
|||
|
||||
namespace Mcp\Tests\Unit\Schema\Result;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Content\ToolUseContent;
|
||||
use Mcp\Schema\Enum\Role;
|
||||
use Mcp\Schema\Result\CreateSamplingMessageResult;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
|
|
@ -50,4 +52,77 @@ final class CreateSamplingMessageResultTest extends TestCase
|
|||
$this->assertSame('provider-specific', $result->stopReason);
|
||||
$this->assertSame('provider-specific', $result->jsonSerialize()['stopReason']);
|
||||
}
|
||||
|
||||
public function testKnownStopReasonStaysAString(): void
|
||||
{
|
||||
$result = CreateSamplingMessageResult::fromArray([
|
||||
'role' => 'assistant',
|
||||
'content' => ['type' => 'text', 'text' => 'Done'],
|
||||
'model' => 'test-model',
|
||||
'stopReason' => 'endTurn',
|
||||
]);
|
||||
|
||||
$this->assertSame('endTurn', $result->stopReason);
|
||||
}
|
||||
|
||||
public function testSingleContentBlockKeepsItsShape(): void
|
||||
{
|
||||
$result = CreateSamplingMessageResult::fromArray([
|
||||
'role' => 'assistant',
|
||||
'content' => ['type' => 'text', 'text' => 'Done'],
|
||||
'model' => 'test-model',
|
||||
]);
|
||||
|
||||
$this->assertInstanceOf(TextContent::class, $result->content);
|
||||
$this->assertCount(1, $result->getContentBlocks());
|
||||
$this->assertSame('{"type":"text","text":"Done"}', json_encode($result->jsonSerialize()['content']));
|
||||
}
|
||||
|
||||
public function testFilteredContentStillSerializesAsAnArray(): void
|
||||
{
|
||||
$blocks = [new TextContent('thinking'), new ToolUseContent('call-1', 'weather', [])];
|
||||
|
||||
// array_filter() preserves keys, so this list starts at index 1.
|
||||
$toolUses = array_filter($blocks, static fn ($block): bool => $block instanceof ToolUseContent);
|
||||
$result = new CreateSamplingMessageResult(Role::Assistant, $toolUses, 'test-model');
|
||||
|
||||
$this->assertSame(
|
||||
'[{"type":"tool_use","id":"call-1","name":"weather","input":{}}]',
|
||||
json_encode($result->jsonSerialize()['content']),
|
||||
);
|
||||
}
|
||||
|
||||
public function testNonAssistantRoleIsRejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('CreateSamplingMessageResult role must be "assistant".');
|
||||
|
||||
CreateSamplingMessageResult::fromArray([
|
||||
'role' => 'user',
|
||||
'content' => ['type' => 'text', 'text' => 'Done'],
|
||||
'model' => 'test-model',
|
||||
]);
|
||||
}
|
||||
|
||||
public function testEmptyContentIsRejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
CreateSamplingMessageResult::fromArray([
|
||||
'role' => 'assistant',
|
||||
'content' => [],
|
||||
'model' => 'test-model',
|
||||
]);
|
||||
}
|
||||
|
||||
public function testToolResultContentIsRejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
|
||||
CreateSamplingMessageResult::fromArray([
|
||||
'role' => 'assistant',
|
||||
'content' => ['type' => 'tool_result', 'toolUseId' => 'call-1', 'content' => []],
|
||||
'model' => 'test-model',
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
63
tests/Unit/Schema/ToolChoiceTest.php
Normal file
63
tests/Unit/Schema/ToolChoiceTest.php
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
<?php
|
||||
|
||||
/*
|
||||
* This file is part of the official PHP MCP SDK.
|
||||
*
|
||||
* A collaboration between Symfony and the PHP Foundation.
|
||||
*
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*/
|
||||
|
||||
namespace Mcp\Tests\Unit\Schema;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Enum\ToolChoiceMode;
|
||||
use Mcp\Schema\ToolChoice;
|
||||
use PHPUnit\Framework\Attributes\DataProvider;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ToolChoiceTest extends TestCase
|
||||
{
|
||||
/**
|
||||
* @return iterable<string, array{ToolChoiceMode}>
|
||||
*/
|
||||
public static function provideModes(): iterable
|
||||
{
|
||||
yield 'auto' => [ToolChoiceMode::Auto];
|
||||
yield 'required' => [ToolChoiceMode::Required];
|
||||
yield 'none' => [ToolChoiceMode::None];
|
||||
}
|
||||
|
||||
#[DataProvider('provideModes')]
|
||||
public function testRoundTrip(ToolChoiceMode $mode): void
|
||||
{
|
||||
$choice = new ToolChoice($mode);
|
||||
|
||||
$this->assertSame(\sprintf('{"mode":"%s"}', $mode->value), json_encode($choice));
|
||||
$this->assertSame($mode, ToolChoice::fromArray(json_decode(json_encode($choice), true))->mode);
|
||||
}
|
||||
|
||||
public function testModeDefaultsToAuto(): void
|
||||
{
|
||||
$this->assertSame(ToolChoiceMode::Auto, (new ToolChoice())->mode);
|
||||
$this->assertSame(ToolChoiceMode::Auto, ToolChoice::fromArray([])->mode);
|
||||
}
|
||||
|
||||
public function testUnknownModeIsRejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Invalid tool choice mode "any".');
|
||||
|
||||
ToolChoice::fromArray(['mode' => 'any']);
|
||||
}
|
||||
|
||||
public function testNonStringModeIsRejected(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Invalid "mode" in ToolChoice data.');
|
||||
|
||||
/* @phpstan-ignore argument.type */
|
||||
ToolChoice::fromArray(['mode' => 1]);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue