[Client] Feat: Implement MCP client component (#192)
* feat(client): add complete MCP client SDK with STDIO and HTTP transports Add Client, Builder, ClientProtocol, ClientSession, and transport implementations for communicating with MCP servers. Supports tools, resources, prompts, and real-time progress/logging notifications. * refactor(examples): reorganize examples into server/ and client/ folders * feat: add SamplingRequestHandler for handling server sampling requests * feat: add setLoggingLevel method to control server logging verbosity * refactor: make progress token dependent on request ID * docs: Update server IP in usage instructions and add notes on sampling server requirements. * feat: add complete() method for completion/complete requests * refactor: properly parse and type initialize result * refactor: standardize method names * fix: revert changes to server related components * fix: revert changes to server related components * refactor: Restructure client transports and handlers into dedicated namespaces. * fix: cs and php-stan errors fixes(partial) * feat: Refactor request handlers to return `Response` or `Error` objects directly, adding a `SamplingException` and error logging for sampling requests. * feat: Replace `ClientTransportInterface` with `TransportInterface` and move response result deserialization to client methods. * refactor: remove redundant timeout check for intialize on transports The processFiber that executes per tick while fiber is suspended already handles timeouts while waiting * feat: broaden symfony/http-client dependency to support Symfony 5.4 to 8.0 * Update examples/client/README.md Co-authored-by: Christopher Hertel <mail@christopher-hertel.de> * Update examples/client/README.md Co-authored-by: Christopher Hertel <mail@christopher-hertel.de> * refactor: remove outgoing message queue from session and simplify transport send method to directly dispatch messages. * refactor: Replace ClientSession with ClientState for clearer intent on runtime state management * refactor: rename connectAndInitialize to connect for consistency * chore: cs fix * chore: use SamplingCallbackInterface instead of a closure for sampling request handler --------- Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
This commit is contained in:
parent
a5a738396d
commit
3ef864c444
31 changed files with 2731 additions and 9 deletions
|
|
@ -85,4 +85,4 @@
|
|||
},
|
||||
"sort-packages": true
|
||||
}
|
||||
}
|
||||
}
|
||||
27
examples/client/README.md
Normal file
27
examples/client/README.md
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
# Client Examples
|
||||
|
||||
These examples demonstrate how to use the MCP PHP Client SDK.
|
||||
|
||||
## STDIO Client
|
||||
|
||||
Connects to an MCP server running as a child process:
|
||||
|
||||
```bash
|
||||
php examples/client/stdio_discovery_calculator.php
|
||||
```
|
||||
|
||||
## HTTP Client
|
||||
|
||||
Connects to an MCP server over HTTP:
|
||||
|
||||
```bash
|
||||
# First, start an HTTP server
|
||||
php -S localhost:8000 examples/server/discovery-calculator/server.php
|
||||
|
||||
# Then run the client
|
||||
php examples/client/http_discovery_calculator.php
|
||||
```
|
||||
|
||||
## Requirements
|
||||
|
||||
All examples require the server examples to be available. The STDIO examples spawn the server process, while the HTTP examples connect to a running HTTP server.
|
||||
134
examples/client/http_client_communication.php
Normal file
134
examples/client/http_client_communication.php
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* HTTP Client Communication Example.
|
||||
*
|
||||
* This example demonstrates server-to-client communication over HTTP:
|
||||
* - Logging notifications
|
||||
* - Progress notifications (via SSE streaming)
|
||||
* - Sampling requests (mocked LLM response)
|
||||
*
|
||||
* Usage:
|
||||
* 1. Start the server: php -S 127.0.0.1:8000 examples/server/client-communication/server.php
|
||||
* 2. Run this script: php examples/client/http_client_communication.php
|
||||
*
|
||||
* Note: PHP's built-in server works for listing tools, calling tools, and receiving
|
||||
* progress/logging notifications. However, sampling requires a concurrent-capable server
|
||||
* (e.g., Symfony CLI, PHP-FPM) since the server must process the client's sampling
|
||||
* response while the original tool request is still pending.
|
||||
*
|
||||
* Eg. symfony serve --passthru=examples/server/client-communication/server.php --no-tls
|
||||
*/
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
require_once __DIR__.'/../../vendor/autoload.php';
|
||||
|
||||
use Mcp\Client;
|
||||
use Mcp\Client\Handler\Notification\LoggingNotificationHandler;
|
||||
use Mcp\Client\Handler\Request\SamplingCallbackInterface;
|
||||
use Mcp\Client\Handler\Request\SamplingRequestHandler;
|
||||
use Mcp\Client\Transport\HttpTransport;
|
||||
use Mcp\Schema\ClientCapabilities;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Enum\Role;
|
||||
use Mcp\Schema\Notification\LoggingMessageNotification;
|
||||
use Mcp\Schema\Request\CreateSamplingMessageRequest;
|
||||
use Mcp\Schema\Result\CreateSamplingMessageResult;
|
||||
|
||||
$endpoint = 'http://127.0.0.1:8000';
|
||||
|
||||
$loggingNotificationHandler = new LoggingNotificationHandler(static function (LoggingMessageNotification $n) {
|
||||
echo "[LOG {$n->level->value}] {$n->data}\n";
|
||||
});
|
||||
|
||||
$samplingRequestHandler = new SamplingRequestHandler(new class implements SamplingCallbackInterface {
|
||||
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
|
||||
{
|
||||
echo "[SAMPLING] Server requested LLM sampling (max {$request->maxTokens} tokens)\n";
|
||||
|
||||
$mockResponse = 'Based on the incident analysis, I recommend: 1) Activate the on-call team, '.
|
||||
'2) Isolate affected systems, 3) Begin root cause analysis, 4) Prepare stakeholder communication.';
|
||||
|
||||
return new CreateSamplingMessageResult(
|
||||
role: Role::Assistant,
|
||||
content: new TextContent($mockResponse),
|
||||
model: 'mock-gpt-4',
|
||||
stopReason: 'end_turn',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
$client = Client::builder()
|
||||
->setClientInfo('HTTP Client Communication Test', '1.0.0')
|
||||
->setInitTimeout(30)
|
||||
->setRequestTimeout(120)
|
||||
->setCapabilities(new ClientCapabilities(sampling: true))
|
||||
->addNotificationHandler($loggingNotificationHandler)
|
||||
->addRequestHandler($samplingRequestHandler)
|
||||
->build();
|
||||
|
||||
$transport = new HttpTransport(endpoint: $endpoint);
|
||||
|
||||
try {
|
||||
echo "Connecting to MCP server at {$endpoint}...\n";
|
||||
$client->connect($transport);
|
||||
|
||||
$serverInfo = $client->getServerInfo();
|
||||
echo 'Connected to: '.($serverInfo->name ?? 'unknown')."\n\n";
|
||||
|
||||
echo "Available tools:\n";
|
||||
$toolsResult = $client->listTools();
|
||||
foreach ($toolsResult->tools as $tool) {
|
||||
echo " - {$tool->name}\n";
|
||||
}
|
||||
echo "\n";
|
||||
|
||||
echo "Calling 'run_dataset_quality_checks'...\n\n";
|
||||
$result = $client->callTool(
|
||||
name: 'run_dataset_quality_checks',
|
||||
arguments: ['dataset' => 'sales_transactions_q4'],
|
||||
onProgress: static function (float $progress, ?float $total, ?string $message) {
|
||||
$percent = $total > 0 ? round(($progress / $total) * 100) : '?';
|
||||
echo "[PROGRESS {$percent}%] {$message}\n";
|
||||
}
|
||||
);
|
||||
|
||||
echo "\nResult:\n";
|
||||
foreach ($result->content as $content) {
|
||||
if ($content instanceof TextContent) {
|
||||
echo $content->text."\n";
|
||||
}
|
||||
}
|
||||
|
||||
echo "\nCalling 'coordinate_incident_response'...\n\n";
|
||||
$result = $client->callTool(
|
||||
name: 'coordinate_incident_response',
|
||||
arguments: ['incidentTitle' => 'Database connection pool exhausted'],
|
||||
onProgress: static function (float $progress, ?float $total, ?string $message) {
|
||||
$percent = $total > 0 ? round(($progress / $total) * 100) : '?';
|
||||
echo "[PROGRESS {$percent}%] {$message}\n";
|
||||
}
|
||||
);
|
||||
|
||||
echo "\nResult:\n";
|
||||
foreach ($result->content as $content) {
|
||||
if ($content instanceof TextContent) {
|
||||
echo $content->text."\n";
|
||||
}
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
echo "Error: {$e->getMessage()}\n";
|
||||
echo $e->getTraceAsString()."\n";
|
||||
} finally {
|
||||
$client->disconnect();
|
||||
}
|
||||
77
examples/client/http_discovery_calculator.php
Normal file
77
examples/client/http_discovery_calculator.php
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* HTTP Client Example.
|
||||
*
|
||||
* This example demonstrates how to use the MCP client with an HTTP transport
|
||||
* to communicate with a remote MCP server over HTTP.
|
||||
*
|
||||
* Usage: php examples/client/http_discovery_calculator.php
|
||||
*
|
||||
* Before running, start an HTTP MCP server:
|
||||
* php -S localhost:8080 examples/server/http-discovery-calculator/server.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.
|
||||
*/
|
||||
|
||||
require_once __DIR__.'/../../vendor/autoload.php';
|
||||
|
||||
use Mcp\Client;
|
||||
use Mcp\Client\Transport\HttpTransport;
|
||||
|
||||
$endpoint = 'http://localhost:8000';
|
||||
|
||||
$client = Client::builder()
|
||||
->setClientInfo('HTTP Example Client', '1.0.0')
|
||||
->setInitTimeout(30)
|
||||
->setRequestTimeout(60)
|
||||
->build();
|
||||
|
||||
$transport = new HttpTransport($endpoint);
|
||||
|
||||
try {
|
||||
echo "Connecting to MCP server at {$endpoint}...\n";
|
||||
$client->connect($transport);
|
||||
|
||||
echo "Connected! Server info:\n";
|
||||
$serverInfo = $client->getServerInfo();
|
||||
echo ' Name: '.($serverInfo->name ?? 'unknown')."\n";
|
||||
echo ' Version: '.($serverInfo->version ?? 'unknown')."\n\n";
|
||||
|
||||
echo "Available tools:\n";
|
||||
$toolsResult = $client->listTools();
|
||||
foreach ($toolsResult->tools as $tool) {
|
||||
echo " - {$tool->name}: {$tool->description}\n";
|
||||
}
|
||||
echo "\n";
|
||||
|
||||
echo "Available resources:\n";
|
||||
$resourcesResult = $client->listResources();
|
||||
foreach ($resourcesResult->resources as $resource) {
|
||||
echo " - {$resource->uri}: {$resource->name}\n";
|
||||
}
|
||||
echo "\n";
|
||||
|
||||
echo "Available prompts:\n";
|
||||
$promptsResult = $client->listPrompts();
|
||||
foreach ($promptsResult->prompts as $prompt) {
|
||||
echo " - {$prompt->name}: {$prompt->description}\n";
|
||||
}
|
||||
echo "\n";
|
||||
} catch (Throwable $e) {
|
||||
echo "Error: {$e->getMessage()}\n";
|
||||
echo $e->getTraceAsString()."\n";
|
||||
} finally {
|
||||
echo "Disconnecting...\n";
|
||||
$client->disconnect();
|
||||
echo "Done.\n";
|
||||
}
|
||||
126
examples/client/stdio_client_communication.php
Normal file
126
examples/client/stdio_client_communication.php
Normal file
|
|
@ -0,0 +1,126 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* STDIO Client Communication Example.
|
||||
*
|
||||
* This example demonstrates server-to-client communication:
|
||||
* - Logging notifications
|
||||
* - Progress notifications
|
||||
* - Sampling requests (mocked LLM response)
|
||||
*
|
||||
* Usage: php examples/client/stdio_client_communication.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.
|
||||
*/
|
||||
|
||||
require_once __DIR__.'/../../vendor/autoload.php';
|
||||
|
||||
use Mcp\Client;
|
||||
use Mcp\Client\Handler\Notification\LoggingNotificationHandler;
|
||||
use Mcp\Client\Handler\Request\SamplingCallbackInterface;
|
||||
use Mcp\Client\Handler\Request\SamplingRequestHandler;
|
||||
use Mcp\Client\Transport\StdioTransport;
|
||||
use Mcp\Schema\ClientCapabilities;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Enum\Role;
|
||||
use Mcp\Schema\Notification\LoggingMessageNotification;
|
||||
use Mcp\Schema\Request\CreateSamplingMessageRequest;
|
||||
use Mcp\Schema\Result\CreateSamplingMessageResult;
|
||||
|
||||
$loggingNotificationHandler = new LoggingNotificationHandler(static function (LoggingMessageNotification $n) {
|
||||
echo "[LOG {$n->level->value}] {$n->data}\n";
|
||||
});
|
||||
|
||||
$samplingRequestHandler = new SamplingRequestHandler(new class implements SamplingCallbackInterface {
|
||||
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
|
||||
{
|
||||
echo "[SAMPLING] Server requested LLM sampling (max {$request->maxTokens} tokens)\n";
|
||||
|
||||
$mockResponse = 'Based on the incident analysis, I recommend: 1) Activate the on-call team, '.
|
||||
'2) Isolate affected systems, 3) Begin root cause analysis, 4) Prepare stakeholder communication.';
|
||||
|
||||
return new CreateSamplingMessageResult(
|
||||
role: Role::Assistant,
|
||||
content: new TextContent($mockResponse),
|
||||
model: 'mock-gpt-4',
|
||||
stopReason: 'end_turn',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
$client = Client::builder()
|
||||
->setClientInfo('STDIO Client Communication Test', '1.0.0')
|
||||
->setInitTimeout(30)
|
||||
->setRequestTimeout(120)
|
||||
->setCapabilities(new ClientCapabilities(sampling: true))
|
||||
->addNotificationHandler($loggingNotificationHandler)
|
||||
->addRequestHandler($samplingRequestHandler)
|
||||
->build();
|
||||
|
||||
$transport = new StdioTransport(
|
||||
command: 'php',
|
||||
args: [__DIR__.'/../server/client-communication/server.php'],
|
||||
);
|
||||
|
||||
try {
|
||||
echo "Connecting to MCP server...\n";
|
||||
$client->connect($transport);
|
||||
|
||||
$serverInfo = $client->getServerInfo();
|
||||
echo 'Connected to: '.($serverInfo->name ?? 'unknown')."\n\n";
|
||||
|
||||
echo "Available tools:\n";
|
||||
$toolsResult = $client->listTools();
|
||||
foreach ($toolsResult->tools as $tool) {
|
||||
echo " - {$tool->name}\n";
|
||||
}
|
||||
echo "\n";
|
||||
|
||||
echo "Calling 'run_dataset_quality_checks'...\n\n";
|
||||
$result = $client->callTool(
|
||||
name: 'run_dataset_quality_checks',
|
||||
arguments: ['dataset' => 'customer_orders_2024'],
|
||||
onProgress: static function (float $progress, ?float $total, ?string $message) {
|
||||
$percent = $total > 0 ? round(($progress / $total) * 100) : '?';
|
||||
echo "[PROGRESS {$percent}%] {$message}\n";
|
||||
}
|
||||
);
|
||||
|
||||
echo "\nResult:\n";
|
||||
foreach ($result->content as $content) {
|
||||
if ($content instanceof TextContent) {
|
||||
echo $content->text."\n";
|
||||
}
|
||||
}
|
||||
|
||||
echo "\nCalling 'coordinate_incident_response'...\n\n";
|
||||
$result = $client->callTool(
|
||||
name: 'coordinate_incident_response',
|
||||
arguments: ['incidentTitle' => 'Database connection pool exhausted'],
|
||||
onProgress: static function (float $progress, ?float $total, ?string $message) {
|
||||
$percent = $total > 0 ? round(($progress / $total) * 100) : '?';
|
||||
echo "[PROGRESS {$percent}%] {$message}\n";
|
||||
}
|
||||
);
|
||||
|
||||
echo "\nResult:\n";
|
||||
foreach ($result->content as $content) {
|
||||
if ($content instanceof TextContent) {
|
||||
echo $content->text."\n";
|
||||
}
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
echo "Error: {$e->getMessage()}\n";
|
||||
echo $e->getTraceAsString()."\n";
|
||||
} finally {
|
||||
$client->disconnect();
|
||||
}
|
||||
89
examples/client/stdio_discovery_calculator.php
Normal file
89
examples/client/stdio_discovery_calculator.php
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* Simple STDIO Client Example.
|
||||
*
|
||||
* This example demonstrates how to use the MCP client with a STDIO transport
|
||||
* to communicate with an MCP server running as a child process.
|
||||
*
|
||||
* Usage: php examples/client/stdio_discovery_calculator.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.
|
||||
*/
|
||||
|
||||
require_once __DIR__.'/../../vendor/autoload.php';
|
||||
|
||||
use Mcp\Client;
|
||||
use Mcp\Client\Transport\StdioTransport;
|
||||
use Mcp\Schema\Content\TextContent;
|
||||
use Mcp\Schema\Content\TextResourceContents;
|
||||
|
||||
$client = Client::builder()
|
||||
->setClientInfo('STDIO Example Client', '1.0.0')
|
||||
->setInitTimeout(30)
|
||||
->setRequestTimeout(60)
|
||||
->build();
|
||||
|
||||
$transport = new StdioTransport(
|
||||
command: 'php',
|
||||
args: [__DIR__.'/../server/discovery-calculator/server.php'],
|
||||
);
|
||||
|
||||
try {
|
||||
echo "Connecting to MCP server...\n";
|
||||
$client->connect($transport);
|
||||
|
||||
echo "Connected! Server info:\n";
|
||||
$serverInfo = $client->getServerInfo();
|
||||
echo ' Name: '.($serverInfo->name ?? 'unknown')."\n";
|
||||
echo ' Version: '.($serverInfo->version ?? 'unknown')."\n\n";
|
||||
|
||||
echo "Available tools:\n";
|
||||
$toolsResult = $client->listTools();
|
||||
foreach ($toolsResult->tools as $tool) {
|
||||
echo " - {$tool->name}: {$tool->description}\n";
|
||||
}
|
||||
echo "\n";
|
||||
|
||||
echo "Calling 'calculate' tool with a=5, b=3, operation='add'...\n";
|
||||
$result = $client->callTool('calculate', ['a' => 5, 'b' => 3, 'operation' => 'add']);
|
||||
echo 'Result: ';
|
||||
foreach ($result->content as $content) {
|
||||
if ($content instanceof TextContent) {
|
||||
echo $content->text;
|
||||
}
|
||||
}
|
||||
echo "\n\n";
|
||||
|
||||
echo "Available resources:\n";
|
||||
$resourcesResult = $client->listResources();
|
||||
foreach ($resourcesResult->resources as $resource) {
|
||||
echo " - {$resource->uri}: {$resource->name}\n";
|
||||
}
|
||||
echo "\n";
|
||||
|
||||
echo "Reading resource 'config://calculator/settings'...\n";
|
||||
$resourceContent = $client->readResource('config://calculator/settings');
|
||||
foreach ($resourceContent->contents as $content) {
|
||||
if ($content instanceof TextResourceContents) {
|
||||
echo ' Content: '.$content->text."\n";
|
||||
echo ' Mimetype: '.$content->mimeType."\n";
|
||||
}
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
echo "Error: {$e->getMessage()}\n";
|
||||
echo $e->getTraceAsString()."\n";
|
||||
} finally {
|
||||
echo "Disconnecting...\n";
|
||||
$client->disconnect();
|
||||
echo "Done.\n";
|
||||
}
|
||||
|
|
@ -8,10 +8,10 @@ The bootstrapping of the example will choose the used transport based on the SAP
|
|||
For running an example, you execute the `server.php` like this:
|
||||
```bash
|
||||
# For using the STDIO transport:
|
||||
php examples/discovery-calculator/server.php
|
||||
php examples/server/discovery-calculator/server.php
|
||||
|
||||
# For using the Streamable HTTP transport:
|
||||
php -S localhost:8000 examples/discovery-userprofile/server.php
|
||||
php -S localhost:8000 examples/server/discovery-userprofile/server.php
|
||||
```
|
||||
|
||||
You will see debug outputs to help you understand what is happening.
|
||||
|
|
@ -19,7 +19,7 @@ You will see debug outputs to help you understand what is happening.
|
|||
Run with Inspector:
|
||||
|
||||
```bash
|
||||
npx @modelcontextprotocol/inspector php examples/discovery-calculator/server.php
|
||||
npx @modelcontextprotocol/inspector php examples/server/discovery-calculator/server.php
|
||||
```
|
||||
|
||||
## Debugging
|
||||
|
|
@ -30,5 +30,5 @@ directory.
|
|||
|
||||
With the Inspector you can set the environment variables like this:
|
||||
```bash
|
||||
npx @modelcontextprotocol/inspector -e DEBUG=1 -e FILE_LOG=1 php examples/discovery-calculator/server.php
|
||||
npx @modelcontextprotocol/inspector -e DEBUG=1 -e FILE_LOG=1 php examples/server/discovery-calculator/server.php
|
||||
```
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ function shutdown(ResponseInterface|int $result): never
|
|||
function logger(): LoggerInterface
|
||||
{
|
||||
return new class extends AbstractLogger {
|
||||
public function log($level, Stringable|string $message, array $context = []): void
|
||||
public function log($level, string|Stringable $message, array $context = []): void
|
||||
{
|
||||
$debug = $_SERVER['DEBUG'] ?? false;
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
/*
|
||||
|
|
|
|||
284
src/Client.php
Normal file
284
src/Client.php
Normal file
|
|
@ -0,0 +1,284 @@
|
|||
<?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;
|
||||
|
||||
use Mcp\Client\Builder;
|
||||
use Mcp\Client\Configuration;
|
||||
use Mcp\Client\Protocol;
|
||||
use Mcp\Client\Transport\TransportInterface;
|
||||
use Mcp\Exception\ConnectionException;
|
||||
use Mcp\Exception\RequestException;
|
||||
use Mcp\Schema\Enum\LoggingLevel;
|
||||
use Mcp\Schema\Implementation;
|
||||
use Mcp\Schema\JsonRpc\Error;
|
||||
use Mcp\Schema\JsonRpc\Request;
|
||||
use Mcp\Schema\JsonRpc\Response;
|
||||
use Mcp\Schema\PromptReference;
|
||||
use Mcp\Schema\Request\CallToolRequest;
|
||||
use Mcp\Schema\Request\CompletionCompleteRequest;
|
||||
use Mcp\Schema\Request\GetPromptRequest;
|
||||
use Mcp\Schema\Request\ListPromptsRequest;
|
||||
use Mcp\Schema\Request\ListResourcesRequest;
|
||||
use Mcp\Schema\Request\ListResourceTemplatesRequest;
|
||||
use Mcp\Schema\Request\ListToolsRequest;
|
||||
use Mcp\Schema\Request\PingRequest;
|
||||
use Mcp\Schema\Request\ReadResourceRequest;
|
||||
use Mcp\Schema\Request\SetLogLevelRequest;
|
||||
use Mcp\Schema\ResourceReference;
|
||||
use Mcp\Schema\Result\CallToolResult;
|
||||
use Mcp\Schema\Result\CompletionCompleteResult;
|
||||
use Mcp\Schema\Result\GetPromptResult;
|
||||
use Mcp\Schema\Result\ListPromptsResult;
|
||||
use Mcp\Schema\Result\ListResourcesResult;
|
||||
use Mcp\Schema\Result\ListResourceTemplatesResult;
|
||||
use Mcp\Schema\Result\ListToolsResult;
|
||||
use Mcp\Schema\Result\ReadResourceResult;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Psr\Log\NullLogger;
|
||||
|
||||
/**
|
||||
* Main MCP Client facade.
|
||||
*
|
||||
* Provides a synchronous API for communicating with MCP servers.
|
||||
* All blocking operations are delegated to the transport.
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class Client
|
||||
{
|
||||
private ?TransportInterface $transport = null;
|
||||
|
||||
public function __construct(
|
||||
private readonly Protocol $protocol,
|
||||
private readonly Configuration $config,
|
||||
private readonly LoggerInterface $logger = new NullLogger(),
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new client builder for fluent configuration.
|
||||
*/
|
||||
public static function builder(): Builder
|
||||
{
|
||||
return new Builder();
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to an MCP server using the provided transport.
|
||||
*
|
||||
* @throws ConnectionException If connection or initialization fails
|
||||
*/
|
||||
public function connect(TransportInterface $transport): void
|
||||
{
|
||||
$this->transport = $transport;
|
||||
$this->protocol->connect($transport, $this->config);
|
||||
|
||||
$transport->connect();
|
||||
|
||||
$this->logger->info('Client connected and initialized');
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if connected and initialized.
|
||||
*/
|
||||
public function isConnected(): bool
|
||||
{
|
||||
return null !== $this->transport && $this->protocol->getState()->isInitialized();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server information from initialization.
|
||||
*/
|
||||
public function getServerInfo(): ?Implementation
|
||||
{
|
||||
return $this->protocol->getState()->getServerInfo();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get server instructions.
|
||||
*/
|
||||
public function getInstructions(): ?string
|
||||
{
|
||||
return $this->protocol->getState()->getInstructions();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a ping request to the server.
|
||||
*/
|
||||
public function ping(): void
|
||||
{
|
||||
$request = new PingRequest();
|
||||
|
||||
$this->sendRequest($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* List available tools from the server.
|
||||
*/
|
||||
public function listTools(?string $cursor = null): ListToolsResult
|
||||
{
|
||||
$request = new ListToolsRequest($cursor);
|
||||
|
||||
$response = $this->sendRequest($request);
|
||||
|
||||
return ListToolsResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call a tool on the server.
|
||||
*
|
||||
* @param string $name Tool name
|
||||
* @param array<string, mixed> $arguments Tool arguments
|
||||
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
|
||||
* Optional callback for progress updates
|
||||
*/
|
||||
public function callTool(string $name, array $arguments = [], ?callable $onProgress = null): CallToolResult
|
||||
{
|
||||
$request = new CallToolRequest($name, $arguments);
|
||||
|
||||
$response = $this->sendRequest($request, $onProgress);
|
||||
|
||||
return CallToolResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* List available resources from the server.
|
||||
*/
|
||||
public function listResources(?string $cursor = null): ListResourcesResult
|
||||
{
|
||||
$request = new ListResourcesRequest($cursor);
|
||||
|
||||
$response = $this->sendRequest($request);
|
||||
|
||||
return ListResourcesResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* List available resource templates from the server.
|
||||
*/
|
||||
public function listResourceTemplates(?string $cursor = null): ListResourceTemplatesResult
|
||||
{
|
||||
$request = new ListResourceTemplatesRequest($cursor);
|
||||
|
||||
$response = $this->sendRequest($request);
|
||||
|
||||
return ListResourceTemplatesResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a resource by URI.
|
||||
*
|
||||
* @param string $uri The resource URI
|
||||
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
|
||||
* Optional callback for progress updates
|
||||
*/
|
||||
public function readResource(string $uri, ?callable $onProgress = null): ReadResourceResult
|
||||
{
|
||||
$request = new ReadResourceRequest($uri);
|
||||
|
||||
$response = $this->sendRequest($request, $onProgress);
|
||||
|
||||
return ReadResourceResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* List available prompts from the server.
|
||||
*/
|
||||
public function listPrompts(?string $cursor = null): ListPromptsResult
|
||||
{
|
||||
$request = new ListPromptsRequest($cursor);
|
||||
|
||||
$response = $this->sendRequest($request);
|
||||
|
||||
return ListPromptsResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a prompt from the server.
|
||||
*
|
||||
* @param string $name Prompt name
|
||||
* @param array<string, string> $arguments Prompt arguments
|
||||
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
|
||||
* Optional callback for progress updates
|
||||
*/
|
||||
public function getPrompt(string $name, array $arguments = [], ?callable $onProgress = null): GetPromptResult
|
||||
{
|
||||
$request = new GetPromptRequest($name, $arguments);
|
||||
|
||||
$response = $this->sendRequest($request, $onProgress);
|
||||
|
||||
return GetPromptResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Request completion suggestions for a prompt or resource argument.
|
||||
*
|
||||
* @param PromptReference|ResourceReference $ref The prompt or resource reference
|
||||
* @param array{name: string, value: string} $argument The argument to complete
|
||||
*/
|
||||
public function complete(PromptReference|ResourceReference $ref, array $argument): CompletionCompleteResult
|
||||
{
|
||||
$request = new CompletionCompleteRequest($ref, $argument);
|
||||
|
||||
$response = $this->sendRequest($request);
|
||||
|
||||
return CompletionCompleteResult::fromArray($response->result);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the minimum logging level for server log messages.
|
||||
*/
|
||||
public function setLoggingLevel(LoggingLevel $level): void
|
||||
{
|
||||
$request = new SetLogLevelRequest($level);
|
||||
|
||||
$this->sendRequest($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a request to the server and wait for response.
|
||||
*
|
||||
* @param (callable(float $progress, ?float $total, ?string $message): void)|null $onProgress
|
||||
*
|
||||
* @return Response<mixed>
|
||||
*
|
||||
* @throws RequestException|ConnectionException
|
||||
*/
|
||||
private function sendRequest(Request $request, ?callable $onProgress = null): Response
|
||||
{
|
||||
if (!$this->isConnected()) {
|
||||
throw new ConnectionException('Client is not connected. Call connect() first.');
|
||||
}
|
||||
|
||||
$withProgress = null !== $onProgress;
|
||||
$fiber = new \Fiber(fn () => $this->protocol->request($request, $this->config->requestTimeout, $withProgress));
|
||||
$response = $this->transport->runRequest($fiber, $onProgress);
|
||||
|
||||
if ($response instanceof Error) {
|
||||
throw RequestException::fromError($response);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from the server.
|
||||
*/
|
||||
public function disconnect(): void
|
||||
{
|
||||
if (null !== $this->transport) {
|
||||
$this->transport->close();
|
||||
$this->transport = null;
|
||||
$this->logger->info('Client disconnected');
|
||||
}
|
||||
}
|
||||
}
|
||||
170
src/Client/Builder.php
Normal file
170
src/Client/Builder.php
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
<?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\Client;
|
||||
|
||||
use Mcp\Client;
|
||||
use Mcp\Client\Handler\Notification\NotificationHandlerInterface;
|
||||
use Mcp\Client\Handler\Request\RequestHandlerInterface;
|
||||
use Mcp\Schema\ClientCapabilities;
|
||||
use Mcp\Schema\Enum\ProtocolVersion;
|
||||
use Mcp\Schema\Implementation;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Psr\Log\NullLogger;
|
||||
|
||||
/**
|
||||
* Fluent builder for creating Client instances.
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
final class Builder
|
||||
{
|
||||
private string $name = 'mcp-php-client';
|
||||
private string $version = '1.0.0';
|
||||
private ?string $description = null;
|
||||
private ?ProtocolVersion $protocolVersion = null;
|
||||
private ?ClientCapabilities $capabilities = null;
|
||||
private int $initTimeout = 30;
|
||||
private int $requestTimeout = 120;
|
||||
private int $maxRetries = 3;
|
||||
private ?LoggerInterface $logger = null;
|
||||
|
||||
/** @var NotificationHandlerInterface[] */
|
||||
private array $notificationHandlers = [];
|
||||
|
||||
/** @var RequestHandlerInterface<mixed>[] */
|
||||
private array $requestHandlers = [];
|
||||
|
||||
/**
|
||||
* Set the client name and version.
|
||||
*/
|
||||
public function setClientInfo(string $name, string $version, ?string $description = null): self
|
||||
{
|
||||
$this->name = $name;
|
||||
$this->version = $version;
|
||||
$this->description = $description;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the protocol version to use.
|
||||
*/
|
||||
public function setProtocolVersion(ProtocolVersion $protocolVersion): self
|
||||
{
|
||||
$this->protocolVersion = $protocolVersion;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set client capabilities.
|
||||
*/
|
||||
public function setCapabilities(ClientCapabilities $capabilities): self
|
||||
{
|
||||
$this->capabilities = $capabilities;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set initialization timeout in seconds.
|
||||
*/
|
||||
public function setInitTimeout(int $seconds): self
|
||||
{
|
||||
$this->initTimeout = $seconds;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set request timeout in seconds.
|
||||
*/
|
||||
public function setRequestTimeout(int $seconds): self
|
||||
{
|
||||
$this->requestTimeout = $seconds;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set maximum retry attempts for failed connections.
|
||||
*/
|
||||
public function setMaxRetries(int $retries): self
|
||||
{
|
||||
$this->maxRetries = $retries;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the logger.
|
||||
*/
|
||||
public function setLogger(LoggerInterface $logger): self
|
||||
{
|
||||
$this->logger = $logger;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a notification handler for server notifications.
|
||||
*/
|
||||
public function addNotificationHandler(NotificationHandlerInterface $handler): self
|
||||
{
|
||||
$this->notificationHandlers[] = $handler;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a request handler for server requests (e.g., sampling).
|
||||
*
|
||||
* @param RequestHandlerInterface<mixed> $handler
|
||||
*/
|
||||
public function addRequestHandler(RequestHandlerInterface $handler): self
|
||||
{
|
||||
$this->requestHandlers[] = $handler;
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the client instance.
|
||||
*/
|
||||
public function build(): Client
|
||||
{
|
||||
$logger = $this->logger ?? new NullLogger();
|
||||
|
||||
$clientInfo = new Implementation(
|
||||
$this->name,
|
||||
$this->version,
|
||||
$this->description,
|
||||
);
|
||||
|
||||
$config = new Configuration(
|
||||
clientInfo: $clientInfo,
|
||||
capabilities: $this->capabilities ?? new ClientCapabilities(),
|
||||
protocolVersion: $this->protocolVersion ?? ProtocolVersion::V2025_06_18,
|
||||
initTimeout: $this->initTimeout,
|
||||
requestTimeout: $this->requestTimeout,
|
||||
maxRetries: $this->maxRetries,
|
||||
);
|
||||
|
||||
$protocol = new Protocol(
|
||||
requestHandlers: $this->requestHandlers,
|
||||
notificationHandlers: $this->notificationHandlers,
|
||||
logger: $logger,
|
||||
);
|
||||
|
||||
return new Client($protocol, $config, $logger);
|
||||
}
|
||||
}
|
||||
34
src/Client/Configuration.php
Normal file
34
src/Client/Configuration.php
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
<?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\Client;
|
||||
|
||||
use Mcp\Schema\ClientCapabilities;
|
||||
use Mcp\Schema\Enum\ProtocolVersion;
|
||||
use Mcp\Schema\Implementation;
|
||||
|
||||
/**
|
||||
* Client configuration holder.
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class Configuration
|
||||
{
|
||||
public function __construct(
|
||||
public readonly Implementation $clientInfo,
|
||||
public readonly ClientCapabilities $capabilities,
|
||||
public readonly ProtocolVersion $protocolVersion = ProtocolVersion::V2025_06_18,
|
||||
public readonly int $initTimeout = 30,
|
||||
public readonly int $requestTimeout = 120,
|
||||
public readonly int $maxRetries = 3,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
<?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\Client\Handler\Notification;
|
||||
|
||||
use Mcp\Schema\JsonRpc\Notification;
|
||||
use Mcp\Schema\Notification\LoggingMessageNotification;
|
||||
|
||||
/**
|
||||
* Handler for logging message notifications from the server.
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class LoggingNotificationHandler implements NotificationHandlerInterface
|
||||
{
|
||||
/**
|
||||
* @param callable(LoggingMessageNotification): void $callback
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly mixed $callback,
|
||||
) {
|
||||
}
|
||||
|
||||
public function supports(Notification $notification): bool
|
||||
{
|
||||
return $notification instanceof LoggingMessageNotification;
|
||||
}
|
||||
|
||||
public function handle(Notification $notification): void
|
||||
{
|
||||
\assert($notification instanceof LoggingMessageNotification);
|
||||
|
||||
($this->callback)($notification);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
<?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\Client\Handler\Notification;
|
||||
|
||||
use Mcp\Schema\JsonRpc\Notification;
|
||||
|
||||
/**
|
||||
* Interface for handling notifications from the server.
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
interface NotificationHandlerInterface
|
||||
{
|
||||
/**
|
||||
* Check if this handler supports the given notification.
|
||||
*/
|
||||
public function supports(Notification $notification): bool;
|
||||
|
||||
/**
|
||||
* Handle the notification.
|
||||
*/
|
||||
public function handle(Notification $notification): void;
|
||||
}
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
<?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\Client\Handler\Notification;
|
||||
|
||||
use Mcp\Client\State\ClientStateInterface;
|
||||
use Mcp\Schema\JsonRpc\Notification;
|
||||
use Mcp\Schema\Notification\ProgressNotification;
|
||||
|
||||
/**
|
||||
* Internal handler for progress notifications.
|
||||
*
|
||||
* Writes progress data to state for transport to consume and execute callbacks.
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*
|
||||
* @internal
|
||||
*/
|
||||
class ProgressNotificationHandler implements NotificationHandlerInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ClientStateInterface $state,
|
||||
) {
|
||||
}
|
||||
|
||||
public function supports(Notification $notification): bool
|
||||
{
|
||||
return $notification instanceof ProgressNotification;
|
||||
}
|
||||
|
||||
public function handle(Notification $notification): void
|
||||
{
|
||||
if (!$notification instanceof ProgressNotification) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->state->storeProgress(
|
||||
(string) $notification->progressToken,
|
||||
$notification->progress,
|
||||
$notification->total,
|
||||
$notification->message,
|
||||
);
|
||||
}
|
||||
}
|
||||
38
src/Client/Handler/Request/RequestHandlerInterface.php
Normal file
38
src/Client/Handler/Request/RequestHandlerInterface.php
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
<?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\Client\Handler\Request;
|
||||
|
||||
use Mcp\Schema\JsonRpc\Error;
|
||||
use Mcp\Schema\JsonRpc\Request;
|
||||
use Mcp\Schema\JsonRpc\Response;
|
||||
|
||||
/**
|
||||
* Interface for handling requests from the server.
|
||||
*
|
||||
* @template TResult
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
interface RequestHandlerInterface
|
||||
{
|
||||
/**
|
||||
* Check if this handler supports the given request.
|
||||
*/
|
||||
public function supports(Request $request): bool;
|
||||
|
||||
/**
|
||||
* Handle the request and return a response or error.
|
||||
*
|
||||
* @return Response<TResult>|Error
|
||||
*/
|
||||
public function handle(Request $request): Response|Error;
|
||||
}
|
||||
25
src/Client/Handler/Request/SamplingCallbackInterface.php
Normal file
25
src/Client/Handler/Request/SamplingCallbackInterface.php
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
<?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\Client\Handler\Request;
|
||||
|
||||
use Mcp\Schema\Request\CreateSamplingMessageRequest;
|
||||
use Mcp\Schema\Result\CreateSamplingMessageResult;
|
||||
|
||||
/**
|
||||
* Contract for callbacks used by SamplingRequestHandler.
|
||||
*
|
||||
* Implementations perform the actual LLM sampling when requested by the server.
|
||||
*/
|
||||
interface SamplingCallbackInterface
|
||||
{
|
||||
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult;
|
||||
}
|
||||
67
src/Client/Handler/Request/SamplingRequestHandler.php
Normal file
67
src/Client/Handler/Request/SamplingRequestHandler.php
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
<?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\Client\Handler\Request;
|
||||
|
||||
use Mcp\Exception\SamplingException;
|
||||
use Mcp\Schema\JsonRpc\Error;
|
||||
use Mcp\Schema\JsonRpc\Request;
|
||||
use Mcp\Schema\JsonRpc\Response;
|
||||
use Mcp\Schema\Request\CreateSamplingMessageRequest;
|
||||
use Mcp\Schema\Result\CreateSamplingMessageResult;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Psr\Log\NullLogger;
|
||||
|
||||
/**
|
||||
* Handler for sampling requests from the server.
|
||||
*
|
||||
* The MCP server may request the client to sample an LLM during tool execution.
|
||||
* This handler wraps a user-provided callback that performs the actual LLM call.
|
||||
*
|
||||
* @implements RequestHandlerInterface<CreateSamplingMessageResult>
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class SamplingRequestHandler implements RequestHandlerInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly SamplingCallbackInterface $callback,
|
||||
private readonly LoggerInterface $logger = new NullLogger(),
|
||||
) {
|
||||
}
|
||||
|
||||
public function supports(Request $request): bool
|
||||
{
|
||||
return $request instanceof CreateSamplingMessageRequest;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Response<CreateSamplingMessageResult>|Error
|
||||
*/
|
||||
public function handle(Request $request): Response|Error
|
||||
{
|
||||
\assert($request instanceof CreateSamplingMessageRequest);
|
||||
|
||||
try {
|
||||
$result = $this->callback->__invoke($request);
|
||||
|
||||
return new Response($request->getId(), $result);
|
||||
} catch (SamplingException $e) {
|
||||
$this->logger->error('Sampling failed: '.$e->getMessage());
|
||||
|
||||
return Error::forInternalError($e->getMessage(), $request->getId());
|
||||
} catch (\Throwable $e) {
|
||||
$this->logger->error('Unexpected error during sampling', ['exception' => $e]);
|
||||
|
||||
return Error::forInternalError('Error while sampling LLM', $request->getId());
|
||||
}
|
||||
}
|
||||
}
|
||||
318
src/Client/Protocol.php
Normal file
318
src/Client/Protocol.php
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
<?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\Client;
|
||||
|
||||
use Mcp\Client\Handler\Notification\NotificationHandlerInterface;
|
||||
use Mcp\Client\Handler\Notification\ProgressNotificationHandler;
|
||||
use Mcp\Client\Handler\Request\RequestHandlerInterface;
|
||||
use Mcp\Client\State\ClientState;
|
||||
use Mcp\Client\State\ClientStateInterface;
|
||||
use Mcp\Client\Transport\TransportInterface;
|
||||
use Mcp\JsonRpc\MessageFactory;
|
||||
use Mcp\Schema\JsonRpc\Error;
|
||||
use Mcp\Schema\JsonRpc\Notification;
|
||||
use Mcp\Schema\JsonRpc\Request;
|
||||
use Mcp\Schema\JsonRpc\Response;
|
||||
use Mcp\Schema\Notification\InitializedNotification;
|
||||
use Mcp\Schema\Request\InitializeRequest;
|
||||
use Mcp\Schema\Result\InitializeResult;
|
||||
use Psr\Log\LoggerInterface;
|
||||
use Psr\Log\NullLogger;
|
||||
|
||||
/**
|
||||
* Client protocol handler for MCP communication.
|
||||
*
|
||||
* Handles message routing, request/response correlation, and the initialization handshake.
|
||||
* All blocking operations are delegated to the transport.
|
||||
*
|
||||
* @phpstan-import-type FiberSuspend from TransportInterface
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class Protocol
|
||||
{
|
||||
private ?TransportInterface $transport = null;
|
||||
private ClientStateInterface $state;
|
||||
private MessageFactory $messageFactory;
|
||||
private LoggerInterface $logger;
|
||||
|
||||
/** @var NotificationHandlerInterface[] */
|
||||
private array $notificationHandlers;
|
||||
|
||||
/**
|
||||
* @param RequestHandlerInterface<mixed>[] $requestHandlers
|
||||
* @param NotificationHandlerInterface[] $notificationHandlers
|
||||
*/
|
||||
public function __construct(
|
||||
private readonly array $requestHandlers = [],
|
||||
array $notificationHandlers = [],
|
||||
?MessageFactory $messageFactory = null,
|
||||
?LoggerInterface $logger = null,
|
||||
) {
|
||||
$this->state = new ClientState();
|
||||
$this->messageFactory = $messageFactory ?? MessageFactory::make();
|
||||
$this->logger = $logger ?? new NullLogger();
|
||||
|
||||
$this->notificationHandlers = [
|
||||
new ProgressNotificationHandler($this->state),
|
||||
...$notificationHandlers,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect this protocol to a transport.
|
||||
*
|
||||
* Sets up message handling callbacks.
|
||||
*
|
||||
* @param TransportInterface $transport The transport to connect
|
||||
* @param Configuration $config The client configuration for initialization
|
||||
*/
|
||||
public function connect(TransportInterface $transport, Configuration $config): void
|
||||
{
|
||||
$this->transport = $transport;
|
||||
$transport->setState($this->state);
|
||||
$transport->onInitialize(fn () => $this->initialize($config));
|
||||
$transport->onMessage($this->processMessage(...));
|
||||
$transport->onError(fn (\Throwable $e) => $this->logger->error('Transport error', ['exception' => $e]));
|
||||
|
||||
$this->logger->info('Protocol connected to transport', ['transport' => $transport::class]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform the MCP initialization handshake.
|
||||
*
|
||||
* Sends InitializeRequest and waits for response, then sends InitializedNotification.
|
||||
*
|
||||
* @param Configuration $config The client configuration
|
||||
*
|
||||
* @return Response<array<string, mixed>>|Error
|
||||
*/
|
||||
public function initialize(Configuration $config): Response|Error
|
||||
{
|
||||
$request = new InitializeRequest(
|
||||
$config->protocolVersion->value,
|
||||
$config->capabilities,
|
||||
$config->clientInfo,
|
||||
);
|
||||
|
||||
$response = $this->request($request, $config->initTimeout);
|
||||
|
||||
if ($response instanceof Response) {
|
||||
$initResult = InitializeResult::fromArray($response->result);
|
||||
$this->state->setServerInfo($initResult->serverInfo);
|
||||
$this->state->setInstructions($initResult->instructions);
|
||||
$this->state->setInitialized(true);
|
||||
|
||||
$this->sendNotification(new InitializedNotification());
|
||||
|
||||
$this->logger->info('Initialization complete', [
|
||||
'server' => $initResult->serverInfo->name,
|
||||
]);
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a request to the server and wait for response.
|
||||
*
|
||||
* If a response is immediately available (sync HTTP), returns it.
|
||||
* Otherwise, suspends the Fiber and waits for the transport to resume it.
|
||||
*
|
||||
* @param Request $request The request to send
|
||||
* @param int $timeout The timeout in seconds
|
||||
* @param bool $withProgress Whether to attach a progress token to the request
|
||||
*
|
||||
* @return Response<array<string, mixed>>|Error
|
||||
*/
|
||||
public function request(Request $request, int $timeout, bool $withProgress = false): Response|Error
|
||||
{
|
||||
$requestId = $this->state->nextRequestId();
|
||||
$request = $request->withId($requestId);
|
||||
|
||||
if ($withProgress) {
|
||||
$progressToken = "prog-{$requestId}";
|
||||
$request = $request->withMeta(['progressToken' => $progressToken]);
|
||||
}
|
||||
|
||||
$this->state->addPendingRequest($requestId, $timeout);
|
||||
$this->sendRequest($request);
|
||||
|
||||
$immediate = $this->state->consumeResponse($requestId);
|
||||
if (null !== $immediate) {
|
||||
$this->logger->debug('Received immediate response', ['id' => $requestId]);
|
||||
|
||||
return $immediate;
|
||||
}
|
||||
|
||||
$this->logger->debug('Suspending fiber for response', ['id' => $requestId]);
|
||||
|
||||
return \Fiber::suspend([
|
||||
'type' => 'await_response',
|
||||
'request_id' => $requestId,
|
||||
'timeout' => $timeout,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a request to the server.
|
||||
*/
|
||||
private function sendRequest(Request $request): void
|
||||
{
|
||||
$this->logger->debug('Sending request', [
|
||||
'id' => $request->getId(),
|
||||
'method' => $request::getMethod(),
|
||||
]);
|
||||
|
||||
$encoded = json_encode($request, \JSON_THROW_ON_ERROR);
|
||||
$this->transport?->send($encoded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a notification to the server (fire and forget).
|
||||
*/
|
||||
public function sendNotification(Notification $notification): void
|
||||
{
|
||||
$this->logger->debug('Sending notification', ['method' => $notification::getMethod()]);
|
||||
|
||||
$encoded = json_encode($notification, \JSON_THROW_ON_ERROR);
|
||||
$this->transport?->send($encoded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a response back to the server (for server-initiated requests).
|
||||
*
|
||||
* @param Response<mixed>|Error $response
|
||||
*/
|
||||
private function sendResponse(Response|Error $response): void
|
||||
{
|
||||
$this->logger->debug('Sending response', ['id' => $response->getId()]);
|
||||
|
||||
$encoded = json_encode($response, \JSON_THROW_ON_ERROR);
|
||||
$this->transport?->send($encoded);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process an incoming message from the server.
|
||||
*
|
||||
* Routes to appropriate handler based on message type.
|
||||
*/
|
||||
public function processMessage(string $input): void
|
||||
{
|
||||
$this->logger->debug('Received message', ['input' => $input]);
|
||||
|
||||
try {
|
||||
$messages = $this->messageFactory->create($input);
|
||||
} catch (\JsonException $e) {
|
||||
$this->logger->warning('Failed to parse message', ['exception' => $e]);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($messages as $message) {
|
||||
if ($message instanceof Response || $message instanceof Error) {
|
||||
$this->handleResponse($message);
|
||||
} elseif ($message instanceof Request) {
|
||||
$this->handleRequest($message);
|
||||
} elseif ($message instanceof Notification) {
|
||||
$this->handleNotification($message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a response from the server.
|
||||
*
|
||||
* This stores it in session. The transport will pick it up and resume the Fiber.
|
||||
*
|
||||
* @param Response<mixed>|Error $response
|
||||
*/
|
||||
private function handleResponse(Response|Error $response): void
|
||||
{
|
||||
$requestId = $response->getId();
|
||||
|
||||
$this->logger->debug('Handling response', ['id' => $requestId]);
|
||||
|
||||
$this->state->storeResponse($requestId, $response->jsonSerialize());
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a request from the server (e.g., sampling request).
|
||||
*/
|
||||
private function handleRequest(Request $request): void
|
||||
{
|
||||
$method = $request::getMethod();
|
||||
|
||||
$this->logger->debug('Received server request', [
|
||||
'method' => $method,
|
||||
'id' => $request->getId(),
|
||||
]);
|
||||
|
||||
foreach ($this->requestHandlers as $handler) {
|
||||
if ($handler->supports($request)) {
|
||||
try {
|
||||
$response = $handler->handle($request);
|
||||
} catch (\Throwable $e) {
|
||||
$this->logger->error('Unexpected error while handling request', [
|
||||
'method' => $method,
|
||||
'exception' => $e,
|
||||
]);
|
||||
|
||||
$response = Error::forInternalError(
|
||||
\sprintf('Unexpected error while handling "%s" request', $method),
|
||||
$request->getId()
|
||||
);
|
||||
}
|
||||
|
||||
$this->sendResponse($response);
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
$error = Error::forMethodNotFound(
|
||||
\sprintf('Client does not handle "%s" requests.', $method),
|
||||
$request->getId()
|
||||
);
|
||||
|
||||
$this->sendResponse($error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a notification from the server.
|
||||
*/
|
||||
private function handleNotification(Notification $notification): void
|
||||
{
|
||||
$method = $notification::getMethod();
|
||||
|
||||
$this->logger->debug('Received server notification', [
|
||||
'method' => $method,
|
||||
]);
|
||||
|
||||
foreach ($this->notificationHandlers as $handler) {
|
||||
if ($handler->supports($notification)) {
|
||||
try {
|
||||
$handler->handle($notification);
|
||||
} catch (\Throwable $e) {
|
||||
$this->logger->warning('Notification handler failed', ['exception' => $e]);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function getState(): ClientStateInterface
|
||||
{
|
||||
return $this->state;
|
||||
}
|
||||
}
|
||||
136
src/Client/State/ClientState.php
Normal file
136
src/Client/State/ClientState.php
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
<?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\Client\State;
|
||||
|
||||
use Mcp\Schema\Implementation;
|
||||
use Mcp\Schema\JsonRpc\Error;
|
||||
use Mcp\Schema\JsonRpc\Response;
|
||||
|
||||
/**
|
||||
* In-memory client state implementation.
|
||||
*
|
||||
* Stores ephemeral runtime state for the client's connection to a server.
|
||||
* This includes pending requests, responses, progress updates, and
|
||||
* negotiated parameters from initialization.
|
||||
*
|
||||
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
|
||||
*/
|
||||
class ClientState implements ClientStateInterface
|
||||
{
|
||||
private int $requestIdCounter = 1;
|
||||
private bool $initialized = false;
|
||||
private ?Implementation $serverInfo = null;
|
||||
private ?string $instructions = null;
|
||||
|
||||
/** @var array<int|string, array{request_id: int|string, timestamp: int, timeout: int}> */
|
||||
private array $pendingRequests = [];
|
||||
|
||||
/** @var array<int|string, array<string, mixed>> */
|
||||
private array $responses = [];
|
||||
|
||||
/** @var array<int, array{token: string, progress: float, total: ?float, message: ?string}> */
|
||||
private array $progressUpdates = [];
|
||||
|
||||
public function nextRequestId(): int
|
||||
{
|
||||
return $this->requestIdCounter++;
|
||||
}
|
||||
|
||||
public function addPendingRequest(int|string $requestId, int $timeout): void
|
||||
{
|
||||
$this->pendingRequests[$requestId] = [
|
||||
'request_id' => $requestId,
|
||||
'timestamp' => time(),
|
||||
'timeout' => $timeout,
|
||||
];
|
||||
}
|
||||
|
||||
public function removePendingRequest(int|string $requestId): void
|
||||
{
|
||||
unset($this->pendingRequests[$requestId]);
|
||||
}
|
||||
|
||||
public function getPendingRequests(): array
|
||||
{
|
||||
return $this->pendingRequests;
|
||||
}
|
||||
|
||||
public function storeResponse(int|string $requestId, array $responseData): void
|
||||
{
|
||||
$this->responses[$requestId] = $responseData;
|
||||
}
|
||||
|
||||
public function consumeResponse(int|string $requestId): Response|Error|null
|
||||
{
|
||||
if (!isset($this->responses[$requestId])) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = $this->responses[$requestId];
|
||||
unset($this->responses[$requestId]);
|
||||
$this->removePendingRequest($requestId);
|
||||
|
||||
if (isset($data['error'])) {
|
||||
return Error::fromArray($data);
|
||||
}
|
||||
|
||||
return Response::fromArray($data);
|
||||
}
|
||||
|
||||
public function setInitialized(bool $initialized): void
|
||||
{
|
||||
$this->initialized = $initialized;
|
||||
}
|
||||
|
||||
public function isInitialized(): bool
|
||||
{
|
||||
return $this->initialized;
|
||||
}
|
||||
|
||||
public function setServerInfo(Implementation $serverInfo): void
|
||||
{
|
||||
$this->serverInfo = $serverInfo;
|
||||
}
|
||||
|
||||
public function getServerInfo(): ?Implementation
|
||||
{
|
||||
return $this->serverInfo;
|
||||
}
|
||||
|
||||
public function setInstructions(?string $instructions): void
|
||||
{
|
||||
$this->instructions = $instructions;
|
||||
}
|
||||
|
||||
public function getInstructions(): ?string
|
||||
{
|
||||
return $this->instructions;
|
||||
}
|
||||
|
||||
public function storeProgress(string $token, float $progress, ?float $total, ?string $message): void
|
||||
{
|
||||
$this->progressUpdates[] = [
|
||||
'token' => $token,
|
||||
'progress' => $progress,
|
||||
'total' => $total,
|
||||
'message' => $message,
|
||||
];
|
||||
}
|
||||
|
||||
public function consumeProgressUpdates(): array
|
||||
{
|
||||
$updates = $this->progressUpdates;
|
||||
$this->progressUpdates = [];
|
||||
|
||||
return $updates;
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue