php-sdk/tests/Unit/Server/Handler/Request/GetPromptHandlerTest.php
Christopher Hertel 5e73683079
[Server] Close the conformance gaps in the modern lifecycle (#447)
* [Server] Let the client gateway see modern-era capabilities

The six supports*() probes read session state only InitializeHandler wrote,
so every request served statelessly reported no client capabilities at all —
a tool guarding on them took the unsupported branch without a signal.
StatelessProtocol now writes the request's declaration under the same keys.

* [Server] Reject the RPCs 2026-07-28 removed

resources/subscribe and resources/unsubscribe were still dispatched and
answered 200 OK, recording subscriptions the modern era never reads. They
join initialize, ping and logging/setLevel in the era guard; the handlers
stay registered because the handshake era still serves them.

* [Server] Decode a wrapped Mcp-Name before comparing it

The Base64 sentinel was only unwrapped for Mcp-Param-*, so any resource URI
or tool name outside the header-safe ASCII set — which the spec explicitly
tells clients to wrap — was compared encoded and refused with -32020.

* [Server] Require the MCP-Protocol-Version header

It was only checked for contradicting the body, so omitting it entirely
passed — leaving the value intermediaries route on unenforced. Tied to the
header validator's presence, since that is what a header-bearing transport
installs and stdio carries its metadata inline.

* [Server] Read the modern-era request body whole

A single read() takes whatever the stream cares to give — 64 bytes from a
chunked transfer is legal — so an oversized-but-valid POST came back as a
parse error. Shares the legacy transport's incremental read as a trait.

* [Schema][Server] Answer a notification with a status, not a response

A body with no id was dispatched as a request and came back as a JSON-RPC
error carrying "id": "" — an id nobody issued, and on a path a client uses
to tell a modern server from a legacy one. Notifications now get 202 and no
body, and Error omits an id it could not read instead of emptying it.

* [Server] Stop emitting the error codes 2026-07-28 reserved

resources/read answered -32002, which this revision forbids; prompts/get
and completion/complete answered it for an unknown *name*, which it never
meant; tools/call answered -32601, which belongs to an unknown method.
Only the resources/read code is revision-gated — older peers expect -32002
there, and nowhere else. Also routes the -32021 capability exception out of
the prompt and resource handlers, which were swallowing it into -32603.
2026-08-18 23:09:34 +02:00

451 lines
16 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\Handler\Request;
use Mcp\Capability\Registry\PromptReference;
use Mcp\Capability\Registry\ReferenceHandlerInterface;
use Mcp\Capability\RegistryInterface;
use Mcp\Exception\PromptGetException;
use Mcp\Exception\PromptNotFoundException;
use Mcp\Schema\Content\PromptMessage;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\Enum\Role;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\GetPromptRequest;
use Mcp\Schema\Result\GetPromptResult;
use Mcp\Server\Handler\Request\GetPromptHandler;
use Mcp\Server\Session\SessionInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
class GetPromptHandlerTest extends TestCase
{
private GetPromptHandler $handler;
private RegistryInterface&MockObject $referenceProvider;
private ReferenceHandlerInterface&MockObject $referenceHandler;
private SessionInterface&MockObject $session;
private LoggerInterface&MockObject $logger;
protected function setUp(): void
{
$this->referenceProvider = $this->createMock(RegistryInterface::class);
$this->referenceHandler = $this->createMock(ReferenceHandlerInterface::class);
$this->session = $this->createMock(SessionInterface::class);
$this->logger = $this->createMock(LoggerInterface::class);
$this->handler = new GetPromptHandler($this->referenceProvider, $this->referenceHandler, $this->logger);
}
public function testSupportsGetPromptRequest(): void
{
$request = $this->createGetPromptRequest('test_prompt');
$this->assertTrue($this->handler->supports($request));
}
public function testHandleSuccessfulPromptGet(): void
{
$request = $this->createGetPromptRequest('greeting_prompt');
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Hello, how can I help you?')),
];
$expectedResult = new GetPromptResult($expectedMessages);
$promptReference = $this->createMock(PromptReference::class);
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('greeting_prompt')
->willReturn($promptReference);
$this->referenceHandler
->expects($this->once())
->method('handle')
->with($promptReference, ['_session' => $this->session, '_request' => $request])
->willReturn($expectedMessages);
$promptReference
->expects($this->once())
->method('formatResult')
->with($expectedMessages)
->willReturn($expectedMessages);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals($expectedResult, $response->result);
}
public function testHandlePromptGetWithArguments(): void
{
$arguments = [
'name' => 'John',
'context' => 'business meeting',
'formality' => 'formal',
];
$request = $this->createGetPromptRequest('personalized_prompt', $arguments);
$expectedMessages = [
new PromptMessage(
Role::User,
new TextContent('Good morning, John. How may I assist you in your business meeting?'),
),
];
$expectedResult = new GetPromptResult($expectedMessages);
$promptReference = $this->createMock(PromptReference::class);
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('personalized_prompt')
->willReturn($promptReference);
$this->referenceHandler
->expects($this->once())
->method('handle')
->with($promptReference, array_merge($arguments, ['_session' => $this->session, '_request' => $request]))
->willReturn($expectedMessages);
$promptReference
->expects($this->once())
->method('formatResult')
->with($expectedMessages)
->willReturn($expectedMessages);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($expectedResult, $response->result);
}
public function testHandlePromptGetWithNullArguments(): void
{
$request = $this->createGetPromptRequest('simple_prompt', null);
$expectedMessages = [
new PromptMessage(Role::Assistant, new TextContent('I am ready to help.')),
];
$expectedResult = new GetPromptResult($expectedMessages);
$promptReference = $this->createMock(PromptReference::class);
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('simple_prompt')
->willReturn($promptReference);
$this->referenceHandler
->expects($this->once())
->method('handle')
->with($promptReference, ['_session' => $this->session, '_request' => $request])
->willReturn($expectedMessages);
$promptReference
->expects($this->once())
->method('formatResult')
->with($expectedMessages)
->willReturn($expectedMessages);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($expectedResult, $response->result);
}
public function testHandlePromptGetWithEmptyArguments(): void
{
$request = $this->createGetPromptRequest('empty_args_prompt', []);
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Default message')),
];
$expectedResult = new GetPromptResult($expectedMessages);
$promptReference = $this->createMock(PromptReference::class);
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('empty_args_prompt')
->willReturn($promptReference);
$this->referenceHandler
->expects($this->once())
->method('handle')
->with($promptReference, ['_session' => $this->session, '_request' => $request])
->willReturn($expectedMessages);
$promptReference
->expects($this->once())
->method('formatResult')
->with($expectedMessages)
->willReturn($expectedMessages);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($expectedResult, $response->result);
}
public function testHandlePromptGetWithMultipleMessages(): void
{
$request = $this->createGetPromptRequest('conversation_prompt');
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Hello')),
new PromptMessage(Role::Assistant, new TextContent('Hi there! How can I help you today?')),
new PromptMessage(Role::User, new TextContent('I need assistance with my project')),
];
$expectedResult = new GetPromptResult($expectedMessages);
$promptReference = $this->createMock(PromptReference::class);
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('conversation_prompt')
->willReturn($promptReference);
$this->referenceHandler
->expects($this->once())
->method('handle')
->with($promptReference, ['_session' => $this->session, '_request' => $request])
->willReturn($expectedMessages);
$promptReference
->expects($this->once())
->method('formatResult')
->with($expectedMessages)
->willReturn($expectedMessages);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($expectedResult, $response->result);
}
public function testHandlePromptNotFoundExceptionReturnsError(): void
{
$request = $this->createGetPromptRequest('nonexistent_prompt');
$exception = new PromptNotFoundException('nonexistent_prompt');
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('nonexistent_prompt')
->willThrowException($exception);
$this->logger
->expects($this->once())
->method('error')
->with('Prompt not found', ['prompt_name' => 'nonexistent_prompt', 'exception' => $exception]);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals(Error::INVALID_PARAMS, $response->code);
$this->assertEquals('Prompt not found: "nonexistent_prompt".', $response->message);
}
public function testHandlePromptGetExceptionReturnsError(): void
{
$request = $this->createGetPromptRequest('failing_prompt');
$exception = new PromptGetException('Failed to get prompt');
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('failing_prompt')
->willThrowException($exception);
$this->logger
->expects($this->once())
->method('error')
->with('Error while handling prompt "failing_prompt": "Failed to get prompt".', ['exception' => $exception]);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Error::class, $response);
$this->assertEquals($request->getId(), $response->id);
$this->assertEquals(Error::INTERNAL_ERROR, $response->code);
$this->assertEquals('Failed to get prompt', $response->message);
}
public function testHandlePromptGetWithComplexArguments(): void
{
$arguments = [
'user_data' => [
'name' => 'Alice',
'preferences' => ['formal', 'concise'],
'history' => [
'last_interaction' => '2025-01-15',
'topics' => ['technology', 'business'],
],
],
'context' => 'technical consultation',
'metadata' => [
'session_id' => 'sess_123456',
'timestamp' => 1705392000,
],
];
$request = $this->createGetPromptRequest('complex_prompt', $arguments);
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Complex prompt generated with all parameters')),
];
$expectedResult = new GetPromptResult($expectedMessages);
$promptReference = $this->createMock(PromptReference::class);
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('complex_prompt')
->willReturn($promptReference);
$this->referenceHandler
->expects($this->once())
->method('handle')
->with($promptReference, array_merge($arguments, ['_session' => $this->session, '_request' => $request]))
->willReturn($expectedMessages);
$promptReference
->expects($this->once())
->method('formatResult')
->with($expectedMessages)
->willReturn($expectedMessages);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($expectedResult, $response->result);
}
public function testHandlePromptGetWithSpecialCharacters(): void
{
$arguments = [
'message' => 'Hello 世界! How are you? 😊',
'special' => 'äöü ñ ß',
'quotes' => 'Text with "double" and \'single\' quotes',
];
$request = $this->createGetPromptRequest('unicode_prompt', $arguments);
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Unicode message processed')),
];
$expectedResult = new GetPromptResult($expectedMessages);
$promptReference = $this->createMock(PromptReference::class);
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('unicode_prompt')
->willReturn($promptReference);
$this->referenceHandler
->expects($this->once())
->method('handle')
->with($promptReference, array_merge($arguments, ['_session' => $this->session, '_request' => $request]))
->willReturn($expectedMessages);
$promptReference
->expects($this->once())
->method('formatResult')
->with($expectedMessages)
->willReturn($expectedMessages);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($expectedResult, $response->result);
}
public function testHandlePromptGetReturnsEmptyMessages(): void
{
$request = $this->createGetPromptRequest('empty_prompt');
$expectedResult = new GetPromptResult([]);
$promptReference = $this->createMock(PromptReference::class);
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('empty_prompt')
->willReturn($promptReference);
$this->referenceHandler
->expects($this->once())
->method('handle')
->with($promptReference, ['_session' => $this->session, '_request' => $request])
->willReturn([]);
$promptReference
->expects($this->once())
->method('formatResult')
->with([])
->willReturn([]);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($expectedResult, $response->result);
}
public function testHandlePromptGetWithLargeNumberOfArguments(): void
{
$arguments = [];
for ($i = 0; $i < 100; ++$i) {
$arguments["arg_{$i}"] = "value_{$i}";
}
$request = $this->createGetPromptRequest('many_args_prompt', $arguments);
$expectedMessages = [
new PromptMessage(Role::User, new TextContent('Processed 100 arguments')),
];
$expectedResult = new GetPromptResult($expectedMessages);
$promptReference = $this->createMock(PromptReference::class);
$this->referenceProvider
->expects($this->once())
->method('getPrompt')
->with('many_args_prompt')
->willReturn($promptReference);
$this->referenceHandler
->expects($this->once())
->method('handle')
->with($promptReference, array_merge($arguments, ['_session' => $this->session, '_request' => $request]))
->willReturn($expectedMessages);
$promptReference
->expects($this->once())
->method('formatResult')
->with($expectedMessages)
->willReturn($expectedMessages);
$response = $this->handler->handle($request, $this->session);
$this->assertInstanceOf(Response::class, $response);
$this->assertEquals($expectedResult, $response->result);
}
/**
* @param array<string, mixed>|null $arguments
*/
private function createGetPromptRequest(string $name, ?array $arguments = null): GetPromptRequest
{
return GetPromptRequest::fromArray([
'jsonrpc' => '2.0',
'method' => GetPromptRequest::getMethod(),
'id' => 'test-request-'.uniqid(),
'params' => [
'name' => $name,
'arguments' => $arguments,
],
]);
}
}