1+ <?php
2+
3+ namespace Luoyue \WebmanMcp \Server ;
4+
5+ use \Mcp \Server \Transport \StreamableHttpTransport as BaseStreamableHttpTransport ;
6+ use Psr \Http \Message \ResponseFactoryInterface ;
7+ use Psr \Http \Message \ServerRequestInterface ;
8+ use Psr \Http \Message \StreamFactoryInterface ;
9+ use Psr \Log \LoggerInterface ;
10+ use Psr \Log \NullLogger ;
11+ use Symfony \Component \Uid \Uuid ;
12+ use Workerman \Connection \TcpConnection ;
13+ use Workerman \Protocols \Http \ServerSentEvents ;
14+
15+ class StreamableHttpTransport extends BaseStreamableHttpTransport
16+ {
17+
18+ private readonly TcpConnection $ connection ;
19+
20+ /**
21+ * @param array<string, string> $corsHeaders
22+ */
23+ public function __construct (
24+ private readonly ServerRequestInterface $ request ,
25+ ?ResponseFactoryInterface $ responseFactory = null ,
26+ ?StreamFactoryInterface $ streamFactory = null ,
27+ array $ corsHeaders = [],
28+ LoggerInterface $ logger = new NullLogger (),
29+ ) {
30+ $ this ->connection = $ request ->getAttribute (TcpConnection::class);
31+ parent ::__construct ($ request , $ responseFactory , $ streamFactory , $ corsHeaders , $ logger );
32+ }
33+
34+ protected function handleFiberTermination (): void
35+ {
36+ $ finalResult = $ this ->sessionFiber ->getReturn ();
37+
38+ if (null !== $ finalResult ) {
39+ try {
40+ $ encoded = json_encode ($ finalResult , \JSON_THROW_ON_ERROR );
41+ $ this ->connection ->send (new ServerSentEvents ([
42+ 'event ' => 'message ' ,
43+ 'data ' => $ encoded ,
44+ ]));
45+ } catch (\JsonException $ e ) {
46+ $ this ->logger ->error ('SSE: Failed to encode final Fiber result. ' , ['exception ' => $ e ]);
47+ }
48+ }
49+
50+ $ this ->sessionFiber = null ;
51+ }
52+
53+ protected function flushOutgoingMessages (?Uuid $ sessionId ): void
54+ {
55+ $ messages = $ this ->getOutgoingMessages ($ sessionId );
56+
57+ foreach ($ messages as $ message ) {
58+ $ this ->connection ->send (new ServerSentEvents ([
59+ 'event ' => 'message ' ,
60+ 'data ' => $ message ['message ' ],
61+ ]));
62+ }
63+ }
64+
65+ }
0 commit comments