Skip to content

Commit 5eb4e84

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 a0e195b commit 5eb4e84

7 files changed

Lines changed: 178 additions & 17 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ All notable changes to `mcp/sdk` will be documented in this file.
2626
* Add `Psr6SessionStore` and `Psr6NotificationBus`, which work like `Psr16SessionStore` and `Psr16NotificationBus` over a PSR-6 cache pool. `Builder::setDiscovery()` also accepts a PSR-6 pool as `$cache`.
2727
* Fix a nullable tool parameter with a default (e.g. `?string $category = 'books'`) receiving the default when the client explicitly sends `null`: `ReferenceHandler` now passes the `null` through.
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()`.
29+
* 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.
2930

3031
### Client
3132

‎docs/handlers/input-required.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,26 @@ The **same key must reach every process that might serve the retry**. A per-proc
9898
value works only for a single-process deployment. Nothing secret belongs in the payload —
9999
it is signed, not encrypted.
100100

101+
### Rotating the key
102+
103+
Pass a list of keys instead of one, and the first key signs while every key verifies:
104+
105+
```php
106+
->setRequestState([$_ENV['MCP_REQUEST_STATE_KEY'], $_ENV['MCP_REQUEST_STATE_KEY_PREVIOUS']], ttl: 600)
107+
```
108+
109+
A state names no key, so the wire format does not change and a single key is a ring of one.
110+
To rotate without failing the calls in flight:
111+
112+
1. Add the new key **behind** the current one, `[$current, $new]`, and deploy it to every
113+
process. They still sign with the current key but already accept the new one.
114+
A single-process deployment can skip this step.
115+
2. Move the new key to the front, `[$new, $current]`. States are signed with the new key from
116+
now on, and the ones the old key signed still verify.
117+
3. After one TTL, every state the old key signed has expired. Remove it, `[$new]`.
118+
119+
Each key needs at least 32 bytes.
120+
101121
## Capabilities
102122

103123
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
@@ -116,6 +116,7 @@ $server = Server::builder()
116116
// Signs the state a multi round-trip request carries through the client.
117117
// The same key must reach every process that might serve the retry.
118118
// The key needs at least 32 bytes, otherwise build() throws. TTL in seconds, default 600.
119+
// A list of keys rotates them: the first signs, every key verifies.
119120
// Without a key, the server refuses every state the client sends back.
120121
->setRequestState($_ENV['MCP_REQUEST_STATE_KEY'], ttl: 600)
121122

@@ -328,7 +329,7 @@ $server = Server::builder()
328329
| `setProtocolVersion()` | protocolVersion | Pin the handshake to one protocol revision |
329330
| `setModernVersions()` | versions | Narrow the revisions the modern (2026-07-28) leg answers for |
330331
| `withoutModernEra()` | - | Serve the handshake era only |
331-
| `setRequestState()` | key, ttl? | Signing key and lifetime for multi round-trip request state |
332+
| `setRequestState()` | key, ttl? | Signing key (or key ring, the first key signing) and lifetime for multi round-trip request state |
332333
| `setInputRequiredLimits()` | maxRounds, roundTimeout | Bound the input-required shim on handshake-era connections |
333334
| `withoutInputRequiredShim()` | - | Do not fulfil an `InputRequiredResult` over a handshake-era connection |
334335
| `setCachePolicy()` | policy | Set the `ttlMs`/`cacheScope` hints on cacheable results |

‎src/Server/Builder.php‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,8 @@ final class Builder
142142
/** @var list<class-string<\Mcp\Schema\JsonRpc\Request>|class-string<\Mcp\Schema\JsonRpc\Notification>> */
143143
private array $extensionMessages = [];
144144

145-
private ?string $requestStateKey = null;
145+
/** @var string|list<string>|null */
146+
private string|array|null $requestStateKey = null;
146147

147148
private int $requestStateTtl = 600;
148149

@@ -376,10 +377,14 @@ public function setCachePolicy(CachePolicy $policy): self
376377
* The same key must reach every instance that might serve the retry, so a
377378
* per-process random value only works for a single-process deployment.
378379
*
379-
* @param string $key at least 32 bytes
380-
* @param int $ttl how long a minted state stays valid, in seconds
380+
* A list of keys is a key ring: the first key signs, every key verifies.
381+
* To rotate, put the new key first and keep the old one behind it until
382+
* the states it signed have expired, one TTL later.
383+
*
384+
* @param string|list<string> $key the signing key or key ring, each key at least 32 bytes
385+
* @param int $ttl how long a minted state stays valid, in seconds
381386
*/
382-
public function setRequestState(string $key, int $ttl = 600): self
387+
public function setRequestState(string|array $key, int $ttl = 600): self
383388
{
384389
$this->requestStateKey = $key;
385390
$this->requestStateTtl = $ttl;

‎src/Server/Stateless/RequestStateCodec.php‎

Lines changed: 48 additions & 10 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 is the same either way.
29+
*
2630
* @author Christopher Hertel <mail@christopher-hertel.de>
2731
*/
2832
final class RequestStateCodec
@@ -32,14 +36,36 @@ final class RequestStateCodec
3236

3337
private const ALGORITHM = 'sha256';
3438

39+
/** @var non-empty-list<string> */
40+
private readonly array $keys;
41+
42+
/**
43+
* @param string|list<string> $key the signing key, or a key ring whose first key signs and whose every key verifies
44+
*/
3545
public function __construct(
36-
private readonly string $key,
46+
string|array $key,
3747
private readonly int $ttlSeconds = 600,
3848
) {
39-
if (\strlen($this->key) < self::MINIMUM_KEY_BYTES) {
40-
throw new InvalidArgumentException(\sprintf('The requestState signing key must be at least %d bytes, got %d.', self::MINIMUM_KEY_BYTES, \strlen($this->key)));
49+
$keys = \is_string($key) ? [$key] : $key;
50+
51+
if ([] === $keys || !array_is_list($keys)) {
52+
throw new InvalidArgumentException('The requestState key ring must be a non-empty list of keys.');
53+
}
54+
55+
foreach ($keys as $i => $candidate) {
56+
$name = \is_string($key) ? 'The requestState signing key' : \sprintf('The requestState signing key at index %d', $i);
57+
58+
if (!\is_string($candidate)) {
59+
throw new InvalidArgumentException(\sprintf('%s must be a string, got %s.', $name, get_debug_type($candidate)));
60+
}
61+
62+
if (\strlen($candidate) < self::MINIMUM_KEY_BYTES) {
63+
throw new InvalidArgumentException(\sprintf('%s must be at least %d bytes, got %d.', $name, self::MINIMUM_KEY_BYTES, \strlen($candidate)));
64+
}
4165
}
4266

67+
$this->keys = $keys;
68+
4369
if ($this->ttlSeconds < 1) {
4470
throw new InvalidArgumentException(\sprintf('The requestState TTL must be at least one second, got %d.', $this->ttlSeconds));
4571
}
@@ -55,13 +81,13 @@ public function mint(array $payload, ?int $now = null): string
5581
'data' => $payload,
5682
], \JSON_THROW_ON_ERROR));
5783

58-
return $body.'.'.self::encode($this->sign($body));
84+
return $body.'.'.self::encode(self::sign($body, $this->keys[0]));
5985
}
6086

6187
/**
6288
* @return array<string, mixed> the payload that was sealed
6389
*
64-
* @throws RequestStateException when the value is malformed, unsigned by this key, or expired
90+
* @throws RequestStateException when the value is malformed, signed by none of the keys, or expired
6591
*/
6692
public function verify(string $state, ?int $now = null): array
6793
{
@@ -73,11 +99,23 @@ public function verify(string $state, ?int $now = null): array
7399

74100
[$body, $mac] = $parts;
75101

76-
$expected = $this->sign($body);
77102
$actual = self::decode($mac);
78103

79-
// Constant-time: a short-circuiting compare is a byte-at-a-time oracle.
80-
if (null === $actual || !hash_equals($expected, $actual)) {
104+
if (null === $actual) {
105+
throw new RequestStateException('mac');
106+
}
107+
108+
// Every key, no early exit: which key signed is nobody's business. A
109+
// ring holds a handful of keys, so trying each costs next to nothing
110+
// and spares the wire format a key id.
111+
$verified = false;
112+
113+
foreach ($this->keys as $key) {
114+
// Constant-time: a short-circuiting compare is a byte-at-a-time oracle.
115+
$verified = hash_equals(self::sign($body, $key), $actual) || $verified;
116+
}
117+
118+
if (!$verified) {
81119
throw new RequestStateException('mac');
82120
}
83121

@@ -106,9 +144,9 @@ public function verify(string $state, ?int $now = null): array
106144
return $claims['data'];
107145
}
108146

109-
private function sign(string $body): string
147+
private static function sign(string $body, string $key): string
110148
{
111-
return hash_hmac(self::ALGORITHM, $body, $this->key, true);
149+
return hash_hmac(self::ALGORITHM, $body, $key, true);
112150
}
113151

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

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

Lines changed: 70 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
@@ -112,6 +115,73 @@ public function testFailureReasonsAreOpaque(): void
112115
}
113116
}
114117

118+
#[TestDox('rotating through a key ring never fails a state still within its TTL')]
119+
public function testKeyRotation(): void
120+
{
121+
$old = new RequestStateCodec(self::OLD_KEY);
122+
$mintedByOld = $old->mint(['round' => 1]);
123+
124+
// Step 1, for more than one instance: every instance learns the new
125+
// key before any signs with it.
126+
$learning = new RequestStateCodec([self::OLD_KEY, self::NEW_KEY]);
127+
$this->assertSame(['round' => 1], $learning->verify($mintedByOld));
128+
$mintedWhileLearning = $learning->mint(['round' => 2]);
129+
$this->assertSame(['round' => 2], $old->verify($mintedWhileLearning), 'An instance not yet updated verifies it.');
130+
131+
// Step 2: the new key signs, the old one still verifies.
132+
$rotated = new RequestStateCodec([self::NEW_KEY, self::OLD_KEY]);
133+
$mintedByNew = $rotated->mint(['round' => 3]);
134+
$this->assertSame(['round' => 1], $rotated->verify($mintedByOld));
135+
$this->assertSame(['round' => 3], $rotated->verify($mintedByNew));
136+
$this->assertSame(['round' => 3], $learning->verify($mintedByNew), 'An instance still on step 1 verifies it.');
137+
138+
// Step 3, one TTL later: the old key is gone, and so is what it signed.
139+
$retired = new RequestStateCodec(self::NEW_KEY);
140+
$this->assertSame(['round' => 3], $retired->verify($mintedByNew));
141+
142+
$this->expectExceptionObject(new RequestStateException('mac'));
143+
$retired->verify($mintedByOld);
144+
}
145+
146+
#[TestDox('a state signed by none of the ring\'s keys is refused')]
147+
public function testForeignKeyRefusedByARing(): void
148+
{
149+
$state = (new RequestStateCodec(self::OTHER_KEY))->mint(['round' => 1]);
150+
151+
$this->expectExceptionObject(new RequestStateException('mac'));
152+
(new RequestStateCodec([self::NEW_KEY, self::OLD_KEY, self::KEY]))->verify($state);
153+
}
154+
155+
#[TestDox('a single key and a ring of that key mint the same wire value')]
156+
public function testSingleKeyIsARingOfOne(): void
157+
{
158+
$single = new RequestStateCodec(self::KEY);
159+
$ring = new RequestStateCodec([self::KEY]);
160+
161+
$this->assertSame($single->mint(['round' => 1], now: 1_000), $ring->mint(['round' => 1], now: 1_000));
162+
$this->assertSame(['round' => 1], $ring->verify($single->mint(['round' => 1])));
163+
$this->assertSame(['round' => 1], $single->verify($ring->mint(['round' => 1])));
164+
}
165+
166+
/**
167+
* @return iterable<string, array{mixed}>
168+
*/
169+
public static function invalidRings(): iterable
170+
{
171+
yield 'empty' => [[]];
172+
yield 'short key behind a good one' => [[self::KEY, 'too-short']];
173+
yield 'not a list' => [['current' => self::KEY]];
174+
yield 'not a string' => [[self::KEY, 42]];
175+
}
176+
177+
#[DataProvider('invalidRings')]
178+
#[TestDox('an invalid key ring is refused at construction: $_dataName')]
179+
public function testInvalidRingRefused(mixed $keys): void
180+
{
181+
$this->expectException(InvalidArgumentException::class);
182+
new RequestStateCodec($keys);
183+
}
184+
115185
#[TestDox('a key too short to be safe is refused at construction')]
116186
public function testShortKeyRefused(): void
117187
{

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

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -577,7 +577,10 @@ public function testUndeclaredGatewayElicitationIsRefused(): void
577577
* A handler asking twice: the second round has to remember the first
578578
* round's answer, which is what the `requestState` is for.
579579
*/
580-
private static function twoAskProtocol(bool $signed = true): StatelessProtocol
580+
/**
581+
* @param string|list<string>|null $key the signing key or key ring, a fixed test key by default
582+
*/
583+
private static function twoAskProtocol(bool $signed = true, string|array|null $key = null): StatelessProtocol
581584
{
582585
$builder = Server::builder()
583586
->setServerInfo('test-server', '1.0.0')
@@ -601,7 +604,7 @@ static function (RequestContext $context): string {
601604
);
602605

603606
if ($signed) {
604-
$builder->setRequestState(str_repeat('k', 32));
607+
$builder->setRequestState($key ?? str_repeat('k', 32));
605608
}
606609

607610
return $builder->buildStateless([ProtocolVersion::V2026_07_28]);
@@ -650,6 +653,29 @@ public function testNamedAsksCarryAcrossRounds(): void
650653
$this->assertSame('morning/aisle', $third['body']['result']['content'][0]['text']);
651654
}
652655

656+
#[TestDox('a server rotating its key still serves the retry of a call the old key signed')]
657+
public function testRetryServedAcrossAKeyRotation(): void
658+
{
659+
$oldKey = str_repeat('o', 32);
660+
$newKey = str_repeat('n', 32);
661+
662+
$second = self::book(self::twoAskProtocol(key: $oldKey), [
663+
'inputResponses' => ['when' => ['action' => 'accept', 'content' => ['v' => 'morning']]],
664+
]);
665+
$retry = [
666+
'inputResponses' => ['seat' => ['action' => 'accept', 'content' => ['v' => 'aisle']]],
667+
'requestState' => $second['body']['result']['requestState'],
668+
];
669+
670+
$rotated = self::book(self::twoAskProtocol(key: [$newKey, $oldKey]), $retry);
671+
$this->assertSame(200, $rotated['status']);
672+
$this->assertSame('morning/aisle', $rotated['body']['result']['content'][0]['text']);
673+
674+
$retired = self::book(self::twoAskProtocol(key: [$newKey]), $retry);
675+
$this->assertSame(400, $retired['status']);
676+
$this->assertSame('The supplied requestState failed verification.', $retired['body']['error']['message']);
677+
}
678+
653679
#[TestDox('carrying an answer to the next round without a signing key fails loudly')]
654680
public function testCarryingAnAnswerNeedsASigningKey(): void
655681
{

0 commit comments

Comments
 (0)