[Schema][Server] Close the 2025-11-25 schema gaps and add the 2026-07-28 surface (#421)

* [Schema][Server] Close the 2025-11-25 schema gaps and add the 2026-07-28 surface

Ports the type definitions this SDK still misses outside of sampling tool use,
which #409 and #420 already cover. Every addition is optional and defaults to
current behaviour, so a connection negotiated on an older revision is
unaffected.

From 2025-11-25, elicitation gains modes. ElicitationMode splits `form` —
build a form from the requested schema — from `url`, which sends the user out
of band and returns only the accept/decline/cancel outcome. That is why
requestedSchema becomes optional and `url` appears beside it.
ClientCapabilities learns the matching sub-capabilities, where an
`elicitation` naming no mode declares form, the only shape that existed
before. Icon gains `theme` from the same revision, and Implementation gains
the `title` BaseMetadata has carried since 2025-06-18.

From 2026-07-28, schemas loosen where the revision loosens them: SEP-2106
drops the object-only restriction, so Tool::outputSchema may describe any JSON
value and CallToolResult::structuredContent follows.

The same revision defines three error codes (-32020 header mismatch, -32021
missing required client capability, -32022 unsupported protocol version).
ProtocolVersionMiddleware switches to the last of them, so a rejected version
carries the supported set as structured data the client can retry from rather
than only as prose.

* [Schema] Reject what the 2026-07-28 types cannot represent

`Implementation::title` reached the typed constructor unchecked, so malformed
wire data raised a TypeError instead of InvalidArgumentException.

`ToolUseContent::input` accepted a list and serialized it as a JSON array,
where the protocol requires an object. The empty array stays exempt: it is
also an empty map and still emits `{}`.

`ToolChoice` and `ElicitRequest` read their mode with isset(), which is false
for an explicit null, so `{"mode": null}` silently became the default instead
of being rejected. Both use array_key_exists() now, letting the existing type
check refuse null.

* [Client][Server] Advertise the implementation title through both builders

`Implementation::title` could be parsed but never sent: neither
`Client\Builder::setClientInfo()` nor `Server\Builder::setServerInfo()`
accepted one, so every SDK user emitted null.

Both gain a trailing optional `$title`. On the server it sits where the
Implementation constructor already puts it, so existing positional calls keep
their meaning; the client builder forwards it by name, leaving the icons and
websiteUrl slots defaulted.

* [Schema] Serialize every non-null structuredContent

The object-only hydration guard was never that: `!is_array()` admitted
`[1, 2, 3]` and `[]`, which serialize to JSON arrays, while rejecting the
scalars 2026-07-28 permits. The truthiness emission gate was backwards in the
same way — it dropped `[]`, `0`, `false` and `""`, yet emitted lists, strings
and an empty stdClass.

Hydration now accepts any JSON value, and `null` alone means absent, matching
`ToolResultContent` which already carries this field that way. Which values a
given revision permits is a question for version-aware serialization, which
results cannot answer yet.

* [Schema][Server] Make url elicitation reachable

`ElicitRequest::forUrl()` built a request no SDK user could send: the only
public gateway method always constructed form mode from an ElicitationSchema,
and `request()` is private.

`elicitUrl()` joins `elicit()`, and both funnel through one send path that
hydrates the result with the request's own mode. Without that, a url-mode
accept — contentless by design — threw, because ElicitResult requires content
whenever the action is accept. The result carries no discriminator of its own,
so the mode has to come from the request it answers.

`supportsElicitationUrl()` reports whether the client named the mode, reusing
the sub-capability reader the sampling checks already use.

* [Schema] Add CHANGELOG entry for the 2026-07-28 surface

* [Capability][Schema][Server] Carry the widened structuredContent end to end

Review follow-up on the SEP-2106 widening, which stopped at the type.

`ToolReference::extractStructuredContent()` returned `?array`, so a tool
declaring a scalar `outputSchema` had its result dropped and logged as
unsendable. It returns `mixed` now and keeps a scalar — but only from
2026-07-28 on, and only when the tool declared an outputSchema: without one
the value is already carried in `content`, and advertising it twice is not an
improvement.

`CallToolHandler` only warned about list-shaped `structuredContent` on a
self-built `CallToolResult`, so a scalar reached revisions that require an
object unremarked. The check is on the shape now, not on the list case alone.

`ElicitResult` retained a `content` the spec says is absent from url-mode
results, leaving a malformed response indistinguishable from a valid one.

`Tool::jsonSerialize()` emitted the empty root schema as `[]`, which is not a
schema at all. Sub-schemas already had this treatment.
This commit is contained in:
Christopher Hertel 2026-08-17 23:09:39 +02:00 • committed by GitHub
commit f84d8f5aa9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 1205 additions and 91 deletions

View file

@ -753,6 +753,46 @@ class RegistryTest extends TestCase
};
}
public function testExtractStructuredContentKeepsAScalarFromSep2106On(): void
{
$tool = $this->createValidTool('test_tool', ['type' => 'string']);
$this->registry->registerTool($tool, static fn () => 'sunny');
$toolRef = $this->registry->getTool('test_tool');
$this->assertSame('sunny', $toolRef->extractStructuredContent('sunny', ProtocolVersion::V2026_07_28));
$this->assertNull($toolRef->extractStructuredContent('sunny', ProtocolVersion::V2025_11_25));
}
public function testExtractStructuredContentDropsAScalarWithoutAnOutputSchema(): void
{
$tool = $this->createValidTool('test_tool', null);
$this->registry->registerTool($tool, static fn () => 'sunny');
$toolRef = $this->registry->getTool('test_tool');
// Without a declared schema the value is already carried in `content`;
// advertising it as structured too would duplicate it.
$this->assertNull($toolRef->extractStructuredContent('sunny', ProtocolVersion::V2026_07_28));
}
public function testExtractStructuredContentKeepsAJsonSerializableScalarFromSep2106On(): void
{
$tool = $this->createValidTool('test_tool', ['type' => 'number']);
$result = new class implements \JsonSerializable {
public function jsonSerialize(): float
{
return 22.5;
}
};
$this->registry->registerTool($tool, static fn () => $result);
$toolRef = $this->registry->getTool('test_tool');
$this->assertSame(22.5, $toolRef->extractStructuredContent($result, ProtocolVersion::V2026_07_28));
$this->assertNull($toolRef->extractStructuredContent($result, ProtocolVersion::V2025_11_25));
}
private function createValidTool(string $name, ?array $outputSchema = null): Tool
{
return new Tool(

View file

@ -0,0 +1,53 @@
<?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;
use Mcp\Client;
use Mcp\Client\Configuration;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
final class BuilderTest extends TestCase
{
#[TestDox('setClientInfo() forwards the title to the advertised clientInfo')]
public function testSetClientInfoForwardsTitle(): void
{
$client = Client::builder()
->setClientInfo('my-client', '1.0.0', 'A test client', 'My Client')
->build();
$clientInfo = $this->extractConfiguration($client)->clientInfo;
$this->assertSame('my-client', $clientInfo->name);
$this->assertSame('1.0.0', $clientInfo->version);
$this->assertSame('A test client', $clientInfo->description);
$this->assertSame('My Client', $clientInfo->title);
}
#[TestDox('setClientInfo() leaves the title absent when it is not given')]
public function testSetClientInfoTitleIsOptional(): void
{
$client = Client::builder()
->setClientInfo('my-client', '1.0.0')
->build();
$this->assertNull($this->extractConfiguration($client)->clientInfo->title);
}
private function extractConfiguration(Client $client): Configuration
{
$config = (new \ReflectionClass($client))->getProperty('config')->getValue($client);
$this->assertInstanceOf(Configuration::class, $config);
return $config;
}
}

View file

@ -12,6 +12,7 @@
namespace Mcp\Tests\Unit\Schema;
use Mcp\Schema\ClientCapabilities;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
class ClientCapabilitiesTest extends TestCase
@ -111,4 +112,69 @@ class ClientCapabilitiesTest extends TestCase
$this->assertTrue($capabilities->samplingContext);
$this->assertTrue($capabilities->samplingTools);
}
#[TestDox('reads the elicitation sub-capabilities')]
public function testReadsElicitationSubCapabilities(): void
{
$capabilities = ClientCapabilities::fromArray([
'elicitation' => ['form' => [], 'url' => []],
]);
$this->assertTrue($capabilities->elicitation);
$this->assertTrue($capabilities->elicitationForm);
$this->assertTrue($capabilities->elicitationUrl);
}
#[TestDox('an elicitation capability naming no mode declares form')]
public function testElicitationWithoutModeImpliesForm(): void
{
$capabilities = ClientCapabilities::fromArray(['elicitation' => []]);
$this->assertTrue($capabilities->elicitationForm);
$this->assertFalse($capabilities->elicitationUrl);
}
#[TestDox('naming url alone does not declare form')]
public function testElicitationUrlAloneIsNotForm(): void
{
$capabilities = ClientCapabilities::fromArray(['elicitation' => ['url' => []]]);
$this->assertFalse($capabilities->elicitationForm);
$this->assertTrue($capabilities->elicitationUrl);
}
#[TestDox('an absent elicitation capability declares no mode either way')]
public function testAbsentElicitationLeavesModesNull(): void
{
$capabilities = ClientCapabilities::fromArray([]);
$this->assertNull($capabilities->elicitation);
$this->assertNull($capabilities->elicitationForm);
$this->assertNull($capabilities->elicitationUrl);
}
#[TestDox('round-trips the elicitation sub-capabilities')]
public function testRoundTripPreservesElicitationSubCapabilities(): void
{
$capabilities = new ClientCapabilities(elicitation: true, elicitationForm: true, elicitationUrl: true);
$encoded = json_encode($capabilities) ?: '';
$this->assertStringContainsString('"elicitation":{"form":{},"url":{}}', $encoded);
$restored = ClientCapabilities::fromArray(json_decode($encoded, true));
$this->assertTrue($restored->elicitationForm);
$this->assertTrue($restored->elicitationUrl);
}
#[TestDox('declaring only a mode still advertises elicitation')]
public function testElicitationModeImpliesParent(): void
{
$capabilities = new ClientCapabilities(elicitationUrl: true);
$encoded = json_decode(json_encode($capabilities) ?: '', true);
$this->assertArrayHasKey('elicitation', $encoded);
$this->assertArrayHasKey('url', $encoded['elicitation']);
}
}

View file

@ -77,4 +77,28 @@ final class ToolUseContentTest extends TestCase
ToolUseContent::fromArray($data);
}
public function testRejectsListInput(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('ToolUseContent "input" must be a map of argument names, not a list.');
/* @phpstan-ignore argument.type (deliberately list-shaped) */
new ToolUseContent('call-1', 'get_weather', ['Berlin']);
}
public function testRejectsListInputFromArray(): void
{
$this->expectException(InvalidArgumentException::class);
ToolUseContent::fromArray(['type' => 'tool_use', 'id' => 'call-1', 'name' => 'x', 'input' => [1]]);
}
public function testEmptyInputIsAccepted(): void
{
$content = ToolUseContent::fromArray(['type' => 'tool_use', 'id' => 'call-1', 'name' => 'ping', 'input' => []]);
$this->assertSame([], $content->input);
$this->assertSame('{"type":"tool_use","id":"call-1","name":"ping","input":{}}', json_encode($content));
}
}

View file

@ -0,0 +1,146 @@
<?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\Elicitation\ElicitationSchema;
use Mcp\Schema\Elicitation\StringSchemaDefinition;
use Mcp\Schema\Enum\ElicitationMode;
use Mcp\Schema\JsonRpc\MessageInterface;
use Mcp\Schema\Request\ElicitRequest;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
class ElicitationModeTest extends TestCase
{
#[TestDox('form elicitation omits the mode discriminator for older clients')]
public function testFormOmitsMode(): void
{
$request = ElicitRequest::forForm('Your name?', $this->createSchema());
$params = $this->paramsOf($request);
$this->assertArrayNotHasKey('mode', $params);
$this->assertArrayHasKey('requestedSchema', $params);
$this->assertSame(ElicitationMode::Form, $request->mode);
}
#[TestDox('url elicitation carries mode and url, and no schema')]
public function testUrlCarriesModeAndUrl(): void
{
$request = ElicitRequest::forUrl('Finish setup', 'https://example.com/setup');
$params = $this->paramsOf($request);
$this->assertSame('url', $params['mode']);
$this->assertSame('https://example.com/setup', $params['url']);
$this->assertArrayNotHasKey('requestedSchema', $params);
$this->assertNull($request->requestedSchema);
}
#[TestDox('a request without mode is still read as form elicitation')]
public function testAbsentModeDefaultsToForm(): void
{
$request = $this->requestFromParams([
'message' => 'Your name?',
'requestedSchema' => [
'type' => 'object',
'properties' => ['name' => ['type' => 'string', 'title' => 'Name']],
],
]);
$this->assertSame(ElicitationMode::Form, $request->mode);
$this->assertNotNull($request->requestedSchema);
}
#[TestDox('parses an explicit url-mode request')]
public function testParsesUrlMode(): void
{
$request = $this->requestFromParams([
'message' => 'Finish setup',
'mode' => 'url',
'url' => 'https://example.com/setup',
]);
$this->assertSame(ElicitationMode::Url, $request->mode);
$this->assertSame('https://example.com/setup', $request->url);
}
#[TestDox('url mode without a url is rejected')]
public function testUrlModeRequiresUrl(): void
{
$this->expectException(InvalidArgumentException::class);
$this->requestFromParams(['message' => 'Finish setup', 'mode' => 'url']);
}
#[TestDox('form mode without a schema is rejected')]
public function testFormModeRequiresSchema(): void
{
$this->expectException(InvalidArgumentException::class);
$this->requestFromParams(['message' => 'Your name?']);
}
#[TestDox('an unknown mode is rejected rather than silently treated as a form')]
public function testUnknownModeRejected(): void
{
$this->expectException(InvalidArgumentException::class);
$this->requestFromParams(['message' => 'hi', 'mode' => 'telepathy']);
}
#[TestDox('an explicit null mode is rejected rather than defaulting to form')]
public function testNullModeRejected(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid "mode" parameter');
$this->requestFromParams([
'message' => 'Your name?',
'mode' => null,
'requestedSchema' => [
'type' => 'object',
'properties' => ['name' => ['type' => 'string', 'title' => 'Name']],
],
]);
}
private function createSchema(): ElicitationSchema
{
return new ElicitationSchema(['name' => new StringSchemaDefinition('Name')], ['name']);
}
/**
* @param array<string, mixed> $params
*/
private function requestFromParams(array $params): ElicitRequest
{
return ElicitRequest::fromArray([
'jsonrpc' => MessageInterface::JSONRPC_VERSION,
'id' => 'request-1',
'method' => ElicitRequest::getMethod(),
'params' => $params,
]);
}
/**
* @return array<string, mixed>
*/
private function paramsOf(ElicitRequest $request): array
{
/** @var array{params?: array<string, mixed>} $encoded */
$encoded = json_decode(json_encode($request->withId('request-1')) ?: '', true);
return $encoded['params'] ?? [];
}
}

View file

@ -12,6 +12,7 @@
namespace Mcp\Tests\Unit\Schema;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Schema\Enum\IconTheme;
use Mcp\Schema\Icon;
use PHPUnit\Framework\TestCase;
@ -85,4 +86,19 @@ class IconTest extends TestCase
$this->assertSame($dataUri, $icon->src);
}
public function testFromArrayReadsTheme(): void
{
$icon = Icon::fromArray(['src' => 'https://example.com/icon.png', 'theme' => 'dark']);
$this->assertSame(IconTheme::Dark, $icon->theme);
$this->assertSame('dark', $icon->jsonSerialize()['theme']);
}
public function testFromArrayRejectsUnknownTheme(): void
{
$this->expectException(InvalidArgumentException::class);
Icon::fromArray(['src' => 'https://example.com/icon.png', 'theme' => 'sepia']);
}
}

View file

@ -26,6 +26,7 @@ final class ImplementationTest extends TestCase
$this->assertNull($implementation->description);
$this->assertNull($implementation->icons);
$this->assertNull($implementation->websiteUrl);
$this->assertNull($implementation->title);
}
public function testFromArrayWithMinimalData(): void
@ -148,6 +149,36 @@ final class ImplementationTest extends TestCase
Implementation::fromArray(['name' => 'my-client', 'version' => '1.0.0', 'icons' => 'nope']);
}
public function testFromArrayThrowsOnNonStringDescription(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid "description" in Implementation data.');
/* @phpstan-ignore argument.type */
Implementation::fromArray(['name' => 'my-client', 'version' => '1.0.0', 'description' => 42]);
}
public function testFromArrayThrowsOnNonStringTitle(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid "title" in Implementation data.');
/* @phpstan-ignore argument.type */
Implementation::fromArray(['name' => 'my-client', 'version' => '1.0.0', 'title' => ['nope']]);
}
public function testFromArrayReadsTitle(): void
{
$implementation = Implementation::fromArray([
'name' => 'my-client',
'version' => '1.0.0',
'title' => 'My Client',
]);
$this->assertSame('My Client', $implementation->title);
$this->assertArrayHasKey('title', $implementation->jsonSerialize());
}
public function testJsonSerializeRoundTrip(): void
{
$implementation = Implementation::fromArray([

View file

@ -0,0 +1,78 @@
<?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\JsonRpc;
use Mcp\Schema\ClientCapabilities;
use Mcp\Schema\Enum\ProtocolVersion;
use Mcp\Schema\JsonRpc\Error;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
class ErrorCodesTest extends TestCase
{
#[TestDox('header mismatch carries -32020')]
public function testHeaderMismatch(): void
{
$error = Error::forHeaderMismatch('Header does not match body', 'req-1');
$this->assertSame(Error::HEADER_MISMATCH, $error->code);
$this->assertSame(-32020, $error->code);
}
#[TestDox('missing client capability carries -32021 and the required capabilities')]
public function testMissingClientCapability(): void
{
$error = Error::forMissingRequiredClientCapability(
'Sampling is required',
new ClientCapabilities(sampling: true),
'req-1',
);
$this->assertSame(-32021, $error->code);
/** @var array{requiredCapabilities: ClientCapabilities} $data */
$data = $error->data;
$this->assertInstanceOf(ClientCapabilities::class, $data['requiredCapabilities']);
$encoded = json_decode(json_encode($error) ?: '', true);
$this->assertArrayHasKey('sampling', $encoded['error']['data']['requiredCapabilities']);
}
#[TestDox('unsupported version carries -32022 plus the requested and supported versions')]
public function testUnsupportedProtocolVersion(): void
{
$error = Error::forUnsupportedProtocolVersion(
'1900-01-01',
[ProtocolVersion::V2025_11_25, ProtocolVersion::V2025_06_18],
'req-1',
);
$this->assertSame(-32022, $error->code);
$this->assertSame([
'requested' => '1900-01-01',
'supported' => ['2025-11-25', '2025-06-18'],
], $error->data);
}
#[TestDox('the supported list survives JSON encoding as a plain array')]
public function testUnsupportedVersionEncoding(): void
{
$error = Error::forUnsupportedProtocolVersion('1900-01-01', ProtocolVersion::handshakeVersions(), 'req-1');
$encoded = json_decode(json_encode($error) ?: '', true);
$this->assertSame(
array_map(static fn (ProtocolVersion $v): string => $v->value, ProtocolVersion::handshakeVersions()),
$encoded['error']['data']['supported'],
);
}
}

View file

@ -0,0 +1,166 @@
<?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\Content\TextContent;
use Mcp\Schema\Result\CallToolResult;
use Mcp\Schema\Tool;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
/**
* SEP-2106 dropped the object-only restriction on `outputSchema` and widened
* `structuredContent` to any JSON value.
*/
class NonObjectOutputSchemaTest extends TestCase
{
/**
* @return array{type: 'object', properties: array<string, mixed>, required: string[]|null}
*/
private static function validInputSchema(): array
{
return [
'type' => 'object',
'properties' => ['q' => ['type' => 'string']],
'required' => null,
];
}
/**
* @param array<string, mixed> $outputSchema
*/
#[TestDox('outputSchema accepts a non-object root')]
#[DataProvider('provideNonObjectSchemas')]
public function testAcceptsNonObjectOutputSchema(array $outputSchema): void
{
$tool = Tool::fromArray([
'name' => 'demo',
'inputSchema' => self::validInputSchema(),
'outputSchema' => $outputSchema,
]);
$this->assertSame($outputSchema, $tool->outputSchema);
}
/**
* @return iterable<string, array{array<string, mixed>}>
*/
public static function provideNonObjectSchemas(): iterable
{
yield 'array' => [['type' => 'array', 'items' => ['type' => 'string']]];
yield 'string' => [['type' => 'string']];
yield 'number' => [['type' => 'number']];
yield 'boolean' => [['type' => 'boolean']];
yield 'composition without a root type' => [['oneOf' => [['type' => 'string'], ['type' => 'number']]]];
}
#[TestDox('inputSchema still requires an object root, since tool arguments are always an object')]
public function testInputSchemaStillRequiresObjectRoot(): void
{
$this->expectException(InvalidArgumentException::class);
/* @phpstan-ignore-next-line argument.type (deliberately invalid: an array root must be rejected) */
Tool::fromArray([
'name' => 'demo',
'inputSchema' => ['type' => 'array', 'properties' => [], 'required' => null],
]);
}
#[TestDox('structuredContent holds any JSON value')]
#[DataProvider('provideStructuredValues')]
public function testStructuredContentHoldsAnyJsonValue(mixed $value): void
{
$result = new CallToolResult([new TextContent('ok')], false, $value);
$this->assertSame($value, $result->structuredContent);
}
/**
* @return iterable<string, array{mixed}>
*/
public static function provideStructuredValues(): iterable
{
yield 'list' => [[1, 2, 3]];
yield 'string' => ['hello'];
yield 'int' => [42];
yield 'float' => [1.5];
yield 'true' => [true];
yield 'zero' => [0];
yield 'false' => [false];
yield 'empty string' => [''];
yield 'empty array' => [[]];
}
/**
* `null` is the only value that means absent, so every other JSON value —
* falsy ones included — reaches the wire. This matches the sibling field on
* {@see \Mcp\Schema\Content\ToolResultContent}, which carries the same tool
* result inside a sampling turn.
*/
#[TestDox('every non-null value reaches the wire, falsy ones included')]
#[DataProvider('provideStructuredValues')]
public function testNonNullValueIsSerialized(mixed $value): void
{
$result = new CallToolResult([new TextContent('ok')], false, $value);
$serialized = $result->jsonSerialize();
$this->assertArrayHasKey('structuredContent', $serialized);
$this->assertSame($value, $serialized['structuredContent']);
}
#[TestDox('a null structuredContent is omitted entirely')]
public function testNullStructuredContentOmitted(): void
{
$result = new CallToolResult([new TextContent('ok')]);
$this->assertArrayNotHasKey('structuredContent', $result->jsonSerialize());
}
#[TestDox('round-trips any JSON structuredContent through fromArray')]
#[DataProvider('provideStructuredValues')]
public function testRoundTrip(mixed $value): void
{
$result = CallToolResult::fromArray([
'content' => [['type' => 'text', 'text' => 'ok']],
'structuredContent' => $value,
]);
$this->assertSame($value, $result->structuredContent);
}
#[TestDox('an object structuredContent still round-trips unchanged')]
public function testObjectRoundTrip(): void
{
$result = CallToolResult::fromArray([
'content' => [['type' => 'text', 'text' => 'ok']],
'structuredContent' => ['temperature' => 22.5],
]);
$this->assertSame(['temperature' => 22.5], $result->structuredContent);
$this->assertSame(['temperature' => 22.5], $result->jsonSerialize()['structuredContent']);
}
#[TestDox('the empty root schema serializes as {} rather than []')]
public function testEmptyOutputSchemaSerializesAsObject(): void
{
$tool = Tool::fromArray([
'name' => 'demo',
'inputSchema' => self::validInputSchema(),
'outputSchema' => [],
]);
$this->assertSame('{}', json_encode($tool->jsonSerialize()['outputSchema']));
}
}

View file

@ -13,6 +13,7 @@ namespace Mcp\Tests\Unit\Schema\Result;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Schema\Enum\ElicitAction;
use Mcp\Schema\Enum\ElicitationMode;
use Mcp\Schema\Result\ElicitResult;
use PHPUnit\Framework\TestCase;
@ -99,6 +100,23 @@ final class ElicitResultTest extends TestCase
ElicitResult::fromArray(['action' => 'accept']);
}
public function testFromArrayWithUrlModeAllowsContentlessAccept(): void
{
$result = ElicitResult::fromArray(['action' => 'accept'], ElicitationMode::Url);
$this->assertSame(ElicitAction::Accept, $result->action);
$this->assertNull($result->content);
$this->assertTrue($result->isAccepted());
}
public function testFromArrayWithExplicitFormModeRequiresContent(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Content must be provided when action is "accept"');
ElicitResult::fromArray(['action' => 'accept'], ElicitationMode::Form);
}
public function testIsAccepted(): void
{
$acceptResult = new ElicitResult(ElicitAction::Accept, ['name' => 'John']);
@ -159,4 +177,15 @@ final class ElicitResultTest extends TestCase
'action' => 'cancel',
], $result->jsonSerialize());
}
public function testUrlModeRejectsContent(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Content must not be provided for a url-mode elicitation result.');
ElicitResult::fromArray(
['action' => 'accept', 'content' => ['name' => 'Ada']],
ElicitationMode::Url,
);
}
}

View file

@ -60,4 +60,13 @@ final class ToolChoiceTest extends TestCase
/* @phpstan-ignore argument.type */
ToolChoice::fromArray(['mode' => 1]);
}
public function testExplicitNullModeIsRejected(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid "mode" in ToolChoice data.');
/* @phpstan-ignore argument.type (deliberately null, as malformed wire data would be) */
ToolChoice::fromArray(['mode' => null]);
}
}

View file

@ -18,6 +18,7 @@ use Mcp\Capability\Registry\ReferenceHandlerInterface;
use Mcp\Exception\LogicException;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\Extension\Apps\McpApps;
use Mcp\Schema\Implementation;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\CallToolRequest;
use Mcp\Schema\ServerCapabilities;
@ -206,6 +207,45 @@ final class BuilderTest extends TestCase
$this->assertFalse($capabilities->tools);
}
#[TestDox('setServerInfo() forwards the title to the advertised serverInfo')]
public function testSetServerInfoForwardsTitle(): void
{
$server = Server::builder()
->setServerInfo('test', '1.0.0', 'A test server', null, 'https://example.com', 'Test Server')
->build();
$serverInfo = $this->extractServerInfo($server);
$this->assertSame('test', $serverInfo->name);
$this->assertSame('A test server', $serverInfo->description);
$this->assertSame('https://example.com', $serverInfo->websiteUrl);
$this->assertSame('Test Server', $serverInfo->title);
}
#[TestDox('setServerInfo() leaves the title absent when it is not given')]
public function testSetServerInfoTitleIsOptional(): void
{
$server = Server::builder()
->setServerInfo('test', '1.0.0')
->build();
$this->assertNull($this->extractServerInfo($server)->title);
}
private function extractServerInfo(Server $server): Implementation
{
$protocol = (new \ReflectionClass($server))->getProperty('protocol')->getValue($server);
$requestHandlers = (new \ReflectionClass($protocol))->getProperty('requestHandlers')->getValue($protocol);
foreach ($requestHandlers as $handler) {
if ($handler instanceof InitializeHandler) {
return $handler->configuration->serverInfo;
}
}
$this->fail('InitializeHandler not found in request handlers');
}
private function extractServerCapabilities(Server $server): ServerCapabilities
{
$protocol = (new \ReflectionClass($server))->getProperty('protocol')->getValue($server);

View file

@ -12,9 +12,18 @@
namespace Mcp\Tests\Unit\Server;
use Mcp\Exception\ClientException;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Schema\ClientCapabilities;
use Mcp\Schema\Elicitation\ElicitationSchema;
use Mcp\Schema\Elicitation\StringSchemaDefinition;
use Mcp\Schema\Enum\ElicitAction;
use Mcp\Schema\Enum\ElicitationMode;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\ElicitRequest;
use Mcp\Schema\Request\ListRootsRequest;
use Mcp\Schema\Result\ElicitResult;
use Mcp\Schema\Result\ListRootsResult;
use Mcp\Server\ClientGateway;
use Mcp\Server\Session\SessionInterface;
@ -63,6 +72,76 @@ final class ClientGatewayTest extends TestCase
$this->assertFalse($gateway->supportsSampling());
}
public function testSupportsSamplingToolsReflectsTheSubCapability(): void
{
$this->assertTrue($this->gatewayFor(['sampling' => ['tools' => []]])->supportsSamplingTools());
$this->assertFalse($this->gatewayFor(['sampling' => []])->supportsSamplingTools());
$this->assertFalse($this->gatewayFor([])->supportsSamplingTools());
}
public function testSupportsSamplingToolsReadsTheObjectShapeToo(): void
{
$capabilities = (new ClientCapabilities(samplingTools: true))->jsonSerialize();
$this->assertTrue($this->gatewayFor((array) $capabilities)->supportsSamplingTools());
}
public function testSupportsElicitationUrlReflectsTheSubCapability(): void
{
$this->assertTrue($this->gatewayFor(['elicitation' => ['url' => []]])->supportsElicitationUrl());
// An `elicitation` naming no mode declares form mode alone.
$this->assertFalse($this->gatewayFor(['elicitation' => []])->supportsElicitationUrl());
$this->assertFalse($this->gatewayFor(['elicitation' => ['form' => []]])->supportsElicitationUrl());
}
public function testElicitUrlSendsAUrlModeRequest(): void
{
$gateway = $this->gatewayFor(['elicitation' => ['url' => []]]);
$request = null;
$result = $this->runInFiber(
static fn (): ElicitResult => $gateway->elicitUrl('Authorize the app', 'https://example.com/consent'),
// A url-mode accept carries no content — the interaction happened out of band.
$this->response(['action' => 'accept']),
ElicitRequest::class,
$request,
);
$this->assertInstanceOf(ElicitRequest::class, $request);
$this->assertSame(ElicitationMode::Url, $request->mode);
$this->assertSame('https://example.com/consent', $request->url);
$this->assertInstanceOf(ElicitResult::class, $result);
$this->assertSame(ElicitAction::Accept, $result->action);
$this->assertNull($result->content);
}
public function testElicitUrlRejectsAClientThatOnlySupportsForms(): void
{
$gateway = $this->gatewayFor(['elicitation' => []]);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessageMatches('/elicitation\.url/');
$gateway->elicitUrl('Authorize the app', 'https://example.com/consent');
}
public function testElicitStillSendsFormMode(): void
{
$gateway = $this->gatewayFor([]);
$request = null;
$result = $this->runInFiber(
static fn (): ElicitResult => $gateway->elicit('Your name?', new ElicitationSchema(['name' => new StringSchemaDefinition('Name')])),
$this->response(['action' => 'accept', 'content' => ['name' => 'Ada']]),
ElicitRequest::class,
$request,
);
$this->assertInstanceOf(ElicitRequest::class, $request);
$this->assertSame(ElicitationMode::Form, $request->mode);
$this->assertSame(['name' => 'Ada'], $result->content);
}
public function testListRootsReturnsRootsFromClient(): void
{
$session = $this->createMock(SessionInterface::class);
@ -98,19 +177,39 @@ final class ClientGatewayTest extends TestCase
}
/**
* Runs the gateway call inside a Fiber, asserts it suspends with a roots/list
* @param array<string, mixed> $capabilities the client capabilities the session reports
*/
private function gatewayFor(array $capabilities): ClientGateway
{
$session = $this->createMock(SessionInterface::class);
$session->method('getId')->willReturn(Uuid::v4());
$session->method('get')->willReturnCallback(
static fn (string $key, mixed $default = null): mixed => 'client_capabilities' === $key ? $capabilities : $default,
);
return new ClientGateway($session);
}
/**
* Runs the gateway call inside a Fiber, asserts it suspends with the expected
* request, then resumes it with the given client response.
*
* @param Response<array<string, mixed>>|Error $response
* @param class-string<Request> $expectedRequest
* @param ?Request $request receives the request the gateway suspended with
*
* @param-out Request $request
*/
private function runInFiber(\Closure $call, Response|Error $response): mixed
private function runInFiber(\Closure $call, Response|Error $response, string $expectedRequest = ListRootsRequest::class, mixed &$request = null): mixed
{
$fiber = new \Fiber($call);
$suspend = $fiber->start();
$this->assertIsArray($suspend);
$this->assertSame('request', $suspend['type']);
$this->assertInstanceOf(ListRootsRequest::class, $suspend['request']);
$this->assertInstanceOf($expectedRequest, $suspend['request']);
$request = $suspend['request'];
$fiber->resume($response);