* [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.
309 lines
11 KiB
PHP
309 lines
11 KiB
PHP
<?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\Server;
|
|
|
|
use Mcp\Capability\Registry;
|
|
use Mcp\Capability\Registry\ElementReference;
|
|
use Mcp\Capability\Registry\Loader\LoaderInterface;
|
|
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;
|
|
use Mcp\Schema\Tool;
|
|
use Mcp\Server;
|
|
use Mcp\Server\Handler\Request\CallToolHandler;
|
|
use Mcp\Server\Handler\Request\InitializeHandler;
|
|
use Mcp\Server\Session\SessionInterface;
|
|
use PHPUnit\Framework\Attributes\TestDox;
|
|
use PHPUnit\Framework\TestCase;
|
|
|
|
final class BuilderTest extends TestCase
|
|
{
|
|
#[TestDox('setReferenceHandler() returns the builder for fluent chaining')]
|
|
public function testSetReferenceHandlerReturnsSelf(): void
|
|
{
|
|
$referenceHandler = $this->createStub(ReferenceHandlerInterface::class);
|
|
|
|
$builder = Server::builder();
|
|
$result = $builder->setReferenceHandler($referenceHandler);
|
|
|
|
$this->assertSame($builder, $result);
|
|
}
|
|
|
|
#[TestDox('build() succeeds with a custom ReferenceHandler')]
|
|
public function testBuildWithCustomReferenceHandler(): void
|
|
{
|
|
$referenceHandler = $this->createStub(ReferenceHandlerInterface::class);
|
|
|
|
$server = Server::builder()
|
|
->setServerInfo('test', '1.0.0')
|
|
->setReferenceHandler($referenceHandler)
|
|
->build();
|
|
|
|
$this->assertInstanceOf(Server::class, $server);
|
|
}
|
|
|
|
#[TestDox('build() succeeds without a custom ReferenceHandler (uses default)')]
|
|
public function testBuildWithoutCustomReferenceHandler(): void
|
|
{
|
|
$server = Server::builder()
|
|
->setServerInfo('test', '1.0.0')
|
|
->build();
|
|
|
|
$this->assertInstanceOf(Server::class, $server);
|
|
}
|
|
|
|
#[TestDox('Custom ReferenceHandler is used when calling a tool')]
|
|
public function testCustomReferenceHandlerIsUsedForToolCalls(): void
|
|
{
|
|
$referenceHandler = $this->createMock(ReferenceHandlerInterface::class);
|
|
$referenceHandler->expects($this->once())
|
|
->method('handle')
|
|
->willReturnCallback(static function (ElementReference $reference, array $arguments): string {
|
|
return 'intercepted';
|
|
});
|
|
|
|
$server = Server::builder()
|
|
->setServerInfo('test', '1.0.0')
|
|
->setReferenceHandler($referenceHandler)
|
|
->addTool(static fn (): string => 'original', name: 'test_tool', description: 'A test tool')
|
|
->build();
|
|
|
|
$result = $this->callTool($server, 'test_tool');
|
|
|
|
$this->assertSame('intercepted', $result);
|
|
}
|
|
|
|
#[TestDox('A pre-built instance handler with constructor dependencies is registered and invoked on that instance')]
|
|
public function testPreBuiltInstanceHandlerIsInvokedOnTheGivenInstance(): void
|
|
{
|
|
// The handler's constructor requires an argument the container-less
|
|
// `new $className()` fallback can never satisfy. If the tool call
|
|
// succeeds, it can only be because the pre-built instance — carrying
|
|
// its injected dependency — was the one invoked.
|
|
$handler = new GreetingService('World');
|
|
|
|
$server = Server::builder()
|
|
->setServerInfo('test', '1.0.0')
|
|
->addTool(handler: [$handler, 'greet'], name: 'greet', description: 'Greets using the injected name')
|
|
->build();
|
|
|
|
$result = $this->callTool($server, 'greet');
|
|
|
|
$this->assertSame('Hello, World', $result);
|
|
}
|
|
|
|
#[TestDox('enableExtension() registers an extension and announces its capability payload')]
|
|
public function testEnableExtensionRegistersExtension(): void
|
|
{
|
|
$server = Server::builder()
|
|
->setServerInfo('test', '1.0.0')
|
|
->enableExtension(new McpApps())
|
|
->build();
|
|
|
|
$capabilities = $this->extractServerCapabilities($server);
|
|
|
|
$this->assertNotNull($capabilities->extensions);
|
|
$this->assertArrayHasKey(McpApps::EXTENSION_ID, $capabilities->extensions);
|
|
$this->assertSame(['mimeTypes' => [McpApps::MIME_TYPE]], $capabilities->extensions[McpApps::EXTENSION_ID]);
|
|
}
|
|
|
|
#[TestDox('enableExtension() throws when the same extension is enabled twice')]
|
|
public function testEnableExtensionRejectsDuplicate(): void
|
|
{
|
|
$this->expectException(LogicException::class);
|
|
$this->expectExceptionMessage(McpApps::EXTENSION_ID);
|
|
|
|
Server::builder()->enableExtension(new McpApps(), new McpApps());
|
|
}
|
|
|
|
#[TestDox('enableExtension() extensions are merged into capabilities set via setCapabilities()')]
|
|
public function testEnableExtensionMergesIntoCustomCapabilities(): void
|
|
{
|
|
$server = Server::builder()
|
|
->setServerInfo('test', '1.0.0')
|
|
->setCapabilities(new ServerCapabilities(tools: true))
|
|
->enableExtension(new McpApps())
|
|
->build();
|
|
|
|
$capabilities = $this->extractServerCapabilities($server);
|
|
|
|
$this->assertNotNull($capabilities->extensions);
|
|
$this->assertArrayHasKey(McpApps::EXTENSION_ID, $capabilities->extensions);
|
|
}
|
|
|
|
#[TestDox('build() advertises tools capability for a pre-populated registry set via setRegistry()')]
|
|
public function testBuildAdvertisesToolsForPreloadedCustomRegistry(): void
|
|
{
|
|
$registry = new Registry();
|
|
$registry->registerTool(
|
|
new Tool(name: 'test_tool', title: null, inputSchema: ['type' => 'object', 'properties' => [], 'required' => null], description: 'A test tool', annotations: null),
|
|
static fn (): string => 'result',
|
|
);
|
|
|
|
$server = Server::builder()
|
|
->setServerInfo('test', '1.0.0')
|
|
->setRegistry($registry)
|
|
->build();
|
|
|
|
$capabilities = $this->extractServerCapabilities($server);
|
|
|
|
$this->assertTrue($capabilities->tools);
|
|
}
|
|
|
|
#[TestDox('setLazyLoading() returns the builder for fluent chaining')]
|
|
public function testSetLazyLoadingReturnsSelf(): void
|
|
{
|
|
$builder = Server::builder();
|
|
|
|
$this->assertSame($builder, $builder->setLazyLoading(false));
|
|
}
|
|
|
|
#[TestDox('Lazy loading (default) advertises tools from configured sources without running loaders')]
|
|
public function testLazyLoadingAdvertisesFromConfiguredSourcesWithoutLoading(): void
|
|
{
|
|
$loader = $this->createMock(LoaderInterface::class);
|
|
$loader->expects($this->never())->method('load');
|
|
|
|
$server = Server::builder()
|
|
->setServerInfo('test', '1.0.0')
|
|
->addLoader($loader)
|
|
->build();
|
|
|
|
$capabilities = $this->extractServerCapabilities($server);
|
|
|
|
// A custom loader is opaque, so its presence advertises tools even though it never ran.
|
|
$this->assertTrue($capabilities->tools);
|
|
}
|
|
|
|
#[TestDox('Eager loading runs the loaders at build time and advertises from the loaded registry')]
|
|
public function testEagerLoadingAdvertisesFromLoadedRegistry(): void
|
|
{
|
|
$loader = $this->createMock(LoaderInterface::class);
|
|
$loader->expects($this->once())->method('load');
|
|
|
|
$server = Server::builder()
|
|
->setServerInfo('test', '1.0.0')
|
|
->setLazyLoading(false)
|
|
->addLoader($loader)
|
|
->build();
|
|
|
|
$capabilities = $this->extractServerCapabilities($server);
|
|
|
|
// The loader ran but registered nothing, so the loaded registry advertises no tools.
|
|
$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);
|
|
$requestHandlers = (new \ReflectionClass($protocol))->getProperty('requestHandlers')->getValue($protocol);
|
|
|
|
foreach ($requestHandlers as $handler) {
|
|
if ($handler instanceof InitializeHandler) {
|
|
return $handler->configuration->capabilities;
|
|
}
|
|
}
|
|
|
|
$this->fail('InitializeHandler not found in request handlers');
|
|
}
|
|
|
|
private function callTool(Server $server, string $toolName): mixed
|
|
{
|
|
$protocol = (new \ReflectionClass($server))->getProperty('protocol')->getValue($server);
|
|
$requestHandlers = (new \ReflectionClass($protocol))->getProperty('requestHandlers')->getValue($protocol);
|
|
|
|
foreach ($requestHandlers as $handler) {
|
|
if ($handler instanceof CallToolHandler) {
|
|
$request = CallToolRequest::fromArray([
|
|
'jsonrpc' => '2.0',
|
|
'method' => 'tools/call',
|
|
'id' => 'test-1',
|
|
'params' => ['name' => $toolName, 'arguments' => []],
|
|
]);
|
|
$session = $this->createStub(SessionInterface::class);
|
|
|
|
$response = $handler->handle($request, $session);
|
|
|
|
if ($response instanceof Response) {
|
|
$content = $response->result->content[0] ?? null;
|
|
|
|
return $content instanceof TextContent ? $content->text : null;
|
|
}
|
|
|
|
$this->fail('Expected Response, got '.$response::class);
|
|
}
|
|
}
|
|
|
|
$this->fail('CallToolHandler not found in request handlers');
|
|
}
|
|
}
|
|
|
|
/**
|
|
* A handler whose constructor dependency cannot be satisfied by the
|
|
* container-less `new $className()` fallback, so it must be registered as a
|
|
* pre-built instance.
|
|
*/
|
|
final class GreetingService
|
|
{
|
|
public function __construct(private string $name)
|
|
{
|
|
}
|
|
|
|
public function greet(): string
|
|
{
|
|
return 'Hello, '.$this->name;
|
|
}
|
|
}
|