Skip to content

Commit 4192b5f

Browse files
committed
[Tests] Cover requestState binding and key rotation end to end
1 parent a0e195b commit 4192b5f

10 files changed

Lines changed: 1021 additions & 0 deletions
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the official PHP MCP SDK.
5+
*
6+
* A collaboration between Symfony and the PHP Foundation.
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
/*
13+
* Server for the `requestState` tests, over `php -S` or stdio. MCP_REQUEST_STATE_KEYS holds the JSON-encoded key or
14+
* key ring, MCP_REQUEST_STATE_BINDER turns on the binder, MCP_REQUEST_STATE_ANONYMOUS drops the authorization.
15+
*/
16+
17+
use Http\Discovery\Psr17Factory;
18+
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
19+
use Mcp\Schema\Content\TextContent;
20+
use Mcp\Schema\Elicitation\ElicitationSchema;
21+
use Mcp\Schema\Elicitation\StringSchemaDefinition;
22+
use Mcp\Schema\Request\ElicitRequest;
23+
use Mcp\Schema\Result\CallToolResult;
24+
use Mcp\Schema\Result\InputRequiredResult;
25+
use Mcp\Server;
26+
use Mcp\Server\Authorization\AccessToken;
27+
use Mcp\Server\RequestContext;
28+
use Mcp\Server\Stateless\OriginatingRequestBinder;
29+
use Mcp\Server\Transport\Http\Middleware\AuthorizationMiddleware;
30+
use Mcp\Server\Transport\Http\Middleware\PassthroughMiddleware;
31+
use Mcp\Server\Transport\Http\OAuth\AuthorizationResult;
32+
use Mcp\Server\Transport\Http\OAuth\AuthorizationTokenValidatorInterface;
33+
use Mcp\Server\Transport\Http\OAuth\ProtectedResourceMetadata;
34+
use Mcp\Server\Transport\StdioTransport;
35+
use Mcp\Server\Transport\StreamableHttpTransport;
36+
37+
require_once dirname(__DIR__, 3).'/vendor/autoload.php';
38+
39+
$subject = static fn (RequestContext $context): string => $context->getAccessToken()?->getSubject() ?? 'nobody';
40+
41+
// Two asks, so the second one has to carry the first answer in the state the SDK mints.
42+
$approver = static function (RequestContext $context): string {
43+
$gateway = $context->getClientGateway();
44+
$schema = new ElicitationSchema(['v' => new StringSchemaDefinition('Value')], ['v']);
45+
46+
$approver = $gateway->elicit('Who approves this?', $schema, key: 'approver')->content['v'] ?? '?';
47+
$gateway->elicit('One-time code?', $schema, key: 'code');
48+
49+
return (string) $approver;
50+
};
51+
52+
$builder = Server::builder()
53+
->setServerInfo('request-state-server', '1.0.0')
54+
->addTool(
55+
static fn (RequestContext $context, string $to, int $amount): string => sprintf('%s moved %d to %s, approved by %s', $subject($context), $amount, $to, $approver($context)),
56+
name: 'transfer',
57+
description: 'Moves money after two asks.',
58+
)
59+
->addTool(
60+
static fn (RequestContext $context, string $account): string => sprintf('%s closed %s, approved by %s', $subject($context), $account, $approver($context)),
61+
name: 'close_account',
62+
description: 'Closes an account after the same two asks.',
63+
)
64+
->addTool(
65+
// Authorizes once and trusts its own signed state on the retry, the reason the state needs integrity at all.
66+
static function (RequestContext $context, int $order) use ($subject): CallToolResult|InputRequiredResult {
67+
if (true === ($context->getInputContext()?->requestState()['authorized'] ?? null)) {
68+
return new CallToolResult([new TextContent(sprintf('%s refunded order %d', $subject($context), $order))]);
69+
}
70+
71+
if (!in_array($subject($context), ['alice', 'nobody'], true)) {
72+
return new CallToolResult([new TextContent('Only a manager may refund.')], isError: true);
73+
}
74+
75+
return new InputRequiredResult(
76+
['reason' => new ElicitRequest('Why?', new ElicitationSchema(['v' => new StringSchemaDefinition('Value')], ['v']))],
77+
requestState: $context->mintRequestState(['authorized' => true]),
78+
);
79+
},
80+
name: 'refund',
81+
description: 'Refunds an order, for managers only.',
82+
)
83+
->addResourceTemplate(
84+
static fn (string $id, RequestContext $context): string => sprintf('contents of %s, approved by %s', $id, $approver($context)),
85+
'doc://{id}',
86+
name: 'doc',
87+
mimeType: 'text/plain',
88+
)
89+
->addTool(static fn (): string => 'pong', name: 'ping', description: 'Asks nothing.');
90+
91+
$keys = json_decode((string) getenv('MCP_REQUEST_STATE_KEYS'), true, flags: \JSON_THROW_ON_ERROR);
92+
93+
if ('' !== (string) getenv('MCP_REQUEST_STATE_BINDER')) {
94+
$builder->setRequestState($keys, binder: new OriginatingRequestBinder());
95+
} else {
96+
$builder->setRequestState($keys);
97+
}
98+
99+
if ('cli-server' !== \PHP_SAPI) {
100+
$builder->build()->run(new StdioTransport());
101+
102+
return;
103+
}
104+
105+
$middleware = [new PassthroughMiddleware()];
106+
107+
if ('' === (string) getenv('MCP_REQUEST_STATE_ANONYMOUS')) {
108+
$middleware = [new AuthorizationMiddleware(
109+
new class implements AuthorizationTokenValidatorInterface {
110+
private const ISSUER = 'https://auth.example.com';
111+
112+
public function validate(string $accessToken): AuthorizationResult
113+
{
114+
$claims = match ($accessToken) {
115+
'alice' => ['sub' => 'alice', 'client_id' => 'app', 'jti' => 'first'],
116+
'alice-refreshed' => ['sub' => 'alice', 'client_id' => 'app', 'jti' => 'second'],
117+
'alice-other-client' => ['sub' => 'alice', 'client_id' => 'other-app', 'jti' => 'third'],
118+
'mallory' => ['sub' => 'mallory', 'client_id' => 'app', 'jti' => 'fourth'],
119+
'no-subject-alice' => ['client_id' => 'app', 'email' => 'alice@example.com'],
120+
'no-subject-mallory' => ['client_id' => 'app', 'email' => 'mallory@example.com'],
121+
default => null,
122+
};
123+
124+
if (null === $claims) {
125+
return AuthorizationResult::unauthorized();
126+
}
127+
128+
return AuthorizationResult::allow(new AccessToken(['mcp'], ['iss' => self::ISSUER, ...$claims]));
129+
}
130+
},
131+
new ProtectedResourceMetadata('http://127.0.0.1/', ['http://127.0.0.1/']),
132+
)];
133+
}
134+
135+
$request = (new Psr17Factory())->createServerRequestFromGlobals();
136+
137+
(new SapiEmitter())->emit($builder->build()->run(new StreamableHttpTransport($request, middleware: $middleware)));
Lines changed: 226 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,226 @@
1+
<?php
2+
3+
/*
4+
* This file is part of the official PHP MCP SDK.
5+
*
6+
* A collaboration between Symfony and the PHP Foundation.
7+
*
8+
* For the full copyright and license information, please view the LICENSE
9+
* file that was distributed with this source code.
10+
*/
11+
12+
namespace Mcp\Tests\Integration;
13+
14+
use Mcp\Client;
15+
use Mcp\Client\Handler\Request\RequestHandlerInterface;
16+
use Mcp\Client\Transport\StdioTransport;
17+
use Mcp\Schema\ClientCapabilities;
18+
use Mcp\Schema\Enum\ElicitAction;
19+
use Mcp\Schema\Enum\ProtocolVersion;
20+
use Mcp\Schema\JsonRpc\Request;
21+
use Mcp\Schema\JsonRpc\Response;
22+
use Mcp\Schema\Request\ElicitRequest;
23+
use Mcp\Schema\Result\ElicitResult;
24+
use PHPUnit\Framework\Attributes\DataProvider;
25+
use PHPUnit\Framework\Attributes\TestDox;
26+
27+
/**
28+
* What a client can do with a state it holds: every replay below succeeds without a binder, and none does with one.
29+
*
30+
* @phpstan-import-type Call from RequestStateTestCase
31+
*/
32+
final class RequestStateBindingTest extends RequestStateTestCase
33+
{
34+
/**
35+
* @return iterable<string, array{string, Call, string, Call, string}>
36+
*/
37+
public static function provideReplays(): iterable
38+
{
39+
$transfer = self::tool('transfer', ['to' => 'bob', 'amount' => 10]);
40+
41+
yield 'alice\'s approval under mallory\'s token' => [
42+
'alice', $transfer,
43+
'mallory', $transfer,
44+
'mallory moved 10 to bob, approved by alice',
45+
];
46+
yield 'alice\'s approval under a token of another client' => [
47+
'alice', $transfer,
48+
'alice-other-client', $transfer,
49+
'alice moved 10 to bob, approved by alice',
50+
];
51+
yield 'an approval of 10 for bob on a transfer of 10000 to mallory' => [
52+
'alice', $transfer,
53+
'alice', self::tool('transfer', ['to' => 'mallory', 'amount' => 10000]),
54+
'alice moved 10000 to mallory, approved by alice',
55+
];
56+
yield 'an approval of a transfer on closing the account' => [
57+
'alice', $transfer,
58+
'alice', self::tool('close_account', ['account' => 'savings']),
59+
'alice closed savings, approved by alice',
60+
];
61+
yield 'an approval to read one document on reading another' => [
62+
'alice', self::resource('doc://public'),
63+
'alice', self::resource('doc://secret'),
64+
'contents of secret, approved by alice',
65+
];
66+
yield 'a manager\'s authorization check under mallory\'s token' => [
67+
'alice', self::tool('refund', ['order' => 1]),
68+
'mallory', self::tool('refund', ['order' => 1]),
69+
'mallory refunded order 1',
70+
];
71+
yield 'a manager\'s authorization check on another order' => [
72+
'alice', self::tool('refund', ['order' => 1]),
73+
'alice', self::tool('refund', ['order' => 2]),
74+
'alice refunded order 2',
75+
];
76+
yield 'tokens telling their users apart by a claim other than the subject' => [
77+
'no-subject-alice', $transfer,
78+
'no-subject-mallory', $transfer,
79+
'nobody moved 10 to bob, approved by no-subject-alice',
80+
];
81+
}
82+
83+
/**
84+
* @param Call $minted
85+
* @param Call $replayed
86+
*/
87+
#[DataProvider('provideReplays')]
88+
#[TestDox('without a binder, a client gets away with $_dataName')]
89+
public function testReplaySucceedsWithoutABinder(string $holder, array $minted, string $replayer, array $replayed, string $outcome): void
90+
{
91+
$url = $this->startServer(self::NEW_KEY);
92+
93+
$this->assertCompleted($this->finish($url, $replayer, $replayed, $this->pendingState($url, $holder, $minted)), $outcome);
94+
}
95+
96+
/**
97+
* @param Call $minted
98+
* @param Call $replayed
99+
*/
100+
#[DataProvider('provideReplays')]
101+
#[TestDox('with a binder, a client is refused $_dataName')]
102+
public function testReplayIsRefusedWithABinder(string $holder, array $minted, string $replayer, array $replayed, string $outcome): void
103+
{
104+
$url = $this->startServer(self::NEW_KEY, binder: true);
105+
106+
$this->assertRefused($this->finish($url, $replayer, $replayed, $this->pendingState($url, $holder, $minted)));
107+
}
108+
109+
#[TestDox('a manager\'s check still stops mallory from starting a refund, whatever the binder')]
110+
public function testHandlerStillDecidesTheFirstRound(): void
111+
{
112+
$url = $this->startServer(self::NEW_KEY, binder: true);
113+
114+
$this->assertCompleted($this->send($url, 'mallory', self::tool('refund', ['order' => 1])), 'Only a manager may refund.');
115+
}
116+
117+
#[TestDox('with a binder, the retry of a call completes under a refreshed token')]
118+
public function testRetryCompletesUnderARefreshedToken(): void
119+
{
120+
$url = $this->startServer(self::NEW_KEY, binder: true);
121+
$call = self::tool('transfer', ['to' => 'bob', 'amount' => 10]);
122+
123+
$this->assertCompleted(
124+
$this->finish($url, 'alice-refreshed', $call, $this->pendingState($url, 'alice', $call)),
125+
'alice moved 10 to bob, approved by alice',
126+
);
127+
}
128+
129+
#[TestDox('with a binder, the retry of a call completes with its arguments re-encoded, another id and other metadata')]
130+
public function testRetryCompletesWhenOnlyItsEnvelopeChanged(): void
131+
{
132+
$url = $this->startServer(self::NEW_KEY, binder: true);
133+
$pending = $this->pendingState($url, 'alice', self::tool('transfer', ['to' => 'bob', 'amount' => 10]));
134+
135+
$answer = $this->send($url, 'alice', self::tool('transfer', ['amount' => 10, 'to' => 'bob']), [
136+
'inputResponses' => [$pending['asks'][0] => ['action' => 'accept', 'content' => ['v' => 'alice']]],
137+
'requestState' => $pending['state'],
138+
], ['progressToken' => 'another-round', 'traceparent' => '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01'], id: 99);
139+
140+
$this->assertCompleted($answer, 'alice moved 10 to bob, approved by alice');
141+
}
142+
143+
#[TestDox('with a binder, a token without a subject cannot finish a call that needs a state, but everything else still works')]
144+
public function testTokenWithoutASubjectFailsClosed(): void
145+
{
146+
$url = $this->startServer(self::NEW_KEY, binder: true);
147+
$call = self::tool('transfer', ['to' => 'bob', 'amount' => 10]);
148+
149+
$this->assertRefused($this->finish($url, 'no-subject-alice', $call, $this->pendingState($url, 'no-subject-alice', $call)));
150+
$this->assertCompleted($this->send($url, 'no-subject-alice', self::tool('ping')), 'pong');
151+
}
152+
153+
#[TestDox('with a binder, an endpoint without authorization still binds the call')]
154+
public function testAnonymousEndpointBindsTheCall(): void
155+
{
156+
$url = $this->startServer(self::NEW_KEY, binder: true, anonymous: true);
157+
$call = self::tool('transfer', ['to' => 'bob', 'amount' => 10]);
158+
$pending = $this->pendingState($url, null, $call);
159+
160+
$this->assertCompleted($this->finish($url, null, $call, $pending), 'nobody moved 10 to bob, approved by ');
161+
$this->assertRefused($this->finish($url, null, self::tool('transfer', ['to' => 'mallory', 'amount' => 10]), $pending));
162+
}
163+
164+
#[TestDox('with a binder, the principal stays off the wire')]
165+
public function testPrincipalStaysOffTheWire(): void
166+
{
167+
$url = $this->startServer(self::NEW_KEY, binder: true);
168+
$state = $this->pendingState($url, 'alice', self::tool('refund', ['order' => 1]))['state'];
169+
170+
$this->assertCount(2, explode('.', $state));
171+
$this->assertSame(
172+
['authorized' => true],
173+
json_decode((string) base64_decode(strtr(explode('.', $state)[0], '-_', '+/'), true), true)['data'] ?? null,
174+
);
175+
}
176+
177+
#[TestDox('with a binder, our own client completes the calls that take several rounds')]
178+
public function testOwnClientCompletesThroughTheBinder(): void
179+
{
180+
$client = $this->client([$this->startServer(self::NEW_KEY, binder: true)], 'alice');
181+
182+
$this->assertSame('alice moved 10 to bob, approved by client', self::text($client->callTool('transfer', ['to' => 'bob', 'amount' => 10])));
183+
$this->assertSame('alice refunded order 1', self::text($client->callTool('refund', ['order' => 1])));
184+
185+
$client->disconnect();
186+
}
187+
188+
/**
189+
* @return iterable<string, array{ProtocolVersion}>
190+
*/
191+
public static function provideEras(): iterable
192+
{
193+
yield 'the modern era' => [ProtocolVersion::V2026_07_28];
194+
yield 'the handshake era' => [ProtocolVersion::V2025_11_25];
195+
}
196+
197+
#[DataProvider('provideEras')]
198+
#[TestDox('with a binder, a client completes the calls that take several rounds over stdio on $_dataName')]
199+
public function testStdioCompletesThroughTheBinder(ProtocolVersion $era): void
200+
{
201+
$client = Client::builder()
202+
->setClientInfo('request-state-client', '1.0.0')
203+
->setProtocolVersion($era)
204+
->setCapabilities(new ClientCapabilities(elicitation: true))
205+
->setRequestTimeout(10)
206+
->addRequestHandler(new class implements RequestHandlerInterface {
207+
public function supports(Request $request): bool
208+
{
209+
return $request instanceof ElicitRequest;
210+
}
211+
212+
public function handle(Request $request): Response
213+
{
214+
return new Response($request->getId(), new ElicitResult(ElicitAction::Accept, ['v' => 'client']));
215+
}
216+
})
217+
->build();
218+
219+
$client->connect(new StdioTransport('php', [__DIR__.'/Fixture/request_state.php'], env: array_merge(getenv(), self::environment(self::NEW_KEY, binder: true))));
220+
221+
$this->assertSame('nobody moved 10 to bob, approved by client', self::text($client->callTool('transfer', ['to' => 'bob', 'amount' => 10])));
222+
$this->assertSame('nobody refunded order 1', self::text($client->callTool('refund', ['order' => 1])));
223+
224+
$client->disconnect();
225+
}
226+
}

0 commit comments

Comments
 (0)