Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
92.31% covered (success)
92.31%
12 / 13
80.00% covered (warning)
80.00%
4 / 5
CRAP
0.00% covered (danger)
0.00%
0 / 1
InMemoryTransport
92.31% covered (success)
92.31%
12 / 13
80.00% covered (warning)
80.00%
4 / 5
9.04
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 readMessage
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
4
 writeMessage
66.67% covered (warning)
66.67%
2 / 3
0.00% covered (danger)
0.00%
0 / 1
2.15
 start
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 stop
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
1<?php
2namespace Apie\McpServer\Transport;
3
4use Apie\McpServer\Exception\StopRunnerException;
5use Mcp\Server\Transport\Transport;
6use Mcp\Types\JsonRpcMessage;
7
8/**
9 * The mcp server package we use have no testability classes, so we use our own in-memory transport.
10 * This allows us to test the server without needing a real transport layer.
11 */
12class InMemoryTransport implements Transport
13{
14    /**
15     * @var array<int, JsonRpcMessage> $written
16     */
17    public array $written = [];
18
19    /**
20     * @param array<int, JsonRpcMessage> $messages
21     */
22    public function __construct(
23        private array $messages
24    ) {
25    }
26    private bool $isRunning = false;
27
28    public function readMessage(): ?JsonRpcMessage
29    {
30        if (!$this->isRunning) {
31            throw new StopRunnerException('Transport is not running');
32        }
33        $res = array_shift($this->messages) ?: null;
34        if (empty($this->messages)) {
35            $this->isRunning = false;
36        }
37        return $res;
38    }
39
40    /**
41     * Write a message to the transport
42     *
43     * @param JsonRpcMessage $message The message to write
44     * @throws \Exception if an error occurs while writing
45     */
46    public function writeMessage(JsonRpcMessage $message): void
47    {
48        if (!$this->isRunning) {
49            throw new StopRunnerException('Transport is not running');
50        }
51        $this->written[] = $message;
52    }
53    public function start(): void
54    {
55        $this->isRunning = true;
56    }
57
58    public function stop(): void
59    {
60        $this->isRunning = false;
61        $this->messages = [];
62    }
63}