php-sdk/src/Server/Transport/StdioTransport.php
Kyrian Obikwelu 2dbd411194
[Server] Simplify server entrypoint with run-based transport lifecycle (#103)
* feat: replace connect/listen flow with run lifecycle

* feat(transport): add phpstan generics for typed transport returns

* refactor: standardize variable naming for MCP server instances in transport handling

* test: remove unnecessary phpstan-ignore annotation in DocBlockTestFixture
2025-10-10 18:52:06 +01:00

118 lines
3 KiB
PHP

<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Server\Transport;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\Uid\Uuid;
/**
* @implements TransportInterface<int>
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class StdioTransport implements TransportInterface
{
/** @var callable(string, ?Uuid): void */
private $messageListener;
/** @var callable(Uuid): void */
private $sessionEndListener;
private ?Uuid $sessionId = null;
/**
* @param resource $input
* @param resource $output
*/
public function __construct(
private $input = \STDIN,
private $output = \STDOUT,
private readonly LoggerInterface $logger = new NullLogger(),
) {
}
public function initialize(): void
{
}
public function onMessage(callable $listener): void
{
$this->messageListener = $listener;
}
public function send(string $data, array $context): void
{
$this->logger->debug('Sending data to client via StdioTransport.', ['data' => $data]);
if (isset($context['session_id'])) {
$this->sessionId = $context['session_id'];
}
fwrite($this->output, $data.\PHP_EOL);
}
public function listen(): int
{
$this->logger->info('StdioTransport is listening for messages on STDIN...');
$status = 0;
while (!feof($this->input)) {
$line = fgets($this->input);
if (false === $line) {
if (!feof($this->input)) {
$status = 1;
}
break;
}
$trimmedLine = trim($line);
if (!empty($trimmedLine)) {
$this->logger->debug('Received message on StdioTransport.', ['line' => $trimmedLine]);
if (\is_callable($this->messageListener)) {
\call_user_func($this->messageListener, $trimmedLine, $this->sessionId);
}
}
}
$this->logger->info('StdioTransport finished listening.');
if (\is_callable($this->sessionEndListener) && null !== $this->sessionId) {
\call_user_func($this->sessionEndListener, $this->sessionId);
$this->sessionId = null;
}
return $status;
}
public function onSessionEnd(callable $listener): void
{
$this->sessionEndListener = $listener;
}
public function close(): void
{
if (\is_callable($this->sessionEndListener) && null !== $this->sessionId) {
\call_user_func($this->sessionEndListener, $this->sessionId);
$this->sessionId = null;
}
if (\is_resource($this->input)) {
fclose($this->input);
}
if (\is_resource($this->output)) {
fclose($this->output);
}
}
}