[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
8 changed files with 2731 additions and 9 deletions
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
|
||||
|
||||
/*
|
||||
|
|
|
|||
Loading…
Reference in a new issue