Repository navigation
Expand file tree
/
Copy pathStreamableHttpTransportTest.php
More file actions
992 lines (808 loc) · 43.4 KB
/
Copy pathStreamableHttpTransportTest.php
File metadata and controls
992 lines (808 loc) · 43.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
<?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\Tests\Unit\Server\Transport;
use Mcp\Schema\Enum\ProtocolVersion;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\Notification\ProgressNotification;
use Mcp\Schema\Request\PingRequest;
use Mcp\Server\Exception\ClientException;
use Mcp\Server\Exception\InvalidArgumentException;
use Mcp\Server\RequestContext;
use Mcp\Server\Server;
use Mcp\Server\Session\FileSessionLock;
use Mcp\Server\Session\InMemorySessionStore;
use Mcp\Server\Session\Session;
use Mcp\Server\Session\SessionLockInterface;
use Mcp\Server\Suspension\RequestSuspension;
use Mcp\Server\Transport\Http\Middleware\CorsMiddleware;
use Mcp\Server\Transport\Http\Middleware\DnsRebindingProtectionMiddleware;
use Mcp\Server\Transport\Http\Middleware\PassthroughMiddleware;
use Mcp\Server\Transport\Http\Middleware\ProtocolVersionMiddleware;
use Mcp\Server\Transport\StreamableHttpTransport;
use Mcp\Server\Transport\TransportInterface;
use Mcp\Tests\Unit\Server\Session\Fixture\HeldElsewhereSessionLock;
use Mcp\Tests\Unit\Server\Session\Fixture\InterleavingSessionStore;
use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\TestDox;
use PHPUnit\Framework\TestCase;
use Psr\Clock\ClockInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Uid\Uuid;
final class StreamableHttpTransportTest extends TestCase
{
private Psr17Factory $factory;
private ?string $lockDirectory = null;
protected function setUp(): void
{
$this->factory = new Psr17Factory();
}
protected function tearDown(): void
{
if (null === $this->lockDirectory || !is_dir($this->lockDirectory)) {
return;
}
foreach (glob($this->lockDirectory.'/*') ?: [] as $file) {
@unlink($file);
}
@rmdir($this->lockDirectory);
}
#[TestDox('default middleware is applied when none is passed')]
public function testDefaultMiddlewareIsAppliedWhenOmitted(): void
{
// Preflight: OPTIONS + Access-Control-Request-Method — CorsMiddleware advertises Methods/Headers only on preflight.
$request = $this->factory
->createServerRequest('OPTIONS', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader('Access-Control-Request-Method', 'POST');
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
$response = $transport->listen();
$this->assertSame(204, $response->getStatusCode());
$this->assertFalse($response->hasHeader('Access-Control-Allow-Origin')); // secure-by-default
$this->assertSame('GET, POST, DELETE', $response->getHeaderLine('Access-Control-Allow-Methods'));
$this->assertNotSame('', $response->getHeaderLine('Access-Control-Allow-Headers'));
$this->assertNotSame('', $response->getHeaderLine('Access-Control-Expose-Headers'));
}
#[TestDox('default middleware blocks non-localhost Origin')]
public function testDefaultMiddlewareBlocksRebindingAttempt(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader('Origin', 'http://evil.example.com');
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
$response = $transport->listen();
$this->assertSame(403, $response->getStatusCode());
}
#[TestDox('default middleware rejects unsupported MCP-Protocol-Version')]
public function testDefaultMiddlewareRejectsUnsupportedProtocolVersion(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader(StreamableHttpTransport::PROTOCOL_VERSION_HEADER, '1900-01-01');
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
$response = $transport->listen();
$this->assertSame(400, $response->getStatusCode());
}
#[TestDox('malformed MCP session IDs are rejected as bad requests')]
public function testMalformedSessionIdHeaderReturnsBadRequest(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader(StreamableHttpTransport::SESSION_HEADER, '{"not":"a-token"}');
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
$response = $transport->listen();
$this->assertSame(400, $response->getStatusCode());
$this->assertStringContainsString(StreamableHttpTransport::SESSION_HEADER, (string) $response->getBody());
}
#[TestDox('duplicate MCP session ID headers are rejected as bad requests')]
public function testDuplicateSessionIdHeadersReturnBadRequest(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader(StreamableHttpTransport::SESSION_HEADER, '2fb587fc-593f-47ce-9d9a-9c06f2b907a3')
->withAddedHeader(StreamableHttpTransport::SESSION_HEADER, '5e583da8-a677-4446-b723-4ddbe00fda62');
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
$response = $transport->listen();
$this->assertSame(400, $response->getStatusCode());
$this->assertStringContainsString('must not be repeated', (string) $response->getBody());
}
#[TestDox('a DELETE of an unknown or already ended session is answered 404')]
public function testDeleteOfAnEndedSessionIsNotFound(): void
{
$server = Server::builder()->setServerInfo('test', '1.0')->setSession(new InMemorySessionStore())->build();
$sessionId = $this->initialize($server);
$this->assertSame(200, $this->delete($server, $sessionId)->getStatusCode());
$response = $this->delete($server, $sessionId);
$this->assertSame(404, $response->getStatusCode());
$this->assertStringContainsString('Session not found', (string) $response->getBody());
}
#[TestDox('a DELETE of an expired session is answered 404')]
public function testDeleteOfAnExpiredSessionIsNotFound(): void
{
$clock = new class implements ClockInterface {
public \DateTimeImmutable $now;
public function now(): \DateTimeImmutable
{
return $this->now;
}
};
$clock->now = new \DateTimeImmutable('2026-10-28 12:00:00');
$server = Server::builder()->setServerInfo('test', '1.0')->setSession(new InMemorySessionStore(60, $clock))->build();
$sessionId = $this->initialize($server);
$clock->now = $clock->now->modify('+61 seconds');
$this->assertSame(404, $this->delete($server, $sessionId)->getStatusCode());
}
#[TestDox('pass-through middleware disables defaults without a warning log')]
public function testPassthroughMiddlewareDisablesDefaultsWithoutWarning(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'evil.example.com')
->withHeader('Origin', 'http://evil.example.com');
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->never())->method('warning');
$transport = new StreamableHttpTransport(
$request,
$this->factory,
$this->factory,
$logger,
[new PassthroughMiddleware()],
);
$response = $transport->listen();
$this->assertNotSame(403, $response->getStatusCode());
$this->assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
}
#[TestDox('explicit empty middleware list disables defaults and emits a warning log')]
public function testEmptyMiddlewareListDisablesDefaultsAndWarns(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'evil.example.com')
->withHeader('Origin', 'http://evil.example.com');
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())
->method('warning')
->with($this->stringContains('empty middleware list'));
$transport = new StreamableHttpTransport(
$request,
$this->factory,
$this->factory,
$logger,
[],
);
$response = $transport->listen();
// No CORS, no DNS rebinding check — transport just answers.
$this->assertNotSame(403, $response->getStatusCode());
$this->assertFalse($response->hasHeader('Access-Control-Allow-Origin'));
$this->assertFalse($response->hasHeader('Access-Control-Allow-Methods'));
}
#[TestDox('a custom middleware list carrying ProtocolVersionMiddleware warns that it will reject the modern era')]
public function testCustomMiddlewareWithProtocolVersionMiddlewareWarns(): void
{
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->once())
->method('warning')
->with($this->stringContains('ProtocolVersionMiddleware'));
new StreamableHttpTransport(
$this->factory->createServerRequest('POST', 'http://localhost/')->withHeader('Host', 'localhost'),
$this->factory,
$this->factory,
$logger,
[new CorsMiddleware(), new DnsRebindingProtectionMiddleware(), new ProtocolVersionMiddleware()],
);
}
#[TestDox('null middleware does not trigger the empty-list warning')]
public function testNullMiddlewareDoesNotWarn(): void
{
$request = $this->factory
->createServerRequest('OPTIONS', 'http://localhost/')
->withHeader('Host', 'localhost');
$logger = $this->createMock(LoggerInterface::class);
$logger->expects($this->never())->method('warning');
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory, $logger);
$transport->listen();
}
#[TestDox('custom middleware composes with default stack via spread')]
public function testDefaultsCanBeSpreadAndExtended(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost');
$transport = new StreamableHttpTransport(
$request,
$this->factory,
$this->factory,
null,
[
...StreamableHttpTransport::defaultMiddleware(),
$this->stubAuth401(),
],
);
$response = $transport->listen();
$this->assertSame(401, $response->getStatusCode());
// CORS middleware is outermost — Expose-Headers is emitted on all responses, including 401.
$this->assertSame('Mcp-Session-Id, WWW-Authenticate, Retry-After', $response->getHeaderLine('Access-Control-Expose-Headers'));
}
#[TestDox('defaults can be filtered to drop DNS rebinding for proxy deployments')]
public function testDefaultsCanBeFilteredToDropDnsRebinding(): void
{
// Behind a reverse proxy: real Host is api.myapp.com, browser Origin is myapp.com.
// DnsRebindingProtectionMiddleware default (localhost-only) would 403 this — drop it.
$request = $this->factory
->createServerRequest('POST', 'http://api.myapp.com/')
->withHeader('Host', 'api.myapp.com')
->withHeader('Origin', 'https://myapp.com');
$transport = new StreamableHttpTransport(
$request,
$this->factory,
$this->factory,
null,
[
...array_filter(
StreamableHttpTransport::defaultMiddleware(),
static fn (MiddlewareInterface $m): bool => !$m instanceof DnsRebindingProtectionMiddleware,
),
$this->stubAuth401(),
],
);
$response = $transport->listen();
// Auth short-circuits with 401 — proves DNS rebinding didn't reject the request first.
$this->assertSame(401, $response->getStatusCode());
// CORS middleware is still in the chain — Expose-Headers attached to the 401.
$this->assertSame('Mcp-Session-Id, WWW-Authenticate, Retry-After', $response->getHeaderLine('Access-Control-Expose-Headers'));
}
#[TestDox('defaults can swap DNS rebinding for wildcard hosts and keep validating Origin behind a proxy')]
public function testDefaultsCanSwapDnsRebindingForWildcardHosts(): void
{
$request = $this->factory
->createServerRequest('POST', 'https://api.myapp.com/')
->withHeader('Origin', 'https://myapp.com');
$middleware = [
...array_map(
static fn (MiddlewareInterface $m): MiddlewareInterface => $m instanceof DnsRebindingProtectionMiddleware
? new DnsRebindingProtectionMiddleware(allowedHosts: ['*'], allowedOrigins: ['https://myapp.com'])
: $m,
StreamableHttpTransport::defaultMiddleware(),
),
$this->stubAuth401(),
];
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory, null, $middleware);
$this->assertSame(401, $transport->listen()->getStatusCode());
$transport = new StreamableHttpTransport($request->withHeader('Origin', 'https://evil.example'), $this->factory, $this->factory, null, $middleware);
$response = $transport->listen();
$this->assertSame(403, $response->getStatusCode());
$this->assertSame('Forbidden: Invalid Origin header.', (string) $response->getBody());
}
#[TestDox('configured CorsMiddleware reflects matching Origin')]
public function testConfiguredCorsReflectsMatchingOrigin(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader('Origin', 'https://myapp.example.com');
$transport = new StreamableHttpTransport(
$request,
$this->factory,
$this->factory,
null,
[
new CorsMiddleware(allowedOrigins: ['https://myapp.example.com']),
new DnsRebindingProtectionMiddleware(allowedHosts: ['localhost'], allowedOrigins: ['https://myapp.example.com']),
new ProtocolVersionMiddleware(),
],
);
$response = $transport->listen();
$this->assertSame('https://myapp.example.com', $response->getHeaderLine('Access-Control-Allow-Origin'));
}
#[TestDox('an allowed Origin does not bypass Host validation')]
public function testAllowedOriginDoesNotBypassHostValidation(): void
{
$request = $this->factory->createServerRequest('POST', 'http://evil.example/')
->withHeader('Origin', 'https://myapp.example.com');
$transport = new StreamableHttpTransport($request, middleware: [
new CorsMiddleware(allowedOrigins: ['https://myapp.example.com']),
new DnsRebindingProtectionMiddleware(allowedOrigins: ['https://myapp.example.com']),
]);
$response = $transport->listen();
$this->assertSame(403, $response->getStatusCode());
$this->assertSame('Forbidden: Invalid Host header.', (string) $response->getBody());
$this->assertSame('https://myapp.example.com', $response->getHeaderLine('Access-Control-Allow-Origin'));
}
#[TestDox('middleware runs before transport handles the request')]
public function testMiddlewareRunsBeforeTransportHandlesRequest(): void
{
$request = $this->factory->createServerRequest('OPTIONS', 'http://localhost/')
->withHeader('Host', 'localhost');
$state = new \stdClass();
$state->called = false;
$spy = new class($state) implements MiddlewareInterface {
public function __construct(private \stdClass $state)
{
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$this->state->called = true;
return $handler->handle($request);
}
};
$transport = new StreamableHttpTransport(
$request,
$this->factory,
$this->factory,
null,
[$spy],
);
$response = $transport->listen();
$this->assertTrue($state->called);
$this->assertSame(204, $response->getStatusCode());
}
#[TestDox('non-middleware entries are rejected')]
public function testInvalidMiddlewareEntryThrows(): void
{
$request = $this->factory->createServerRequest('POST', 'http://localhost/');
$this->expectException(InvalidArgumentException::class);
new StreamableHttpTransport(
$request,
$this->factory,
$this->factory,
null,
[new \stdClass()], // @phpstan-ignore-line argument.type
);
}
public function testPostBodyExceedingMaxBytesReturns413(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withBody($this->factory->createStream(str_repeat('a', 64)));
// Empty middleware bypasses the default security stack to isolate body-size handling.
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory, null, [], maxBodyBytes: 16);
$response = $transport->listen();
$this->assertSame(413, $response->getStatusCode());
}
public function testPostBodyWithinMaxBytesIsNotRejected(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withBody($this->factory->createStream('{}'));
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory, null, [], maxBodyBytes: 1024);
$response = $transport->listen();
$this->assertNotSame(413, $response->getStatusCode());
}
public function testNonPositiveMaxBodyBytesThrows(): void
{
$request = $this->factory->createServerRequest('POST', 'http://localhost/');
$this->expectException(InvalidArgumentException::class);
new StreamableHttpTransport($request, $this->factory, $this->factory, null, [], maxBodyBytes: 0);
}
#[TestDox('an immediate response is consumed once and not replayed on a later POST')]
public function testImmediateResponseIsNotReplayedOnSecondPost(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withBody($this->factory->createStream('{"jsonrpc":"2.0","id":1,"method":"ping"}'));
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
$calls = 0;
$transport->onMessage(static function (TransportInterface $transport, string $payload) use (&$calls): void {
if (1 === ++$calls) {
$transport->send('{"jsonrpc":"2.0","id":1,"result":{}}', ['status_code' => 200]);
}
});
$first = $transport->listen();
$this->assertSame(200, $first->getStatusCode());
$this->assertSame('{"jsonrpc":"2.0","id":1,"result":{}}', (string) $first->getBody());
$second = $transport->listen();
$this->assertSame(2, $calls);
$this->assertSame(202, $second->getStatusCode());
$this->assertSame('', (string) $second->getBody());
}
#[TestDox('the polling loop resumes the fiber with the timeout error the response finder reports')]
public function testPollingLoopResumesFiberWithTimeoutErrorFromResponseFinder(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withBody($this->factory->createStream('{"jsonrpc":"2.0","id":1,"method":"ping"}'));
$transport = new StreamableHttpTransport($request, $this->factory, $this->factory);
$received = null;
$fiber = new \Fiber(static function () use (&$received) {
$received = \Fiber::suspend();
return null;
});
$fiber->start();
$transport->onMessage(static function (TransportInterface $transport) use ($fiber): void {
$transport->attachFiberToSession($fiber, Uuid::v4());
});
$transport->setOutgoingMessagesProvider(static fn (): array => []);
$transport->setResponseFinder(static fn (Uuid $requestId): Error => Error::forInternalError('Request timed out', $requestId->toRfc4122()));
$transport->setPendingRequestsProvider(static fn (): array => [
'00000000-0000-4000-8000-000000000001' => ['request_id' => '00000000-0000-4000-8000-000000000001', 'timestamp' => 1_000_000, 'timeout' => 120],
]);
$response = $transport->listen();
$this->assertSame('text/event-stream', $response->getHeaderLine('Content-Type'));
$this->expectOutputString('');
$response->getBody()->getContents();
$this->assertTrue($fiber->isTerminated());
$this->assertInstanceOf(Error::class, $received);
}
#[TestDox('the polling loop stops once the client has disconnected')]
public function testPollingLoopStopsOnceTheClientHasDisconnected(): void
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withBody($this->factory->createStream('{"jsonrpc":"2.0","id":1,"method":"ping"}'));
$transport = new class($request, $this->factory, $this->factory) extends StreamableHttpTransport {
protected function isConnectionAborted(): bool
{
return true;
}
};
$received = null;
$fiber = new \Fiber(static function () use (&$received) {
$received = \Fiber::suspend();
return null;
});
$fiber->start();
$transport->onMessage(static function (TransportInterface $transport) use ($fiber): void {
$transport->attachFiberToSession($fiber, Uuid::v4());
});
$transport->setOutgoingMessagesProvider(static fn (): array => []);
$transport->setResponseFinder(static fn () => null);
$transport->setPendingRequestsProvider(static fn (): array => [
'00000000-0000-4000-8000-000000000001' => ['request_id' => '00000000-0000-4000-8000-000000000001', 'timestamp' => time(), 'timeout' => 120],
]);
$response = $transport->listen();
$output = '';
ob_start(static function (string $chunk) use (&$output): string {
$output .= $chunk;
return '';
});
try {
$response->getBody()->getContents();
} finally {
ob_end_flush();
}
$this->assertSame(": keep-alive\n\n", $output);
$this->assertTrue($fiber->isSuspended(), 'The abandoned call must not be resumed.');
$this->assertNull($received);
}
/**
* @return iterable<string, array{bool}>
*/
public static function provideInterleavings(): iterable
{
yield 'B runs between A saving its session and A answering' => [false];
yield 'B loaded the session before A saved it (lost update)' => [true];
}
#[TestDox('concurrent POSTs of one session each get their own response: $_dataName')]
#[DataProvider('provideInterleavings')]
public function testConcurrentPostsOfOneSessionEachGetTheirOwnResponse(bool $readBeforeWrite): void
{
$store = new InterleavingSessionStore();
$sessionId = $this->post($store, '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}')
->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
$responseB = null;
$store->interleaveOnNextWrite(function () use ($store, $sessionId, &$responseB): void {
$responseB = $this->post($store, '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"text":"b"}}}', $sessionId);
}, $readBeforeWrite);
$responseA = $this->post($store, '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"echo","arguments":{"text":"a"}}}', $sessionId);
$this->assertInstanceOf(ResponseInterface::class, $responseB);
foreach ([2 => $responseA, 3 => $responseB] as $id => $response) {
$this->assertSame(200, $response->getStatusCode(), \sprintf('Request %d was answered %d.', $id, $response->getStatusCode()));
$this->assertSame($sessionId, $response->getHeaderLine(StreamableHttpTransport::SESSION_HEADER));
$this->assertSame($id, json_decode((string) $response->getBody(), true)['id'] ?? null, \sprintf('Request %d got: %s', $id, $response->getBody()));
}
}
/**
* @return iterable<string, array{string}>
*/
public static function provideBatches(): iterable
{
yield 'requests' => ['[{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"echo","arguments":{"text":"a"}}},{"jsonrpc":"2.0","id":3,"method":"ping"}]'];
yield 'one request' => ['[{"jsonrpc":"2.0","id":2,"method":"ping"}]'];
yield 'empty' => ['[]'];
yield 'notifications' => ['[{"jsonrpc":"2.0","method":"notifications/initialized"}]'];
yield 'initialize' => ['[{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}]'];
}
#[DataProvider('provideBatches')]
#[TestDox('a batch is refused with a 400, also in a session that negotiated 2025-03-26: $_dataName')]
public function testBatchIsRefused(string $batch): void
{
$store = new InterleavingSessionStore();
$sessionId = $this->post($store, '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}')
->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
$response = $this->post($store, $batch, $sessionId);
$this->assertSame(400, $response->getStatusCode());
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
$answer = json_decode((string) $response->getBody(), true);
$this->assertArrayNotHasKey(0, $answer);
$this->assertSame(Error::INVALID_REQUEST, $answer['error']['code']);
$this->assertStringContainsString('batching', $answer['error']['message']);
}
#[TestDox('a request meeting queued notifications is answered as SSE with them first, then its response')]
public function testQueuedNotificationsGoOutOnAStreamBeforeTheResponse(): void
{
$store = new InterleavingSessionStore();
$sessionId = $this->post($store, '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}')
->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
// A notification another request of the session queued, e.g. a resource update.
$session = new Session($store, Uuid::fromString($sessionId));
$session->set('_mcp.outgoing_queue', [[
'message' => '{"jsonrpc":"2.0","method":"notifications/resources/updated","params":{"uri":"file:///a"}}',
'context' => ['type' => 'notification'],
]]);
$session->save();
$response = $this->post($store, '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"echo","arguments":{"text":"a"}}}', $sessionId);
$this->assertSame(200, $response->getStatusCode());
$this->assertSame('text/event-stream', $response->getHeaderLine('Content-Type'));
$this->assertSame($sessionId, $response->getHeaderLine(StreamableHttpTransport::SESSION_HEADER));
preg_match_all('/^data: (.+)$/m', (string) $response->getBody(), $matches);
$messages = array_map(static fn (string $data): array => json_decode($data, true), $matches[1]);
$this->assertSame(
['notifications/resources/updated', 2],
array_map(static fn (array $message): string|int => $message['method'] ?? $message['id'], $messages),
);
$this->assertSame([], (new Session($store, Uuid::fromString($sessionId)))->get('_mcp.outgoing_queue'));
}
#[TestDox('a request answered as JSON carries its response alone, a single object')]
public function testJsonAnswerIsTheResponseAlone(): void
{
$store = new InterleavingSessionStore();
$sessionId = $this->post($store, '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}')
->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
$response = $this->post($store, '{"jsonrpc":"2.0","id":2,"method":"ping"}', $sessionId);
$this->assertSame('application/json', $response->getHeaderLine('Content-Type'));
$this->assertSame(['jsonrpc' => '2.0', 'id' => 2, 'result' => []], json_decode((string) $response->getBody(), true));
}
#[TestDox('with a session lock, a POST arriving while another of the session runs is held off instead of overwriting it')]
public function testSessionLockHoldsOffAConcurrentPostOfTheSameSession(): void
{
$store = new InterleavingSessionStore();
$sessionId = $this->post($store, '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}', lock: $this->fileLock())
->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
// B loads the session before A saved it, the lost update: on its own worker, with its own lock instance.
$responseB = null;
$store->interleaveOnNextWrite(function () use ($store, $sessionId, &$responseB): void {
$responseB = $this->post($store, '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"echo","arguments":{"text":"b"}}}', $sessionId, $this->fileLock());
}, readBeforeWrite: true);
$responseA = $this->post($store, '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"echo","arguments":{"text":"a"}}}', $sessionId, $this->fileLock());
$this->assertSame(200, $responseA->getStatusCode());
$this->assertSame(2, json_decode((string) $responseA->getBody(), true)['id'] ?? null);
$this->assertInstanceOf(ResponseInterface::class, $responseB);
$this->assertSame(503, $responseB->getStatusCode());
$error = json_decode((string) $responseB->getBody(), true);
$this->assertSame(3, $error['id'] ?? null);
$this->assertSame(Error::SERVER_ERROR, $error['error']['code'] ?? null);
}
#[TestDox('the session lock is released while a handler waits for the client, so the next request of the session proceeds')]
public function testSessionLockIsReleasedWhileAHandlerWaitsForTheClient(): void
{
$store = new InterleavingSessionStore();
$lock = $this->fileLock();
$sessionId = $this->post($store, '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}', lock: $lock)
->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
$first = $this->post($store, '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ask","arguments":{}}}', $sessionId, $lock);
$second = $this->post($store, '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"ask","arguments":{}}}', $sessionId, $lock);
$this->assertSame('text/event-stream', $first->getHeaderLine('Content-Type'));
$this->assertSame('text/event-stream', $second->getHeaderLine('Content-Type'));
// Both requests to the client were stored, each under its own id.
$session = new Session($store, Uuid::fromString($sessionId));
$this->assertCount(2, $session->get('_mcp.pending_requests'));
}
#[TestDox('a message a resumed handler cannot store fails in the handler instead of resuming it with nothing')]
public function testMessageThatCannotBeStoredFailsInTheHandler(): void
{
$store = new InterleavingSessionStore();
$lock = new HeldElsewhereSessionLock($this->fileLock());
$sessionId = $this->post($store, '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}', lock: $lock)
->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
$stream = $this->post($store, '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"ask-then-notify","arguments":{}}}', $sessionId, $lock);
$this->assertSame('text/event-stream', $stream->getHeaderLine('Content-Type'));
// The client answers the first request on a POST of its own, then another worker holds the
// session past the timeout, so what the resumed handler sends next cannot be stored.
$pendingRequestIds = array_keys((new Session($store, Uuid::fromString($sessionId)))->get('_mcp.pending_requests'));
$answer = $this->post($store, \sprintf('{"jsonrpc":"2.0","id":%s,"result":{}}', json_encode($pendingRequestIds[0])), $sessionId, $this->fileLock());
$this->assertLessThan(300, $answer->getStatusCode());
$lock->heldElsewhere = true;
$output = $this->readStream($stream);
$this->assertMatchesRegularExpression('/"id":2,"result".*first: ok, second: Failed to send the message to the client\., notify: Failed to send the message to the client\./s', $output);
$this->assertStringNotContainsString('"error"', $output);
}
/**
* @return iterable<string, array{string}>
*/
public static function providePostsWithoutRequest(): iterable
{
yield 'client response' => ['{"jsonrpc":"2.0","id":"7","result":{}}'];
yield 'notification' => ['{"jsonrpc":"2.0","method":"notifications/roots/list_changed"}'];
}
#[DataProvider('providePostsWithoutRequest')]
#[TestDox('a POST without a request is accepted with 202 and no body, and leaves the queued messages in place')]
public function testPostWithoutRequestDoesNotDrainTheOutgoingQueue(string $body): void
{
$store = new InterleavingSessionStore();
$sessionId = $this->post($store, '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}')
->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
$queued = [[
'message' => '{"jsonrpc":"2.0","method":"notifications/resources/updated","params":{"uri":"file:///a"}}',
'context' => ['type' => 'notification'],
]];
$session = new Session($store, Uuid::fromString($sessionId));
$session->set('_mcp.outgoing_queue', $queued);
$session->save();
$response = $this->post($store, $body, $sessionId);
$this->assertSame(202, $response->getStatusCode());
$this->assertSame('', (string) $response->getBody());
$session = new Session($store, Uuid::fromString($sessionId));
$this->assertSame($queued, $session->get('_mcp.outgoing_queue'));
}
/**
* @return iterable<string, array{string, ?string, bool}>
*/
public static function provideInitializeVersionHeaders(): iterable
{
foreach (['without sessions' => false, 'with sessions' => true] as $mode => $withSession) {
yield 'an older header, '.$mode => [ProtocolVersion::V2025_11_25->value, ProtocolVersion::V2025_03_26->value, $withSession];
yield 'a newer header, '.$mode => [ProtocolVersion::V2025_03_26->value, ProtocolVersion::V2025_11_25->value, $withSession];
yield 'no header, '.$mode => [ProtocolVersion::V2025_11_25->value, null, $withSession];
}
}
#[DataProvider('provideInitializeVersionHeaders')]
#[TestDox('initialize negotiates the body version given $_dataName')]
public function testInitializeNegotiatesTheBodyVersion(string $bodyVersion, ?string $headerVersion, bool $withSession): void
{
$store = new InMemorySessionStore();
$builder = Server::builder()->setServerInfo('test', '1.0');
if ($withSession) {
$builder->setSession($store);
}
$response = $builder->build()->run(new StreamableHttpTransport($this->initializeRequest($bodyVersion, $headerVersion), $this->factory, $this->factory));
$this->assertSame(200, $response->getStatusCode());
$this->assertSame($bodyVersion, json_decode((string) $response->getBody(), true)['result']['protocolVersion'] ?? null);
if ($withSession) {
$sessionId = $response->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
$this->assertNotSame('', $sessionId);
$session = new Session($store, Uuid::fromString($sessionId));
$this->assertSame($bodyVersion, $session->get('protocol_version'));
}
}
/**
* Sends one POST to a fresh server sharing $store, like a PHP worker would.
*/
private function post(InterleavingSessionStore $store, string $body, string $sessionId = '', ?SessionLockInterface $lock = null): ResponseInterface
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader('Content-Type', 'application/json')
->withHeader('Accept', 'application/json, text/event-stream')
->withBody($this->factory->createStream($body));
if ('' !== $sessionId) {
$request = $request
->withHeader(StreamableHttpTransport::SESSION_HEADER, $sessionId)
->withHeader(StreamableHttpTransport::PROTOCOL_VERSION_HEADER, '2025-06-18');
}
$builder = Server::builder()
->setServerInfo('test', '1.0')
->setSession($store)
->addTool(static fn (string $text): string => $text, 'echo')
->addTool(static function (RequestContext $context): string {
$context->getClientGateway()->progress(0.5);
return 'done';
}, 'progress')
->addTool(static function (RequestContext $context): string {
// Suspends on a request to the client, as elicitation and sampling do.
\Fiber::suspend(new RequestSuspension(new PingRequest(), $context->getSession()->getId()->toRfc4122(), 5));
return 'done';
}, 'ask')
->addTool(static function (RequestContext $context): string {
$gateway = $context->getClientGateway();
$first = $gateway->request(new PingRequest(), 5);
$second = $gateway->request(new PingRequest(), 5);
try {
$gateway->notify(new ProgressNotification('p', 0.5));
$notified = 'ok';
} catch (ClientException $e) {
$notified = $e->getMessage();
}
return \sprintf(
'first: %s, second: %s, notify: %s',
$first instanceof Error ? $first->message : 'ok',
$second instanceof Error ? $second->message : 'ok',
$notified,
);
}, 'ask-then-notify');
if (null !== $lock) {
$builder->setSessionLock($lock);
}
return $builder->build()->run(new StreamableHttpTransport($request, $this->factory, $this->factory));
}
/**
* Opens a session on $server and returns its id.
*/
private function initialize(Server $server): string
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader('Content-Type', 'application/json')
->withHeader('Accept', 'application/json, text/event-stream')
->withBody($this->factory->createStream('{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}'));
return $server->run(new StreamableHttpTransport($request, $this->factory, $this->factory))->getHeaderLine(StreamableHttpTransport::SESSION_HEADER);
}
private function initializeRequest(string $bodyVersion, ?string $headerVersion): ServerRequestInterface
{
$request = $this->factory
->createServerRequest('POST', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader('Content-Type', 'application/json')
->withHeader('Accept', 'application/json, text/event-stream')
->withBody($this->factory->createStream(\sprintf('{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"%s","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}', $bodyVersion)));
if (null === $headerVersion) {
return $request;
}
return $request->withHeader(StreamableHttpTransport::PROTOCOL_VERSION_HEADER, $headerVersion);
}
private function delete(Server $server, string $sessionId): ResponseInterface
{
$request = $this->factory
->createServerRequest('DELETE', 'http://localhost/')
->withHeader('Host', 'localhost')
->withHeader(StreamableHttpTransport::SESSION_HEADER, $sessionId);
return $server->run(new StreamableHttpTransport($request, $this->factory, $this->factory));
}
/**
* Reads an SSE response; the stream calls ob_flush() itself, so the output is captured by a handler, not a plain buffer.
*/
private function readStream(ResponseInterface $response): string
{
$output = '';
ob_start(static function (string $chunk) use (&$output): string {
$output .= $chunk;
return '';
});
try {
$response->getBody()->getContents();
} finally {
ob_end_flush();
}
return $output;
}
/**
* A lock instance of its own, as each worker has, over one shared directory.
*/
private function fileLock(): FileSessionLock
{
$this->lockDirectory ??= sys_get_temp_dir().'/mcp-session-lock-'.bin2hex(random_bytes(6));
return new FileSessionLock($this->lockDirectory, timeout: 0.05);
}
private function stubAuth401(): MiddlewareInterface
{
return new class($this->factory) implements MiddlewareInterface {
public function __construct(private ResponseFactoryInterface $factory)
{
}
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
return $this->factory->createResponse(401);
}
};
}
}