Skip to content

Commit 24360c3

Browse files
BrocksiNetchr-hertel
authored andcommitted
[Server] Rotate the requestState signing key with a key ring
Builder::setRequestState() and RequestStateCodec take a list of keys: the first key signs, every key verifies, so an operator can put a new key in front and drop the old one once the states it signed expired, without failing the multi round-trip calls in flight. A state names no key: verification tries each key of the ring, so the wire format is unchanged and instances of an older release still verify the states a ring signs. A single key works as before.
1 parent 7a69dd9 commit 24360c3

7 files changed

Lines changed: 192 additions & 19 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ All notable changes to `mcp/sdk` will be documented in this file.
2828
* Fix a `subscriptions/listen` stream that can carry nothing (the server announces none of the requested types, or the client asks for none) being held open for the full subscription lifetime: it is acknowledged with an empty `notifications` filter and closed gracefully right away, instead of pinning a PHP-FPM worker. Adds `NotificationFilter::isEmpty()`.
2929
* [BC Break] Answer `server/discover` with `DiscoverHandler`, which a handler added through `Builder::addRequestHandler()` can replace, and dispatch `RequestEvent`, `ResponseEvent` and `ErrorEvent` for it. A `StatelessProtocol` built without the `Builder` needs `DiscoverHandler` and a `MessageFactory` with `DiscoverRequest` to answer it.
3030
* Add a `binder` argument to `Builder::setRequestState()` binding the modern era's `requestState` to the request it was minted for, as the 2026-07-28 specification recommends: the binder's value is covered by the state's MAC, and a state echoed on a request that binds to another value is refused like a forged one. `OriginatingRequestBinder` binds the authenticated principal, the method, the tool, prompt or resource, and a digest of the arguments; a token without a subject fails closed, and a `subject` resolver identifies users by another claim. `RequestStateBinderInterface` takes custom bindings. Without a binder, nothing changes.
31+
* Rotate the `requestState` signing key without failing the calls in flight: `Builder::setRequestState()` and `RequestStateCodec` take a list of keys, the first signing and every key verifying. The wire format is unchanged, and a single key works as before.
3132

3233
### Client
3334

‎docs/handlers/input-required.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,26 @@ it and its `AccessToken`. Bind only what stays the same across the rounds of one
142142
States minted before the binder was configured no longer verify, so turning it on fails the
143143
calls in flight for at most one TTL.
144144

145+
### Rotating the key
146+
147+
Pass a list of keys instead of one, and the first key signs while every key verifies:
148+
149+
```php
150+
->setRequestState([$_ENV['MCP_REQUEST_STATE_KEY'], $_ENV['MCP_REQUEST_STATE_KEY_PREVIOUS']], ttl: 600)
151+
```
152+
153+
A state names no key, so the wire format does not change and a single key is a ring of one.
154+
To rotate without failing the calls in flight:
155+
156+
1. Add the new key **behind** the current one, `[$current, $new]`, and deploy it to every
157+
process. They still sign with the current key but already accept the new one.
158+
A single-process deployment can skip this step.
159+
2. Move the new key to the front, `[$new, $current]`. States are signed with the new key from
160+
now on, and the ones the old key signed still verify.
161+
3. After one TTL, every state the old key signed has expired. Remove it, `[$new]`.
162+
163+
Each key needs at least 32 bytes.
164+
145165
## Capabilities
146166

147167
A server must not ask for input the client cannot provide. The SDK checks each ask against

‎docs/run/server-builder.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ $server = Server::builder()
117117
// Signs the state a multi round-trip request carries through the client.
118118
// The same key must reach every process that might serve the retry.
119119
// The key needs at least 32 bytes, otherwise build() throws. TTL in seconds, default 600.
120+
// A list of keys rotates them: the first signs, every key verifies.
120121
// Without a key, the server refuses every state the client sends back.
121122
// The optional binder ties each state to the principal and the call it was
122123
// minted for, so a client cannot echo it on another call or under another token.
@@ -336,7 +337,7 @@ $server = Server::builder()
336337
| `setProtocolVersion()` | protocolVersion | Pin the handshake to one protocol revision |
337338
| `setModernVersions()` | versions | Narrow the revisions the modern (2026-07-28) leg answers for |
338339
| `withoutModernEra()` | - | Serve the handshake era only |
339-
| `setRequestState()` | key, ttl?, binder? | Signing key, lifetime and optional binding to the originating request for multi round-trip request state |
340+
| `setRequestState()` | key, ttl?, binder? | Signing key (or key ring, the first key signing), lifetime and optional binding to the originating request for multi round-trip request state |
340341
| `setInputRequiredLimits()` | maxRounds, roundTimeout | Bound the input-required shim on handshake-era connections |
341342
| `withoutInputRequiredShim()` | - | Do not fulfil an `InputRequiredResult` over a handshake-era connection |
342343
| `setCachePolicy()` | policy | Set the `ttlMs`/`cacheScope` hints on cacheable results |

‎src/Server/Builder.php‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,8 @@ final class Builder
145145
/** @var list<class-string<\Mcp\Schema\JsonRpc\Request>|class-string<\Mcp\Schema\JsonRpc\Notification>> */
146146
private array $extensionMessages = [];
147147

148-
private ?string $requestStateKey = null;
148+
/** @var string|list<string>|null */
149+
private string|array|null $requestStateKey = null;
149150

150151
private int $requestStateTtl = 600;
151152

@@ -381,18 +382,22 @@ public function setCachePolicy(CachePolicy $policy): self
381382
* The same key must reach every instance that might serve the retry, so a
382383
* per-process random value only works for a single-process deployment.
383384
*
385+
* A list of keys is a key ring: the first key signs, every key verifies.
386+
* To rotate, put the new key first and keep the old one behind it until
387+
* the states it signed have expired, one TTL later.
388+
*
384389
* A binder ties every state the modern era mints to the request it was
385390
* minted for, e.g. {@see Stateless\OriginatingRequestBinder} to the
386391
* principal, method and arguments: a state echoed on a request that binds
387392
* to another value fails verification like a forged one. States minted
388393
* before a binder was configured no longer verify, so adding one fails the
389394
* multi round-trip calls in flight for at most the TTL.
390395
*
391-
* @param string $key at least 32 bytes
396+
* @param string|list<string> $key the signing key or key ring, each key at least 32 bytes
392397
* @param int $ttl how long a minted state stays valid, in seconds
393398
* @param RequestStateBinderInterface|null $binder binds each state to its originating request
394399
*/
395-
public function setRequestState(string $key, int $ttl = 600, ?RequestStateBinderInterface $binder = null): self
400+
public function setRequestState(string|array $key, int $ttl = 600, ?RequestStateBinderInterface $binder = null): self
396401
{
397402
$this->requestStateKey = $key;
398403
$this->requestStateTtl = $ttl;

‎src/Server/Stateless/RequestStateCodec.php‎

Lines changed: 51 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@
2323
* {@see self::verify()} refuses anything whose MAC or expiry does not hold.
2424
* Signed, not encrypted: nothing secret belongs in the payload.
2525
*
26+
* Takes one key or a key ring to rotate without failing the calls in flight:
27+
* the first key signs, every key verifies. The value names no key, so the
28+
* wire format does not change.
29+
*
2630
* A codec {@see self::withBinding() bound} to a value also covers that value
2731
* with the MAC, without putting it on the wire: a state minted under one
2832
* binding fails verification under any other, and so does a state minted
@@ -37,28 +41,50 @@ final class RequestStateCodec
3741

3842
private const ALGORITHM = 'sha256';
3943

44+
/** @var non-empty-list<string> */
45+
private readonly array $keys;
46+
47+
/**
48+
* @param string|list<string> $key the signing key, or a key ring whose first key signs and whose every key verifies
49+
*/
4050
public function __construct(
41-
private readonly string $key,
51+
string|array $key,
4252
private readonly int $ttlSeconds = 600,
4353
private readonly ?string $binding = null,
4454
) {
45-
if (\strlen($this->key) < self::MINIMUM_KEY_BYTES) {
46-
throw new InvalidArgumentException(\sprintf('The requestState signing key must be at least %d bytes, got %d.', self::MINIMUM_KEY_BYTES, \strlen($this->key)));
55+
$keys = \is_string($key) ? [$key] : $key;
56+
57+
if ([] === $keys || !array_is_list($keys)) {
58+
throw new InvalidArgumentException('The requestState key ring must be a non-empty list of keys.');
59+
}
60+
61+
foreach ($keys as $i => $candidate) {
62+
$name = \is_string($key) ? 'The requestState signing key' : \sprintf('The requestState signing key at index %d', $i);
63+
64+
if (!\is_string($candidate)) {
65+
throw new InvalidArgumentException(\sprintf('%s must be a string, got %s.', $name, get_debug_type($candidate)));
66+
}
67+
68+
if (\strlen($candidate) < self::MINIMUM_KEY_BYTES) {
69+
throw new InvalidArgumentException(\sprintf('%s must be at least %d bytes, got %d.', $name, self::MINIMUM_KEY_BYTES, \strlen($candidate)));
70+
}
4771
}
4872

73+
$this->keys = $keys;
74+
4975
if ($this->ttlSeconds < 1) {
5076
throw new InvalidArgumentException(\sprintf('The requestState TTL must be at least one second, got %d.', $this->ttlSeconds));
5177
}
5278
}
5379

5480
/**
55-
* A codec with the same key and TTL whose states only verify under the
81+
* A codec with the same keys and TTL whose states only verify under the
5682
* same binding, e.g. the value a {@see RequestStateBinderInterface}
5783
* computed for the request at hand.
5884
*/
5985
public function withBinding(string $binding): self
6086
{
61-
return new self($this->key, $this->ttlSeconds, $binding);
87+
return new self($this->keys, $this->ttlSeconds, $binding);
6288
}
6389

6490
/**
@@ -71,14 +97,14 @@ public function mint(array $payload, ?int $now = null): string
7197
'data' => $payload,
7298
], \JSON_THROW_ON_ERROR));
7399

74-
return $body.'.'.self::encode($this->sign($body));
100+
return $body.'.'.self::encode($this->sign($body, $this->keys[0]));
75101
}
76102

77103
/**
78104
* @return array<string, mixed> the payload that was sealed
79105
*
80-
* @throws RequestStateException when the value is malformed, unsigned by this key, bound to
81-
* something else than this codec, or expired
106+
* @throws RequestStateException when the value is malformed, signed by none of the keys,
107+
* bound to something else than this codec, or expired
82108
*/
83109
public function verify(string $state, ?int $now = null): array
84110
{
@@ -90,11 +116,23 @@ public function verify(string $state, ?int $now = null): array
90116

91117
[$body, $mac] = $parts;
92118

93-
$expected = $this->sign($body);
94119
$actual = self::decode($mac);
95120

96-
// Constant-time: a short-circuiting compare is a byte-at-a-time oracle.
97-
if (null === $actual || !hash_equals($expected, $actual)) {
121+
if (null === $actual) {
122+
throw new RequestStateException('mac');
123+
}
124+
125+
// Every key, no early exit: which key signed is nobody's business. A
126+
// ring holds a handful of keys, so trying each costs next to nothing
127+
// and spares the wire format a key id.
128+
$verified = false;
129+
130+
foreach ($this->keys as $key) {
131+
// Constant-time: a short-circuiting compare is a byte-at-a-time oracle.
132+
$verified = hash_equals($this->sign($body, $key), $actual) || $verified;
133+
}
134+
135+
if (!$verified) {
98136
throw new RequestStateException('mac');
99137
}
100138

@@ -123,13 +161,13 @@ public function verify(string $state, ?int $now = null): array
123161
return $claims['data'];
124162
}
125163

126-
private function sign(string $body): string
164+
private function sign(string $body, string $key): string
127165
{
128166
// The body is base64url, so it never contains the '.' separating it
129167
// from the binding: a bound and an unbound input can never collide.
130168
$input = null === $this->binding ? $body : $body.'.'.$this->binding;
131169

132-
return hash_hmac(self::ALGORITHM, $input, $this->key, true);
170+
return hash_hmac(self::ALGORITHM, $input, $key, true);
133171
}
134172

135173
private static function encode(string $raw): string

‎tests/Unit/Server/Stateless/RequestStateCodecTest.php‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,16 @@
1414
use Mcp\Exception\InvalidArgumentException;
1515
use Mcp\Exception\RequestStateException;
1616
use Mcp\Server\Stateless\RequestStateCodec;
17+
use PHPUnit\Framework\Attributes\DataProvider;
1718
use PHPUnit\Framework\Attributes\TestDox;
1819
use PHPUnit\Framework\TestCase;
1920

2021
class RequestStateCodecTest extends TestCase
2122
{
2223
private const KEY = 'a-key-that-is-long-enough-to-be-secure';
2324
private const OTHER_KEY = 'a-different-key-that-is-also-long-enough';
25+
private const OLD_KEY = 'the-key-being-rotated-out-of-the-ring';
26+
private const NEW_KEY = 'the-key-being-rotated-into-the-ring-now';
2427

2528
#[TestDox('a sealed payload survives the round trip intact')]
2629
public function testRoundTrip(): void
@@ -159,6 +162,85 @@ public function testBindingStaysOffTheWire(): void
159162
);
160163
}
161164

165+
#[TestDox('rotating through a key ring never fails a state still within its TTL')]
166+
public function testKeyRotation(): void
167+
{
168+
$old = new RequestStateCodec(self::OLD_KEY);
169+
$mintedByOld = $old->mint(['round' => 1]);
170+
171+
// Step 1, for more than one instance: every instance learns the new
172+
// key before any signs with it.
173+
$learning = new RequestStateCodec([self::OLD_KEY, self::NEW_KEY]);
174+
$this->assertSame(['round' => 1], $learning->verify($mintedByOld));
175+
$mintedWhileLearning = $learning->mint(['round' => 2]);
176+
$this->assertSame(['round' => 2], $old->verify($mintedWhileLearning), 'An instance not yet updated verifies it.');
177+
178+
// Step 2: the new key signs, the old one still verifies.
179+
$rotated = new RequestStateCodec([self::NEW_KEY, self::OLD_KEY]);
180+
$mintedByNew = $rotated->mint(['round' => 3]);
181+
$this->assertSame(['round' => 1], $rotated->verify($mintedByOld));
182+
$this->assertSame(['round' => 3], $rotated->verify($mintedByNew));
183+
$this->assertSame(['round' => 3], $learning->verify($mintedByNew), 'An instance still on step 1 verifies it.');
184+
185+
// Step 3, one TTL later: the old key is gone, and so is what it signed.
186+
$retired = new RequestStateCodec(self::NEW_KEY);
187+
$this->assertSame(['round' => 3], $retired->verify($mintedByNew));
188+
189+
$this->expectExceptionObject(new RequestStateException('mac'));
190+
$retired->verify($mintedByOld);
191+
}
192+
193+
#[TestDox('a state signed by none of the ring\'s keys is refused')]
194+
public function testForeignKeyRefusedByARing(): void
195+
{
196+
$state = (new RequestStateCodec(self::OTHER_KEY))->mint(['round' => 1]);
197+
198+
$this->expectExceptionObject(new RequestStateException('mac'));
199+
(new RequestStateCodec([self::NEW_KEY, self::OLD_KEY, self::KEY]))->verify($state);
200+
}
201+
202+
#[TestDox('a bound codec keeps the key ring: a bound state the old key signed verifies after the rotation')]
203+
public function testBindingSurvivesARotation(): void
204+
{
205+
$state = (new RequestStateCodec(self::OLD_KEY))->withBinding('tools/call|book')->mint(['round' => 1]);
206+
$rotated = new RequestStateCodec([self::NEW_KEY, self::OLD_KEY]);
207+
208+
$this->assertSame(['round' => 1], $rotated->withBinding('tools/call|book')->verify($state));
209+
210+
$this->expectExceptionObject(new RequestStateException('mac'));
211+
$rotated->withBinding('tools/call|cancel')->verify($state);
212+
}
213+
214+
#[TestDox('a single key and a ring of that key mint the same wire value')]
215+
public function testSingleKeyIsARingOfOne(): void
216+
{
217+
$single = new RequestStateCodec(self::KEY);
218+
$ring = new RequestStateCodec([self::KEY]);
219+
220+
$this->assertSame($single->mint(['round' => 1], now: 1_000), $ring->mint(['round' => 1], now: 1_000));
221+
$this->assertSame(['round' => 1], $ring->verify($single->mint(['round' => 1])));
222+
$this->assertSame(['round' => 1], $single->verify($ring->mint(['round' => 1])));
223+
}
224+
225+
/**
226+
* @return iterable<string, array{mixed}>
227+
*/
228+
public static function invalidRings(): iterable
229+
{
230+
yield 'empty' => [[]];
231+
yield 'short key behind a good one' => [[self::KEY, 'too-short']];
232+
yield 'not a list' => [['current' => self::KEY]];
233+
yield 'not a string' => [[self::KEY, 42]];
234+
}
235+
236+
#[DataProvider('invalidRings')]
237+
#[TestDox('an invalid key ring is refused at construction: $_dataName')]
238+
public function testInvalidRingRefused(mixed $keys): void
239+
{
240+
$this->expectException(InvalidArgumentException::class);
241+
new RequestStateCodec($keys);
242+
}
243+
162244
#[TestDox('a key too short to be safe is refused at construction')]
163245
public function testShortKeyRefused(): void
164246
{

‎tests/Unit/Server/Stateless/StatelessProtocolTest.php‎

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -587,7 +587,10 @@ public function testUndeclaredGatewayElicitationIsRefused(): void
587587
* A handler asking twice: the second round has to remember the first
588588
* round's answer, which is what the `requestState` is for.
589589
*/
590-
private static function twoAskProtocol(bool $signed = true, ?RequestStateBinderInterface $binder = null): StatelessProtocol
590+
/**
591+
* @param string|list<string>|null $key the signing key or key ring, a fixed test key by default
592+
*/
593+
private static function twoAskProtocol(bool $signed = true, ?RequestStateBinderInterface $binder = null, string|array|null $key = null): StatelessProtocol
591594
{
592595
$builder = Server::builder()
593596
->setServerInfo('test-server', '1.0.0')
@@ -611,7 +614,7 @@ static function (RequestContext $context): string {
611614
);
612615

613616
if ($signed) {
614-
$builder->setRequestState(str_repeat('k', 32), binder: $binder);
617+
$builder->setRequestState($key ?? str_repeat('k', 32), binder: $binder);
615618
}
616619

617620
return $builder->buildStateless([ProtocolVersion::V2026_07_28]);
@@ -827,6 +830,29 @@ public function testUnboundStateIsNotTiedToTheCall(): void
827830
$this->assertSame('morning/aisle', $answer['body']['result']['content'][0]['text']);
828831
}
829832

833+
#[TestDox('a server rotating its key still serves the retry of a call the old key signed')]
834+
public function testRetryServedAcrossAKeyRotation(): void
835+
{
836+
$oldKey = str_repeat('o', 32);
837+
$newKey = str_repeat('n', 32);
838+
839+
$second = self::book(self::twoAskProtocol(key: $oldKey), [
840+
'inputResponses' => ['when' => ['action' => 'accept', 'content' => ['v' => 'morning']]],
841+
]);
842+
$retry = [
843+
'inputResponses' => ['seat' => ['action' => 'accept', 'content' => ['v' => 'aisle']]],
844+
'requestState' => $second['body']['result']['requestState'],
845+
];
846+
847+
$rotated = self::book(self::twoAskProtocol(key: [$newKey, $oldKey]), $retry);
848+
$this->assertSame(200, $rotated['status']);
849+
$this->assertSame('morning/aisle', $rotated['body']['result']['content'][0]['text']);
850+
851+
$retired = self::book(self::twoAskProtocol(key: [$newKey]), $retry);
852+
$this->assertSame(400, $retired['status']);
853+
$this->assertSame('The supplied requestState failed verification.', $retired['body']['error']['message']);
854+
}
855+
830856
#[TestDox('carrying an answer to the next round without a signing key fails loudly')]
831857
public function testCarryingAnAnswerNeedsASigningKey(): void
832858
{

0 commit comments

Comments
 (0)