Add elicitation support for server-to-client user input requests (#228)
- Add ElicitAction enum (accept/decline/cancel) - Add schema definitions for elicitation fields (string, number, boolean, enum) - Add ElicitationSchema wrapper for requestedSchema - Add ElicitRequest and ElicitResult for elicitation/create method - Update ClientCapabilities to support elicitation capability - Add elicit() method to ClientGateway - Store client capabilities in session during initialization - Add comprehensive unit tests - Add elicitation example server with book_restaurant, confirm_action, and collect_feedback tools
This commit is contained in:
parent
aafac3ddf5
commit
02e86377e4
28 changed files with 2582 additions and 5 deletions
|
|
@ -59,6 +59,7 @@
|
|||
"Mcp\\Example\\Server\\ClientCommunication\\": "examples/server/client-communication/",
|
||||
"Mcp\\Example\\Server\\ClientLogging\\": "examples/server/client-logging/",
|
||||
"Mcp\\Example\\Server\\CombinedRegistration\\": "examples/server/combined-registration/",
|
||||
"Mcp\\Example\\Server\\Elicitation\\": "examples/server/elicitation/",
|
||||
"Mcp\\Example\\Server\\ComplexToolSchema\\": "examples/server/complex-tool-schema/",
|
||||
"Mcp\\Example\\Server\\Conformance\\": "examples/server/conformance/",
|
||||
"Mcp\\Example\\Server\\CustomDependencies\\": "examples/server/custom-dependencies/",
|
||||
|
|
|
|||
|
|
@ -276,3 +276,80 @@ public function formatText(
|
|||
string $format = 'sentence'
|
||||
): array
|
||||
```
|
||||
|
||||
### Elicitation
|
||||
|
||||
**File**: `examples/server/elicitation/`
|
||||
|
||||
**What it demonstrates:**
|
||||
- Server-to-client elicitation requests
|
||||
- Interactive user input during tool execution
|
||||
- Multi-field form schemas with validation
|
||||
- Boolean confirmation dialogs
|
||||
- Enum fields with human-readable labels
|
||||
- Handling accept/decline/cancel responses
|
||||
- Session persistence requirement for server-initiated requests
|
||||
|
||||
**Key Features:**
|
||||
```php
|
||||
// Check client support before eliciting
|
||||
if (!$context->getClientGateway()->supportsElicitation()) {
|
||||
return ['status' => 'error', 'message' => 'Client does not support elicitation'];
|
||||
}
|
||||
|
||||
// Build schema with multiple field types
|
||||
$schema = new ElicitationSchema(
|
||||
properties: [
|
||||
'party_size' => new NumberSchemaDefinition(
|
||||
title: 'Party Size',
|
||||
integerOnly: true,
|
||||
minimum: 1,
|
||||
maximum: 20
|
||||
),
|
||||
'date' => new StringSchemaDefinition(
|
||||
title: 'Reservation Date',
|
||||
format: 'date'
|
||||
),
|
||||
'dietary' => new EnumSchemaDefinition(
|
||||
title: 'Dietary Restrictions',
|
||||
enum: ['none', 'vegetarian', 'vegan'],
|
||||
enumNames: ['None', 'Vegetarian', 'Vegan']
|
||||
),
|
||||
],
|
||||
required: ['party_size', 'date']
|
||||
);
|
||||
|
||||
// Send elicitation request
|
||||
$result = $client->elicit(
|
||||
message: 'Please provide your reservation details',
|
||||
requestedSchema: $schema
|
||||
);
|
||||
|
||||
// Handle response
|
||||
if ($result->isAccepted()) {
|
||||
$data = $result->content; // User-provided data
|
||||
} elseif ($result->isDeclined() || $result->isCancelled()) {
|
||||
// User declined or cancelled
|
||||
}
|
||||
```
|
||||
|
||||
**Important Notes:**
|
||||
- Elicitation requires a session store (e.g., `FileSessionStore`)
|
||||
- Check client capabilities with `supportsElicitation()` before sending requests
|
||||
- Schema supports primitive types: string, number/integer, boolean, enum
|
||||
- String fields support format validation: date, date-time, email, uri
|
||||
- Users can accept (providing data), decline, or cancel requests
|
||||
|
||||
**Usage:**
|
||||
```bash
|
||||
# Interactive testing with MCP client that supports elicitation
|
||||
npx @modelcontextprotocol/inspector php examples/server/elicitation/server.php
|
||||
|
||||
# Test with Goose (confirmed working by reviewer)
|
||||
# Or configure in Claude Desktop or other MCP clients
|
||||
```
|
||||
|
||||
**Example Tools:**
|
||||
1. **book_restaurant** - Multi-field reservation form with number, date, and enum fields
|
||||
2. **confirm_action** - Simple boolean confirmation dialog
|
||||
3. **collect_feedback** - Rating and comments form with optional fields
|
||||
|
|
|
|||
293
examples/server/elicitation/ElicitationHandlers.php
Normal file
293
examples/server/elicitation/ElicitationHandlers.php
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Example\Server\Elicitation;
|
||||
|
||||
use Mcp\Capability\Attribute\McpTool;
|
||||
use Mcp\Schema\Elicitation\BooleanSchemaDefinition;
|
||||
use Mcp\Schema\Elicitation\ElicitationSchema;
|
||||
use Mcp\Schema\Elicitation\EnumSchemaDefinition;
|
||||
use Mcp\Schema\Elicitation\NumberSchemaDefinition;
|
||||
use Mcp\Schema\Elicitation\StringSchemaDefinition;
|
||||
use Mcp\Server\RequestContext;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
/**
|
||||
* Example handlers demonstrating the elicitation feature.
|
||||
*
|
||||
* Elicitation allows servers to request additional information from users
|
||||
* during tool execution. The user can accept (providing data), decline,
|
||||
* or cancel the request.
|
||||
*/
|
||||
final class ElicitationHandlers
|
||||
{
|
||||
public function __construct(
|
||||
private readonly LoggerInterface $logger,
|
||||
) {
|
||||
$this->logger->info('ElicitationHandlers instantiated.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Book a restaurant reservation with user elicitation.
|
||||
*
|
||||
* Demonstrates multi-field elicitation with different field types:
|
||||
* - Number field for party size with validation
|
||||
* - String field with date format for reservation date
|
||||
* - Enum field for dietary restrictions with human-readable labels
|
||||
*
|
||||
* @return array{status: string, message: string, booking?: array{party_size: int, date: string, dietary: string}}
|
||||
*/
|
||||
#[McpTool('book_restaurant', 'Book a restaurant reservation, collecting details via elicitation.')]
|
||||
public function bookRestaurant(RequestContext $context, string $restaurantName): array
|
||||
{
|
||||
if (!$context->getClientGateway()->supportsElicitation()) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => 'Client does not support elicitation. Please provide reservation details (party_size, date, dietary) as tool parameters instead.',
|
||||
];
|
||||
}
|
||||
|
||||
$client = $context->getClientGateway();
|
||||
|
||||
$this->logger->info(\sprintf('Starting reservation process for restaurant: %s', $restaurantName));
|
||||
|
||||
$schema = new ElicitationSchema(
|
||||
properties: [
|
||||
'party_size' => new NumberSchemaDefinition(
|
||||
title: 'Party Size',
|
||||
integerOnly: true,
|
||||
description: 'Number of guests in your party',
|
||||
default: 2,
|
||||
minimum: 1,
|
||||
maximum: 20,
|
||||
),
|
||||
'date' => new StringSchemaDefinition(
|
||||
title: 'Reservation Date',
|
||||
description: 'Preferred date for your reservation',
|
||||
format: 'date',
|
||||
),
|
||||
'dietary' => new EnumSchemaDefinition(
|
||||
title: 'Dietary Restrictions',
|
||||
enum: ['none', 'vegetarian', 'vegan', 'gluten-free', 'halal', 'kosher'],
|
||||
description: 'Any dietary restrictions or preferences',
|
||||
default: 'none',
|
||||
enumNames: ['None', 'Vegetarian', 'Vegan', 'Gluten-Free', 'Halal', 'Kosher'],
|
||||
),
|
||||
],
|
||||
required: ['party_size', 'date'],
|
||||
);
|
||||
|
||||
$result = $client->elicit(
|
||||
message: \sprintf('Please provide your reservation details for %s:', $restaurantName),
|
||||
requestedSchema: $schema,
|
||||
timeout: 120,
|
||||
);
|
||||
|
||||
if ($result->isDeclined()) {
|
||||
$this->logger->info('User declined to provide reservation details.');
|
||||
|
||||
return [
|
||||
'status' => 'declined',
|
||||
'message' => 'Reservation request was declined by user.',
|
||||
];
|
||||
}
|
||||
|
||||
if ($result->isCancelled()) {
|
||||
$this->logger->info('User cancelled the reservation request.');
|
||||
|
||||
return [
|
||||
'status' => 'cancelled',
|
||||
'message' => 'Reservation request was cancelled.',
|
||||
];
|
||||
}
|
||||
|
||||
$content = $result->content;
|
||||
if (null === $content) {
|
||||
throw new \RuntimeException('Expected content for accepted elicitation.');
|
||||
}
|
||||
|
||||
if (!isset($content['party_size']) || !isset($content['date'])) {
|
||||
throw new \RuntimeException('Missing required fields: party_size and date.');
|
||||
}
|
||||
|
||||
$partySize = (int) $content['party_size'];
|
||||
$date = (string) $content['date'];
|
||||
$dietary = (string) ($content['dietary'] ?? 'none');
|
||||
|
||||
if ($partySize < 1 || $partySize > 20) {
|
||||
throw new \RuntimeException(\sprintf('Invalid party size: %d. Must be between 1 and 20.', $partySize));
|
||||
}
|
||||
|
||||
$this->logger->info(\sprintf(
|
||||
'Booking confirmed: %d guests on %s with %s dietary requirements',
|
||||
$partySize,
|
||||
$date,
|
||||
$dietary,
|
||||
));
|
||||
|
||||
return [
|
||||
'status' => 'confirmed',
|
||||
'message' => \sprintf(
|
||||
'Reservation confirmed at %s for %d guests on %s.',
|
||||
$restaurantName,
|
||||
$partySize,
|
||||
$date,
|
||||
),
|
||||
'booking' => [
|
||||
'party_size' => $partySize,
|
||||
'date' => $date,
|
||||
'dietary' => $dietary,
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Confirm an action with a simple boolean elicitation.
|
||||
*
|
||||
* Demonstrates the simplest elicitation pattern - a yes/no confirmation.
|
||||
*
|
||||
* @return array{status: string, message: string}
|
||||
*/
|
||||
#[McpTool('confirm_action', 'Request user confirmation before proceeding with an action.')]
|
||||
public function confirmAction(RequestContext $context, string $actionDescription): array
|
||||
{
|
||||
if (!$context->getClientGateway()->supportsElicitation()) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => 'Client does not support elicitation. Please confirm the action explicitly in your request.',
|
||||
];
|
||||
}
|
||||
|
||||
$client = $context->getClientGateway();
|
||||
|
||||
$schema = new ElicitationSchema(
|
||||
properties: [
|
||||
'confirm' => new BooleanSchemaDefinition(
|
||||
title: 'Confirm',
|
||||
description: 'Check to confirm you want to proceed',
|
||||
default: false,
|
||||
),
|
||||
],
|
||||
required: ['confirm'],
|
||||
);
|
||||
|
||||
$result = $client->elicit(
|
||||
message: \sprintf('Are you sure you want to: %s?', $actionDescription),
|
||||
requestedSchema: $schema,
|
||||
);
|
||||
|
||||
if (!$result->isAccepted()) {
|
||||
return [
|
||||
'status' => 'not_confirmed',
|
||||
'message' => 'Action was not confirmed by user.',
|
||||
];
|
||||
}
|
||||
|
||||
$content = $result->content;
|
||||
if (null === $content) {
|
||||
throw new \RuntimeException('Expected content for accepted elicitation.');
|
||||
}
|
||||
|
||||
if (!isset($content['confirm'])) {
|
||||
throw new \RuntimeException('Missing required field: confirm.');
|
||||
}
|
||||
|
||||
$confirmed = (bool) $content['confirm'];
|
||||
|
||||
if (!$confirmed) {
|
||||
return [
|
||||
'status' => 'not_confirmed',
|
||||
'message' => 'User did not check the confirmation box.',
|
||||
];
|
||||
}
|
||||
|
||||
$this->logger->info(\sprintf('User confirmed action: %s', $actionDescription));
|
||||
|
||||
return [
|
||||
'status' => 'confirmed',
|
||||
'message' => \sprintf('Action confirmed: %s', $actionDescription),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect user feedback using elicitation.
|
||||
*
|
||||
* Demonstrates elicitation with optional fields and enum with labels.
|
||||
*
|
||||
* @return array{status: string, message: string, feedback?: array{rating: string, comments: string}}
|
||||
*/
|
||||
#[McpTool('collect_feedback', 'Collect user feedback via elicitation form.')]
|
||||
public function collectFeedback(RequestContext $context, string $topic): array
|
||||
{
|
||||
if (!$context->getClientGateway()->supportsElicitation()) {
|
||||
return [
|
||||
'status' => 'error',
|
||||
'message' => 'Client does not support elicitation. Please provide feedback (rating 1-5, comments) as tool parameters instead.',
|
||||
];
|
||||
}
|
||||
|
||||
$client = $context->getClientGateway();
|
||||
|
||||
$schema = new ElicitationSchema(
|
||||
properties: [
|
||||
'rating' => new EnumSchemaDefinition(
|
||||
title: 'Rating',
|
||||
enum: ['1', '2', '3', '4', '5'],
|
||||
description: 'Rate your experience from 1 (poor) to 5 (excellent)',
|
||||
enumNames: ['1 - Poor', '2 - Fair', '3 - Good', '4 - Very Good', '5 - Excellent'],
|
||||
),
|
||||
'comments' => new StringSchemaDefinition(
|
||||
title: 'Comments',
|
||||
description: 'Any additional comments or suggestions (optional)',
|
||||
maxLength: 500,
|
||||
),
|
||||
],
|
||||
required: ['rating'],
|
||||
);
|
||||
|
||||
$result = $client->elicit(
|
||||
message: \sprintf('Please provide your feedback about: %s', $topic),
|
||||
requestedSchema: $schema,
|
||||
);
|
||||
|
||||
if (!$result->isAccepted()) {
|
||||
return [
|
||||
'status' => 'skipped',
|
||||
'message' => 'User chose not to provide feedback.',
|
||||
];
|
||||
}
|
||||
|
||||
$content = $result->content;
|
||||
if (null === $content) {
|
||||
throw new \RuntimeException('Expected content for accepted elicitation.');
|
||||
}
|
||||
|
||||
if (!isset($content['rating'])) {
|
||||
throw new \RuntimeException('Missing required field: rating.');
|
||||
}
|
||||
|
||||
$rating = (string) $content['rating'];
|
||||
$comments = (string) ($content['comments'] ?? '');
|
||||
|
||||
$this->logger->info(\sprintf('Feedback received: rating=%s, comments=%s', $rating, $comments));
|
||||
|
||||
return [
|
||||
'status' => 'received',
|
||||
'message' => 'Thank you for your feedback!',
|
||||
'feedback' => [
|
||||
'rating' => $rating,
|
||||
'comments' => $comments,
|
||||
],
|
||||
];
|
||||
}
|
||||
}
|
||||
40
examples/server/elicitation/server.php
Normal file
40
examples/server/elicitation/server.php
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/**
|
||||
* MCP Elicitation Example Server.
|
||||
*
|
||||
* Demonstrates server-to-client elicitation for interactive user input during tool execution.
|
||||
* See docs/examples.md for detailed documentation and usage examples.
|
||||
*/
|
||||
|
||||
require_once dirname(__DIR__).'/bootstrap.php';
|
||||
chdir(__DIR__);
|
||||
|
||||
use Mcp\Schema\ServerCapabilities;
|
||||
use Mcp\Server;
|
||||
use Mcp\Server\Session\FileSessionStore;
|
||||
|
||||
$server = Server::builder()
|
||||
->setServerInfo('Elicitation Demo', '1.0.0')
|
||||
->setLogger(logger())
|
||||
->setContainer(container())
|
||||
->setSession(new FileSessionStore(__DIR__.'/sessions'))
|
||||
->setCapabilities(new ServerCapabilities(logging: true, tools: true))
|
||||
->setDiscovery(__DIR__)
|
||||
->build();
|
||||
|
||||
$result = $server->run(transport());
|
||||
|
||||
shutdown($result);
|
||||
|
|
@ -26,6 +26,7 @@ class ClientCapabilities implements \JsonSerializable
|
|||
public readonly ?bool $roots = false,
|
||||
public readonly ?bool $rootsListChanged = null,
|
||||
public readonly ?bool $sampling = null,
|
||||
public readonly ?bool $elicitation = null,
|
||||
public readonly ?array $experimental = null,
|
||||
) {
|
||||
}
|
||||
|
|
@ -36,6 +37,7 @@ class ClientCapabilities implements \JsonSerializable
|
|||
* listChanged?: bool,
|
||||
* },
|
||||
* sampling?: bool,
|
||||
* elicitation?: bool,
|
||||
* experimental?: array<string, mixed>,
|
||||
* } $data
|
||||
*/
|
||||
|
|
@ -56,10 +58,16 @@ class ClientCapabilities implements \JsonSerializable
|
|||
$sampling = true;
|
||||
}
|
||||
|
||||
$elicitation = null;
|
||||
if (isset($data['elicitation'])) {
|
||||
$elicitation = true;
|
||||
}
|
||||
|
||||
return new self(
|
||||
$rootsEnabled,
|
||||
$rootsListChanged,
|
||||
$sampling,
|
||||
$elicitation,
|
||||
$data['experimental'] ?? null
|
||||
);
|
||||
}
|
||||
|
|
@ -68,6 +76,7 @@ class ClientCapabilities implements \JsonSerializable
|
|||
* @return array{
|
||||
* roots?: object,
|
||||
* sampling?: object,
|
||||
* elicitation?: object,
|
||||
* experimental?: object,
|
||||
* }
|
||||
*/
|
||||
|
|
@ -85,6 +94,10 @@ class ClientCapabilities implements \JsonSerializable
|
|||
$data['sampling'] = new \stdClass();
|
||||
}
|
||||
|
||||
if ($this->elicitation) {
|
||||
$data['elicitation'] = new \stdClass();
|
||||
}
|
||||
|
||||
if ($this->experimental) {
|
||||
$data['experimental'] = (object) $this->experimental;
|
||||
}
|
||||
|
|
|
|||
68
src/Schema/Elicitation/AbstractSchemaDefinition.php
Normal file
68
src/Schema/Elicitation/AbstractSchemaDefinition.php
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Elicitation;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Base class for schema definitions in elicitation requests.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
abstract class AbstractSchemaDefinition implements \JsonSerializable
|
||||
{
|
||||
public function __construct(
|
||||
public readonly string $title,
|
||||
public readonly ?string $description = null,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate that title exists and is a string in the data array.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*
|
||||
* @throws InvalidArgumentException
|
||||
*/
|
||||
protected static function validateTitle(array $data, string $schemaType): void
|
||||
{
|
||||
if (!isset($data['title']) || !\is_string($data['title'])) {
|
||||
throw new InvalidArgumentException(\sprintf('Missing or invalid "title" for %s schema definition.', $schemaType));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the base JSON structure with type, title, and optional description.
|
||||
*
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function buildBaseJson(string $type): array
|
||||
{
|
||||
$data = [
|
||||
'type' => $type,
|
||||
'title' => $this->title,
|
||||
];
|
||||
|
||||
if (null !== $this->description) {
|
||||
$data['description'] = $this->description;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
abstract public function jsonSerialize(): array;
|
||||
}
|
||||
72
src/Schema/Elicitation/BooleanSchemaDefinition.php
Normal file
72
src/Schema/Elicitation/BooleanSchemaDefinition.php
Normal file
|
|
@ -0,0 +1,72 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Elicitation;
|
||||
|
||||
/**
|
||||
* Schema definition for boolean fields in elicitation requests.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
final class BooleanSchemaDefinition extends AbstractSchemaDefinition
|
||||
{
|
||||
/**
|
||||
* @param string $title Human-readable title for the field
|
||||
* @param string|null $description Optional description/help text
|
||||
* @param bool|null $default Optional default value
|
||||
*/
|
||||
public function __construct(
|
||||
string $title,
|
||||
?string $description = null,
|
||||
public readonly ?bool $default = null,
|
||||
) {
|
||||
parent::__construct($title, $description);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* title: string,
|
||||
* description?: string,
|
||||
* default?: bool,
|
||||
* } $data
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::validateTitle($data, 'boolean');
|
||||
|
||||
return new self(
|
||||
title: $data['title'],
|
||||
description: $data['description'] ?? null,
|
||||
default: isset($data['default']) ? (bool) $data['default'] : null,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* type: string,
|
||||
* title: string,
|
||||
* description?: string,
|
||||
* default?: bool,
|
||||
* }
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$data = $this->buildBaseJson('boolean');
|
||||
|
||||
if (null !== $this->default) {
|
||||
$data['default'] = $this->default;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
103
src/Schema/Elicitation/ElicitationSchema.php
Normal file
103
src/Schema/Elicitation/ElicitationSchema.php
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Elicitation;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Schema wrapper for elicitation requestedSchema (JSON Schema object type).
|
||||
*
|
||||
* Represents an object schema with primitive property definitions and optional required fields.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
final class ElicitationSchema implements \JsonSerializable
|
||||
{
|
||||
/**
|
||||
* @param array<string, StringSchemaDefinition|NumberSchemaDefinition|BooleanSchemaDefinition|EnumSchemaDefinition> $properties Property definitions keyed by name
|
||||
* @param string[] $required Array of required property names
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly array $properties,
|
||||
public readonly array $required = [],
|
||||
) {
|
||||
if ([] === $properties) {
|
||||
throw new InvalidArgumentException('properties array must not be empty.');
|
||||
}
|
||||
|
||||
foreach ($required as $name) {
|
||||
if (!\array_key_exists($name, $properties)) {
|
||||
throw new InvalidArgumentException(\sprintf('Required property "%s" is not defined in properties.', $name));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ElicitationSchema from array data.
|
||||
*
|
||||
* @param array{
|
||||
* type?: string,
|
||||
* properties: array<string, array{type: string, title: string, ...}>,
|
||||
* required?: string[],
|
||||
* } $data
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
if (isset($data['type']) && 'object' !== $data['type']) {
|
||||
throw new InvalidArgumentException('ElicitationSchema type must be "object".');
|
||||
}
|
||||
|
||||
if (!isset($data['properties']) || !\is_array($data['properties'])) {
|
||||
throw new InvalidArgumentException('Missing or invalid "properties" for elicitation schema.');
|
||||
}
|
||||
|
||||
$properties = [];
|
||||
foreach ($data['properties'] as $name => $propertyData) {
|
||||
if (!\is_array($propertyData)) {
|
||||
throw new InvalidArgumentException(\sprintf('Property "%s" must be an array.', $name));
|
||||
}
|
||||
$properties[$name] = PrimitiveSchemaDefinition::fromArray($propertyData);
|
||||
}
|
||||
|
||||
return new self(
|
||||
properties: $properties,
|
||||
required: $data['required'] ?? [],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* type: string,
|
||||
* properties: array<string, mixed>,
|
||||
* required?: string[],
|
||||
* }
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$data = [
|
||||
'type' => 'object',
|
||||
'properties' => [],
|
||||
];
|
||||
|
||||
foreach ($this->properties as $name => $property) {
|
||||
$data['properties'][$name] = $property->jsonSerialize();
|
||||
}
|
||||
|
||||
if ([] !== $this->required) {
|
||||
$data['required'] = $this->required;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
120
src/Schema/Elicitation/EnumSchemaDefinition.php
Normal file
120
src/Schema/Elicitation/EnumSchemaDefinition.php
Normal file
|
|
@ -0,0 +1,120 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Elicitation;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Schema definition for string enum fields in elicitation requests.
|
||||
*
|
||||
* Provides a list of allowed values with optional human-readable labels.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
final class EnumSchemaDefinition extends AbstractSchemaDefinition
|
||||
{
|
||||
/**
|
||||
* @param string $title Human-readable title for the field
|
||||
* @param string[] $enum Array of allowed string values
|
||||
* @param string|null $description Optional description/help text
|
||||
* @param string|null $default Optional default value (must be in enum)
|
||||
* @param string[]|null $enumNames Optional human-readable labels for each enum value
|
||||
*/
|
||||
public function __construct(
|
||||
string $title,
|
||||
public readonly array $enum,
|
||||
?string $description = null,
|
||||
public readonly ?string $default = null,
|
||||
public readonly ?array $enumNames = null,
|
||||
) {
|
||||
parent::__construct($title, $description);
|
||||
|
||||
if ([] === $enum) {
|
||||
throw new InvalidArgumentException('enum array must not be empty.');
|
||||
}
|
||||
|
||||
foreach ($enum as $value) {
|
||||
if (!\is_string($value)) {
|
||||
throw new InvalidArgumentException('All enum values must be strings.');
|
||||
}
|
||||
}
|
||||
|
||||
if (null !== $enumNames && \count($enumNames) !== \count($enum)) {
|
||||
throw new InvalidArgumentException('enumNames length must match enum length.');
|
||||
}
|
||||
|
||||
if (null !== $default && !\in_array($default, $enum, true)) {
|
||||
throw new InvalidArgumentException(\sprintf('Default value "%s" is not in the enum array.', $default));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* title: string,
|
||||
* enum: string[],
|
||||
* description?: string,
|
||||
* default?: string,
|
||||
* enumNames?: string[],
|
||||
* } $data
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::validateTitle($data, 'enum');
|
||||
|
||||
if (!isset($data['enum']) || !\is_array($data['enum'])) {
|
||||
throw new InvalidArgumentException('Missing or invalid "enum" for enum schema definition.');
|
||||
}
|
||||
|
||||
return new self(
|
||||
title: $data['title'],
|
||||
enum: $data['enum'],
|
||||
description: $data['description'] ?? null,
|
||||
default: $data['default'] ?? null,
|
||||
enumNames: $data['enumNames'] ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* type: string,
|
||||
* title: string,
|
||||
* enum: string[],
|
||||
* description?: string,
|
||||
* default?: string,
|
||||
* enumNames?: string[],
|
||||
* }
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$data = [
|
||||
'type' => 'string',
|
||||
'title' => $this->title,
|
||||
'enum' => $this->enum,
|
||||
];
|
||||
|
||||
if (null !== $this->description) {
|
||||
$data['description'] = $this->description;
|
||||
}
|
||||
|
||||
if (null !== $this->default) {
|
||||
$data['default'] = $this->default;
|
||||
}
|
||||
|
||||
if (null !== $this->enumNames) {
|
||||
$data['enumNames'] = $this->enumNames;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
117
src/Schema/Elicitation/NumberSchemaDefinition.php
Normal file
117
src/Schema/Elicitation/NumberSchemaDefinition.php
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Elicitation;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Schema definition for number/integer fields in elicitation requests.
|
||||
*
|
||||
* Supports minimum and maximum value constraints.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
final class NumberSchemaDefinition extends AbstractSchemaDefinition
|
||||
{
|
||||
/**
|
||||
* @param string $title Human-readable title for the field
|
||||
* @param bool $integerOnly Whether to restrict to integer values only
|
||||
* @param string|null $description Optional description/help text
|
||||
* @param int|float|null $default Optional default value
|
||||
* @param int|float|null $minimum Optional minimum value (inclusive)
|
||||
* @param int|float|null $maximum Optional maximum value (inclusive)
|
||||
*/
|
||||
public function __construct(
|
||||
string $title,
|
||||
public readonly bool $integerOnly = false,
|
||||
?string $description = null,
|
||||
public readonly int|float|null $default = null,
|
||||
public readonly int|float|null $minimum = null,
|
||||
public readonly int|float|null $maximum = null,
|
||||
) {
|
||||
parent::__construct($title, $description);
|
||||
|
||||
if (null !== $minimum && null !== $maximum && $minimum > $maximum) {
|
||||
throw new InvalidArgumentException('minimum cannot be greater than maximum.');
|
||||
}
|
||||
|
||||
if (null !== $default && null !== $minimum && $default < $minimum) {
|
||||
throw new InvalidArgumentException('default value cannot be less than minimum.');
|
||||
}
|
||||
|
||||
if (null !== $default && null !== $maximum && $default > $maximum) {
|
||||
throw new InvalidArgumentException('default value cannot be greater than maximum.');
|
||||
}
|
||||
|
||||
if ($integerOnly && null !== $default && $default !== (int) $default) {
|
||||
throw new InvalidArgumentException('default value must be an integer when integerOnly is true.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* type: string,
|
||||
* title: string,
|
||||
* description?: string,
|
||||
* default?: int|float,
|
||||
* minimum?: int|float,
|
||||
* maximum?: int|float,
|
||||
* } $data
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::validateTitle($data, 'number');
|
||||
|
||||
$type = $data['type'] ?? 'number';
|
||||
$integerOnly = 'integer' === $type;
|
||||
|
||||
return new self(
|
||||
title: $data['title'],
|
||||
integerOnly: $integerOnly,
|
||||
description: $data['description'] ?? null,
|
||||
default: $data['default'] ?? null,
|
||||
minimum: $data['minimum'] ?? null,
|
||||
maximum: $data['maximum'] ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* type: string,
|
||||
* title: string,
|
||||
* description?: string,
|
||||
* default?: int|float,
|
||||
* minimum?: int|float,
|
||||
* maximum?: int|float,
|
||||
* }
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$data = $this->buildBaseJson($this->integerOnly ? 'integer' : 'number');
|
||||
|
||||
if (null !== $this->default) {
|
||||
$data['default'] = $this->default;
|
||||
}
|
||||
|
||||
if (null !== $this->minimum) {
|
||||
$data['minimum'] = $this->minimum;
|
||||
}
|
||||
|
||||
if (null !== $this->maximum) {
|
||||
$data['maximum'] = $this->maximum;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
57
src/Schema/Elicitation/PrimitiveSchemaDefinition.php
Normal file
57
src/Schema/Elicitation/PrimitiveSchemaDefinition.php
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Elicitation;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Factory class for creating primitive schema definitions from array data.
|
||||
*
|
||||
* Dispatches to the correct schema definition class based on the "type" field.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
final class PrimitiveSchemaDefinition
|
||||
{
|
||||
/**
|
||||
* Create a schema definition from array data.
|
||||
*
|
||||
* @param array{
|
||||
* type: string,
|
||||
* title: string,
|
||||
* description?: string,
|
||||
* default?: mixed,
|
||||
* enum?: string[],
|
||||
* enumNames?: string[],
|
||||
* format?: string,
|
||||
* minLength?: int,
|
||||
* maxLength?: int,
|
||||
* minimum?: int|float,
|
||||
* maximum?: int|float,
|
||||
* } $data
|
||||
*/
|
||||
public static function fromArray(array $data): StringSchemaDefinition|NumberSchemaDefinition|BooleanSchemaDefinition|EnumSchemaDefinition
|
||||
{
|
||||
if (!isset($data['type']) || !\is_string($data['type'])) {
|
||||
throw new InvalidArgumentException('Missing or invalid "type" for primitive schema definition.');
|
||||
}
|
||||
|
||||
return match ($data['type']) {
|
||||
'string' => isset($data['enum']) ? EnumSchemaDefinition::fromArray($data) : StringSchemaDefinition::fromArray($data),
|
||||
'integer', 'number' => NumberSchemaDefinition::fromArray($data),
|
||||
'boolean' => BooleanSchemaDefinition::fromArray($data),
|
||||
default => throw new InvalidArgumentException(\sprintf('Unsupported primitive type "%s". Supported types are: string, integer, number, boolean.', $data['type'])),
|
||||
};
|
||||
}
|
||||
}
|
||||
121
src/Schema/Elicitation/StringSchemaDefinition.php
Normal file
121
src/Schema/Elicitation/StringSchemaDefinition.php
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Elicitation;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Schema definition for string fields in elicitation requests.
|
||||
*
|
||||
* Supports optional format validation (date, date-time, email, uri) and length constraints.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
final class StringSchemaDefinition extends AbstractSchemaDefinition
|
||||
{
|
||||
private const VALID_FORMATS = ['date', 'date-time', 'email', 'uri'];
|
||||
|
||||
/**
|
||||
* @param string $title Human-readable title for the field
|
||||
* @param string|null $description Optional description/help text
|
||||
* @param string|null $default Optional default value
|
||||
* @param string|null $format Optional format constraint (date, date-time, email, uri)
|
||||
* @param int|null $minLength Optional minimum string length
|
||||
* @param int|null $maxLength Optional maximum string length
|
||||
*/
|
||||
public function __construct(
|
||||
string $title,
|
||||
?string $description = null,
|
||||
public readonly ?string $default = null,
|
||||
public readonly ?string $format = null,
|
||||
public readonly ?int $minLength = null,
|
||||
public readonly ?int $maxLength = null,
|
||||
) {
|
||||
parent::__construct($title, $description);
|
||||
|
||||
if (null !== $format && !\in_array($format, self::VALID_FORMATS, true)) {
|
||||
throw new InvalidArgumentException(\sprintf('Invalid format "%s". Valid formats are: %s.', $format, implode(', ', self::VALID_FORMATS)));
|
||||
}
|
||||
|
||||
if (null !== $minLength && $minLength < 0) {
|
||||
throw new InvalidArgumentException('minLength must be non-negative.');
|
||||
}
|
||||
|
||||
if (null !== $maxLength && $maxLength < 0) {
|
||||
throw new InvalidArgumentException('maxLength must be non-negative.');
|
||||
}
|
||||
|
||||
if (null !== $minLength && null !== $maxLength && $minLength > $maxLength) {
|
||||
throw new InvalidArgumentException('minLength cannot be greater than maxLength.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{
|
||||
* title: string,
|
||||
* description?: string,
|
||||
* default?: string,
|
||||
* format?: string,
|
||||
* minLength?: int,
|
||||
* maxLength?: int,
|
||||
* } $data
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
self::validateTitle($data, 'string');
|
||||
|
||||
return new self(
|
||||
title: $data['title'],
|
||||
description: $data['description'] ?? null,
|
||||
default: $data['default'] ?? null,
|
||||
format: $data['format'] ?? null,
|
||||
minLength: isset($data['minLength']) ? (int) $data['minLength'] : null,
|
||||
maxLength: isset($data['maxLength']) ? (int) $data['maxLength'] : null,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* type: string,
|
||||
* title: string,
|
||||
* description?: string,
|
||||
* default?: string,
|
||||
* format?: string,
|
||||
* minLength?: int,
|
||||
* maxLength?: int,
|
||||
* }
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$data = $this->buildBaseJson('string');
|
||||
|
||||
if (null !== $this->default) {
|
||||
$data['default'] = $this->default;
|
||||
}
|
||||
|
||||
if (null !== $this->format) {
|
||||
$data['format'] = $this->format;
|
||||
}
|
||||
|
||||
if (null !== $this->minLength) {
|
||||
$data['minLength'] = $this->minLength;
|
||||
}
|
||||
|
||||
if (null !== $this->maxLength) {
|
||||
$data['maxLength'] = $this->maxLength;
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
26
src/Schema/Enum/ElicitAction.php
Normal file
26
src/Schema/Enum/ElicitAction.php
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Enum;
|
||||
|
||||
/**
|
||||
* Action taken by the user in response to an elicitation request.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
enum ElicitAction: string
|
||||
{
|
||||
case Accept = 'accept';
|
||||
case Decline = 'decline';
|
||||
case Cancel = 'cancel';
|
||||
}
|
||||
74
src/Schema/Request/ElicitRequest.php
Normal file
74
src/Schema/Request/ElicitRequest.php
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Request;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Elicitation\ElicitationSchema;
|
||||
use Mcp\Schema\JsonRpc\Request;
|
||||
|
||||
/**
|
||||
* A request from the server to elicit additional information from the user.
|
||||
*
|
||||
* The client will present the message and requested schema to the user, allowing them
|
||||
* to provide the requested information, decline, or cancel the operation.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
final class ElicitRequest extends Request
|
||||
{
|
||||
/**
|
||||
* @param string $message A human-readable message describing what information is needed
|
||||
* @param ElicitationSchema $requestedSchema The schema defining the fields to elicit from the user
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly string $message,
|
||||
public readonly ElicitationSchema $requestedSchema,
|
||||
) {
|
||||
}
|
||||
|
||||
public static function getMethod(): string
|
||||
{
|
||||
return 'elicitation/create';
|
||||
}
|
||||
|
||||
protected static function fromParams(?array $params): static
|
||||
{
|
||||
if (!isset($params['message']) || !\is_string($params['message'])) {
|
||||
throw new InvalidArgumentException('Missing or invalid "message" parameter for elicitation/create.');
|
||||
}
|
||||
|
||||
if (!isset($params['requestedSchema']) || !\is_array($params['requestedSchema'])) {
|
||||
throw new InvalidArgumentException('Missing or invalid "requestedSchema" parameter for elicitation/create.');
|
||||
}
|
||||
|
||||
return new self(
|
||||
$params['message'],
|
||||
ElicitationSchema::fromArray($params['requestedSchema']),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{
|
||||
* message: string,
|
||||
* requestedSchema: ElicitationSchema,
|
||||
* }
|
||||
*/
|
||||
protected function getParams(): array
|
||||
{
|
||||
return [
|
||||
'message' => $this->message,
|
||||
'requestedSchema' => $this->requestedSchema,
|
||||
];
|
||||
}
|
||||
}
|
||||
89
src/Schema/Result/ElicitResult.php
Normal file
89
src/Schema/Result/ElicitResult.php
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Schema\Result;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Enum\ElicitAction;
|
||||
use Mcp\Schema\JsonRpc\ResultInterface;
|
||||
|
||||
/**
|
||||
* The client's response to an elicitation/create request from the server.
|
||||
*
|
||||
* Contains the user's action (accept, decline, or cancel) and the content
|
||||
* they provided when accepting.
|
||||
*
|
||||
* @author Johannes Wachter <johannes@sulu.io>
|
||||
*/
|
||||
final class ElicitResult implements ResultInterface
|
||||
{
|
||||
/**
|
||||
* @param ElicitAction $action The user's action in response to the elicitation
|
||||
* @param array<string, mixed>|null $content The content provided by the user (only present when action is "accept")
|
||||
*/
|
||||
public function __construct(
|
||||
public readonly ElicitAction $action,
|
||||
public readonly ?array $content = null,
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{action: string, content?: array<string, mixed>} $data
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
if (!isset($data['action']) || !\is_string($data['action'])) {
|
||||
throw new InvalidArgumentException('Missing or invalid "action" in ElicitResult data.');
|
||||
}
|
||||
|
||||
$action = ElicitAction::from($data['action']);
|
||||
$content = isset($data['content']) && \is_array($data['content']) ? $data['content'] : null;
|
||||
|
||||
if (ElicitAction::Accept === $action && null === $content) {
|
||||
throw new InvalidArgumentException('Content must be provided when action is "accept".');
|
||||
}
|
||||
|
||||
return new self($action, $content);
|
||||
}
|
||||
|
||||
public function isAccepted(): bool
|
||||
{
|
||||
return ElicitAction::Accept === $this->action;
|
||||
}
|
||||
|
||||
public function isDeclined(): bool
|
||||
{
|
||||
return ElicitAction::Decline === $this->action;
|
||||
}
|
||||
|
||||
public function isCancelled(): bool
|
||||
{
|
||||
return ElicitAction::Cancel === $this->action;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{action: string, content?: array<string, mixed>}
|
||||
*/
|
||||
public function jsonSerialize(): array
|
||||
{
|
||||
$result = [
|
||||
'action' => $this->action->value,
|
||||
];
|
||||
|
||||
if (null !== $this->content) {
|
||||
$result['content'] = $this->content;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
|
@ -19,6 +19,7 @@ use Mcp\Schema\Content\Content;
|
|||
use Mcp\Schema\Content\ImageContent;
|
||||
use Mcp\Schema\Content\SamplingMessage;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Elicitation\ElicitationSchema;
|
||||
use Mcp\Schema\Enum\LoggingLevel;
|
||||
use Mcp\Schema\Enum\Role;
|
||||
use Mcp\Schema\Enum\SamplingContext;
|
||||
|
|
@ -30,7 +31,9 @@ use Mcp\Schema\ModelPreferences;
|
|||
use Mcp\Schema\Notification\LoggingMessageNotification;
|
||||
use Mcp\Schema\Notification\ProgressNotification;
|
||||
use Mcp\Schema\Request\CreateSamplingMessageRequest;
|
||||
use Mcp\Schema\Request\ElicitRequest;
|
||||
use Mcp\Schema\Result\CreateSamplingMessageResult;
|
||||
use Mcp\Schema\Result\ElicitResult;
|
||||
use Mcp\Server\Session\SessionInterface;
|
||||
|
||||
/**
|
||||
|
|
@ -158,6 +161,50 @@ class ClientGateway
|
|||
return CreateSamplingMessageResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method for elicitation requests.
|
||||
*
|
||||
* Requests additional information from the user via the client. The user can
|
||||
* accept (providing the requested data), decline, or cancel the request.
|
||||
*
|
||||
* @param string $message A human-readable message describing what information is needed
|
||||
* @param ElicitationSchema $requestedSchema The schema defining the fields to elicit from the user
|
||||
* @param int $timeout The timeout in seconds
|
||||
*
|
||||
* @return ElicitResult The elicitation response containing the user's action and any provided content
|
||||
*
|
||||
* @throws ClientException if the client request results in an error message
|
||||
*/
|
||||
public function elicit(string $message, ElicitationSchema $requestedSchema, int $timeout = 120): ElicitResult
|
||||
{
|
||||
$request = new ElicitRequest($message, $requestedSchema);
|
||||
|
||||
$response = $this->request($request, $timeout);
|
||||
|
||||
if ($response instanceof Error) {
|
||||
throw new ClientException($response);
|
||||
}
|
||||
|
||||
return ElicitResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the connected client supports elicitation.
|
||||
*
|
||||
* Elicitation allows servers to request additional information from users
|
||||
* during tool execution. This method checks the client's advertised capabilities
|
||||
* to determine if elicitation/create requests are supported.
|
||||
*
|
||||
* @return bool True if the client supports elicitation, false otherwise
|
||||
*/
|
||||
public function supportsElicitation(): bool
|
||||
{
|
||||
$capabilities = $this->session->get('client_capabilities', []);
|
||||
|
||||
// MCP spec: capability presence indicates support (value is typically {} or [])
|
||||
return \array_key_exists('elicitation', $capabilities);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a request to the client and wait for a response (blocking).
|
||||
*
|
||||
|
|
|
|||
|
|
@ -45,6 +45,7 @@ final class InitializeHandler implements RequestHandlerInterface
|
|||
\assert($request instanceof InitializeRequest);
|
||||
|
||||
$session->set('client_info', $request->clientInfo->jsonSerialize());
|
||||
$session->set('client_capabilities', $request->capabilities->jsonSerialize());
|
||||
|
||||
return new Response(
|
||||
$request->getId(),
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ class Session implements SessionInterface
|
|||
* Official keys are:
|
||||
* - initialized: bool
|
||||
* - client_info: array|null
|
||||
* - client_capabilities: array|null
|
||||
* - protocol_version: string|null
|
||||
* - log_level: string|null
|
||||
*
|
||||
|
|
|
|||
110
tests/Unit/Schema/Elicitation/BooleanSchemaDefinitionTest.php
Normal file
110
tests/Unit/Schema/Elicitation/BooleanSchemaDefinitionTest.php
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Elicitation;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Elicitation\BooleanSchemaDefinition;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class BooleanSchemaDefinitionTest extends TestCase
|
||||
{
|
||||
public function testConstructorWithMinimalParams(): void
|
||||
{
|
||||
$schema = new BooleanSchemaDefinition('Confirm');
|
||||
|
||||
$this->assertSame('Confirm', $schema->title);
|
||||
$this->assertNull($schema->description);
|
||||
$this->assertNull($schema->default);
|
||||
}
|
||||
|
||||
public function testConstructorWithAllParams(): void
|
||||
{
|
||||
$schema = new BooleanSchemaDefinition(
|
||||
title: 'Confirmation',
|
||||
description: 'Do you confirm this action?',
|
||||
default: false,
|
||||
);
|
||||
|
||||
$this->assertSame('Confirmation', $schema->title);
|
||||
$this->assertSame('Do you confirm this action?', $schema->description);
|
||||
$this->assertFalse($schema->default);
|
||||
}
|
||||
|
||||
public function testConstructorWithTrueDefault(): void
|
||||
{
|
||||
$schema = new BooleanSchemaDefinition(
|
||||
title: 'Subscribe',
|
||||
default: true,
|
||||
);
|
||||
|
||||
$this->assertTrue($schema->default);
|
||||
}
|
||||
|
||||
public function testFromArrayWithMinimalParams(): void
|
||||
{
|
||||
$schema = BooleanSchemaDefinition::fromArray(['title' => 'Confirm']);
|
||||
|
||||
$this->assertSame('Confirm', $schema->title);
|
||||
$this->assertNull($schema->description);
|
||||
$this->assertNull($schema->default);
|
||||
}
|
||||
|
||||
public function testFromArrayWithAllParams(): void
|
||||
{
|
||||
$schema = BooleanSchemaDefinition::fromArray([
|
||||
'title' => 'Confirmation',
|
||||
'description' => 'Do you confirm this action?',
|
||||
'default' => true,
|
||||
]);
|
||||
|
||||
$this->assertSame('Confirmation', $schema->title);
|
||||
$this->assertSame('Do you confirm this action?', $schema->description);
|
||||
$this->assertTrue($schema->default);
|
||||
}
|
||||
|
||||
public function testFromArrayWithMissingTitle(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Missing or invalid "title"');
|
||||
|
||||
/* @phpstan-ignore argument.type */
|
||||
BooleanSchemaDefinition::fromArray([]);
|
||||
}
|
||||
|
||||
public function testJsonSerializeWithMinimalParams(): void
|
||||
{
|
||||
$schema = new BooleanSchemaDefinition('Confirm');
|
||||
|
||||
$this->assertSame([
|
||||
'type' => 'boolean',
|
||||
'title' => 'Confirm',
|
||||
], $schema->jsonSerialize());
|
||||
}
|
||||
|
||||
public function testJsonSerializeWithAllParams(): void
|
||||
{
|
||||
$schema = new BooleanSchemaDefinition(
|
||||
title: 'Confirmation',
|
||||
description: 'Do you confirm this action?',
|
||||
default: false,
|
||||
);
|
||||
|
||||
$this->assertSame([
|
||||
'type' => 'boolean',
|
||||
'title' => 'Confirmation',
|
||||
'description' => 'Do you confirm this action?',
|
||||
'default' => false,
|
||||
], $schema->jsonSerialize());
|
||||
}
|
||||
}
|
||||
221
tests/Unit/Schema/Elicitation/ElicitationSchemaTest.php
Normal file
221
tests/Unit/Schema/Elicitation/ElicitationSchemaTest.php
Normal file
|
|
@ -0,0 +1,221 @@
|
|||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/*
|
||||
* 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\Elicitation;
|
||||
|
||||
use Mcp\Exception\InvalidArgumentException;
|
||||
use Mcp\Schema\Elicitation\BooleanSchemaDefinition;
|
||||
use Mcp\Schema\Elicitation\ElicitationSchema;
|
||||
use Mcp\Schema\Elicitation\EnumSchemaDefinition;
|
||||
use Mcp\Schema\Elicitation\NumberSchemaDefinition;
|
||||
use Mcp\Schema\Elicitation\StringSchemaDefinition;
|
||||
use PHPUnit\Framework\TestCase;
|
||||
|
||||
final class ElicitationSchemaTest extends TestCase
|
||||
{
|
||||
public function testConstructorWithMinimalParams(): void
|
||||
{
|
||||
$properties = [
|
||||
'name' => new StringSchemaDefinition('Name'),
|
||||
];
|
||||
|
||||
$schema = new ElicitationSchema($properties);
|
||||
|
||||
$this->assertCount(1, $schema->properties);
|
||||
$this->assertSame([], $schema->required);
|
||||
}
|
||||
|
||||
public function testConstructorWithRequiredFields(): void
|
||||
{
|
||||
$properties = [
|
||||
'name' => new StringSchemaDefinition('Name'),
|
||||
'email' => new StringSchemaDefinition('Email'),
|
||||
];
|
||||
|
||||
$schema = new ElicitationSchema($properties, ['name']);
|
||||
|
||||
$this->assertCount(2, $schema->properties);
|
||||
$this->assertSame(['name'], $schema->required);
|
||||
}
|
||||
|
||||
public function testConstructorWithMultipleTypes(): void
|
||||
{
|
||||
$properties = [
|
||||
'name' => new StringSchemaDefinition('Name'),
|
||||
'age' => new NumberSchemaDefinition('Age', integerOnly: true),
|
||||
'subscribe' => new BooleanSchemaDefinition('Subscribe'),
|
||||
'rating' => new EnumSchemaDefinition('Rating', ['1', '2', '3', '4', '5']),
|
||||
];
|
||||
|
||||
$schema = new ElicitationSchema($properties, ['name', 'age']);
|
||||
|
||||
$this->assertCount(4, $schema->properties);
|
||||
$this->assertInstanceOf(StringSchemaDefinition::class, $schema->properties['name']);
|
||||
$this->assertInstanceOf(NumberSchemaDefinition::class, $schema->properties['age']);
|
||||
$this->assertInstanceOf(BooleanSchemaDefinition::class, $schema->properties['subscribe']);
|
||||
$this->assertInstanceOf(EnumSchemaDefinition::class, $schema->properties['rating']);
|
||||
}
|
||||
|
||||
public function testConstructorWithEmptyProperties(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('properties array must not be empty');
|
||||
|
||||
new ElicitationSchema([]);
|
||||
}
|
||||
|
||||
public function testConstructorWithInvalidRequired(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Required property "unknown" is not defined in properties');
|
||||
|
||||
new ElicitationSchema(
|
||||
['name' => new StringSchemaDefinition('Name')],
|
||||
['unknown'],
|
||||
);
|
||||
}
|
||||
|
||||
public function testFromArrayWithMinimalParams(): void
|
||||
{
|
||||
$schema = ElicitationSchema::fromArray([
|
||||
'properties' => [
|
||||
'name' => ['type' => 'string', 'title' => 'Name'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertCount(1, $schema->properties);
|
||||
$this->assertInstanceOf(StringSchemaDefinition::class, $schema->properties['name']);
|
||||
}
|
||||
|
||||
public function testFromArrayWithExplicitObjectType(): void
|
||||
{
|
||||
$schema = ElicitationSchema::fromArray([
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'name' => ['type' => 'string', 'title' => 'Name'],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertCount(1, $schema->properties);
|
||||
}
|
||||
|
||||
public function testFromArrayWithInvalidType(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('ElicitationSchema type must be "object"');
|
||||
|
||||
ElicitationSchema::fromArray([
|
||||
'type' => 'array',
|
||||
'properties' => [
|
||||
'name' => ['type' => 'string', 'title' => 'Name'],
|
||||
],
|
||||
]);
|
||||
}
|
||||
|
||||
public function testFromArrayWithMissingProperties(): void
|
||||
{
|
||||
$this->expectException(InvalidArgumentException::class);
|
||||
$this->expectExceptionMessage('Missing or invalid "properties"');
|
||||
|
||||
/* @phpstan-ignore argument.type */
|
||||
ElicitationSchema::fromArray([]);
|
||||
}
|
||||
|
||||
public function testFromArrayWithRequiredFields(): void
|
||||
{
|
||||
$schema = ElicitationSchema::fromArray([
|
||||
'properties' => [
|
||||
'name' => ['type' => 'string', 'title' => 'Name'],
|
||||
'email' => ['type' => 'string', 'title' => 'Email', 'format' => 'email'],
|
||||
],
|
||||
'required' => ['name'],
|
||||
]);
|
||||
|
||||
$this->assertSame(['name'], $schema->required);
|
||||
}
|
||||
|
||||
public function testFromArrayWithMultipleTypes(): void
|
||||
{
|
||||
$schema = ElicitationSchema::fromArray([
|
||||
'properties' => [
|
||||
'name' => ['type' => 'string', 'title' => 'Name'],
|
||||
'age' => ['type' => 'integer', 'title' => 'Age', 'minimum' => 0],
|
||||
'confirm' => ['type' => 'boolean', 'title' => 'Confirm'],
|
||||
'rating' => ['type' => 'string', 'title' => 'Rating', 'enum' => ['1', '2', '3']],
|
||||
],
|
||||
]);
|
||||
|
||||
$this->assertInstanceOf(StringSchemaDefinition::class, $schema->properties['name']);
|
||||
$this->assertInstanceOf(NumberSchemaDefinition::class, $schema->properties['age']);
|
||||
$this->assertInstanceOf(BooleanSchemaDefinition::class, $schema->properties['confirm']);
|
||||
$this->assertInstanceOf(EnumSchemaDefinition::class, $schema->properties['rating']);
|
||||
}
|
||||
|
||||
public function testJsonSerializeWithMinimalParams(): void
|
||||
{
|
||||
$schema = new ElicitationSchema([
|
||||
'name' => new StringSchemaDefinition('Name'),
|
||||
]);
|
||||
|
||||
$result = $schema->jsonSerialize();
|
||||
|
||||
$this->assertSame('object', $result['type']);
|
||||
$this->assertArrayHasKey('name', $result['properties']);
|
||||
$this->assertSame('string', $result['properties']['name']['type']);
|
||||
$this->assertArrayNotHasKey('required', $result);
|
||||
}
|
||||
|
||||
public function testJsonSerializeWithRequiredFields(): void
|
||||
{
|
||||
$schema = new ElicitationSchema(
|
||||
[
|
||||
'name' => new StringSchemaDefinition('Name'),
|
||||
'email' => new StringSchemaDefinition('Email'),
|
||||
],
|
||||
['name'],
|
||||
);
|
||||
|
||||
$result = $schema->jsonSerialize();
|
||||
|
||||
$this->assertSame(['name'], $result['required']);
|
||||
}
|
||||
|
||||
public function testJsonSerializeWithFullSchema(): void
|
||||
{
|
||||
$schema = new ElicitationSchema(
|
||||
[
|
||||
'name' => new StringSchemaDefinition('Full Name', description: 'Your full name'),
|
||||
'age' => new NumberSchemaDefinition('Age', integerOnly: true, minimum: 0, maximum: 150),
|
||||
'subscribe' => new BooleanSchemaDefinition('Subscribe', default: false),
|
||||
],
|
||||
['name', 'age'],
|
||||
);
|
||||
|
||||
$result = $schema->jsonSerialize();
|
||||
|
||||
$this->assertSame('object', $result['type']);
|
||||
$this->assertCount(3, $result['properties']);
|
||||
$this->assertSame(['name', 'age'], $result['required']);
|
||||
|
||||
$this->assertSame('string', $result['properties']['name']['type']);
|
||||
$this->assertSame('Full Name', $result['properties']['name']['title']);
|
||||
$this->assertSame('Your full name', $result['properties']['name']['description']);
|
||||
|
||||
$this->assertSame('integer', $result['properties']['age']['type']);
|
||||
$this->assertSame(0, $result['properties']['age']['minimum']);
|
||||
$this->assertSame(150, $result['properties']['age']['maximum']);
|
||||
|
||||
$this->assertSame('boolean', $result['properties']['subscribe']['type']);
|
||||
$this->assertFalse($result['properties']['subscribe']['default']);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue