Skip to content

Commit 2a24b6f

Browse files
[Server] Bind Streamable HTTP sessions to the principal that opened them
1 parent 57b45eb commit 2a24b6f

12 files changed

Lines changed: 396 additions & 33 deletions

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,11 @@
22

33
All notable changes to `mcp/sdk` will be documented in this file.
44

5+
0.10.0
6+
------
7+
8+
* [BC Break] Bind handshake-era sessions to the principal that opened them, as the security best practices recommend. A request of another principal with the session's id is answered with `404`, like an unknown session, and its `DELETE` does not end the session. `AuthorizationMiddleware` identifies the principal by the token's issuer, subject and client; an application that authenticates requests itself sets the `StreamableHttpTransport::PRINCIPAL_ATTRIBUTE` request attribute. `Protocol::processInput()`, `BaseTransport::handleMessage()`, `BaseTransport::handleSessionEnd()`, `StreamableHttpTransport::handlePostRequest()` and `StreamableHttpTransport::handleDeleteRequest()` take a `?string $principal` parameter, as do the `TransportInterface::onMessage()` and `onSessionEnd()` listeners as last argument.
9+
510
0.9.0
611
-----
712

‎docs/run/authorization.md‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -313,16 +313,31 @@ challenge a client steps up from. Use `$token->hasScope()` for decisions that de
313313
arguments beyond the tool name. With a `ScopePolicy`, the token's scopes include those implied by
314314
its hierarchy.
315315

316+
## Sessions and the Principal
317+
318+
A handshake-era session only serves the principal that opened it, as the
319+
[security best practices](https://modelcontextprotocol.io/specification/2025-11-25/basic/security_best_practices#session-hijacking)
320+
recommend. `AuthorizationMiddleware` identifies the principal by the issuer, subject and client of
321+
the token. They stay the same when the client refreshes its token, so the session survives the refresh.
322+
323+
When another principal sends the session's `Mcp-Session-Id`, the server answers 404, as for an
324+
unknown session, and a `DELETE` does not end the session. A token without a `sub` claim identifies
325+
no principal. A session opened with such a token only serves requests without a principal.
326+
316327
## Authenticating Outside the SDK
317328

318329
If your application or framework already authenticates the request, skip `AuthorizationMiddleware`
319330
and hand the result to the transport as the PSR-7 request attribute `AccessToken::class`. Both HTTP
320-
transports read it from there, so handlers get it through `RequestContext::getAccessToken()` as usual:
331+
transports read it from there, so handlers get it through `RequestContext::getAccessToken()` as usual.
332+
Also set the `StreamableHttpTransport::PRINCIPAL_ATTRIBUTE` attribute to a string that identifies
333+
the user, so that a session only serves the user that opened it:
321334

322335
```php
323336
use Mcp\Server\Authorization\AccessToken;
324337

325-
$request = $request->withAttribute(AccessToken::class, new AccessToken($scopes, $claims));
338+
$request = $request
339+
->withAttribute(AccessToken::class, new AccessToken($scopes, $claims))
340+
->withAttribute(StreamableHttpTransport::PRINCIPAL_ATTRIBUTE, $userId);
326341
$transport = new StreamableHttpTransport($request);
327342
```
328343

‎src/Server/Protocol.php‎

Lines changed: 63 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,9 @@ class Protocol
7070

7171
public const SESSION_LOGGING_LEVEL = '_mcp.logging_level';
7272

73+
/** Session key for the fingerprint of the principal that opened the session */
74+
private const SESSION_PRINCIPAL = '_mcp.principal';
75+
7376
/**
7477
* Deliberately generic: unexpected throwables carry internal details such as file paths, class
7578
* names and argument types, which must not be handed to the peer. The full exception is logged.
@@ -139,7 +142,7 @@ public function connect(TransportInterface $transport): void
139142
{
140143
$transport->onMessage($this->processInput(...));
141144

142-
$transport->onSessionEnd($this->destroySession(...));
145+
$transport->onSessionEnd($this->endSession(...));
143146

144147
// The transport keeps these callbacks, so they reference it weakly to not keep it alive.
145148
$transportRef = \WeakReference::create($transport);
@@ -167,13 +170,14 @@ public function connect(TransportInterface $transport): void
167170
*
168171
* @param TransportInterface<mixed> $transport
169172
* @param AccessToken|null $accessToken the token the input was authorized with, if the transport authorizes
173+
* @param string|null $principal who the input was authenticated as, if the transport authenticates
170174
*/
171-
public function processInput(TransportInterface $transport, string $input, ?Uuid $sessionId, ?AccessToken $accessToken = null): void
175+
public function processInput(TransportInterface $transport, string $input, ?Uuid $sessionId, ?AccessToken $accessToken = null, ?string $principal = null): void
172176
{
173177
// Last line of defense: a malformed message must never escape as a PHP error and take the
174178
// server process down.
175179
try {
176-
$this->doProcessInput($transport, $input, $sessionId, $accessToken);
180+
$this->doProcessInput($transport, $input, $sessionId, $accessToken, $principal);
177181
} catch (\Throwable $e) {
178182
$this->logger->error(\sprintf('Uncaught exception while processing input: %s', $e->getMessage()), ['exception' => $e]);
179183

@@ -230,7 +234,7 @@ private static function findResponseId(string $input): string|int|null
230234
/**
231235
* @param TransportInterface<mixed> $transport
232236
*/
233-
private function doProcessInput(TransportInterface $transport, string $input, ?Uuid $sessionId, ?AccessToken $accessToken): void
237+
private function doProcessInput(TransportInterface $transport, string $input, ?Uuid $sessionId, ?AccessToken $accessToken, ?string $principal): void
234238
{
235239
$this->logger->info('Received message to process.');
236240
$this->logger->debug('Received message payload.', ['message' => $input]);
@@ -269,7 +273,7 @@ private function doProcessInput(TransportInterface $transport, string $input, ?U
269273
}
270274

271275
try {
272-
$this->handleMessages($transport, $sessionId, $messages, $accessToken);
276+
$this->handleMessages($transport, $sessionId, $messages, $accessToken, $principal);
273277
} finally {
274278
if ($takesLock) {
275279
$this->releaseSessionLock($sessionId);
@@ -281,9 +285,9 @@ private function doProcessInput(TransportInterface $transport, string $input, ?U
281285
* @param TransportInterface<mixed> $transport
282286
* @param array<int, mixed> $messages
283287
*/
284-
private function handleMessages(TransportInterface $transport, ?Uuid $sessionId, array $messages, ?AccessToken $accessToken): void
288+
private function handleMessages(TransportInterface $transport, ?Uuid $sessionId, array $messages, ?AccessToken $accessToken, ?string $principal): void
285289
{
286-
$session = $this->resolveSession($transport, $sessionId, $messages);
290+
$session = $this->resolveSession($transport, $sessionId, $messages, $principal);
287291
if (null === $session) {
288292
return;
289293
}
@@ -1112,8 +1116,9 @@ private function hasInitializeRequest(array $messages): bool
11121116
* @param TransportInterface<mixed> $transport
11131117
* @param Uuid|null $sessionId The session ID from the transport
11141118
* @param array<int,mixed> $messages The parsed messages
1119+
* @param string|null $principal Who the messages were authenticated as
11151120
*/
1116-
private function resolveSession(TransportInterface $transport, ?Uuid $sessionId, array $messages): ?SessionInterface
1121+
private function resolveSession(TransportInterface $transport, ?Uuid $sessionId, array $messages, ?string $principal): ?SessionInterface
11171122
{
11181123
if ($this->hasInitializeRequest($messages)) {
11191124
// Spec: An initialize request must not be part of a batch.
@@ -1133,6 +1138,10 @@ private function resolveSession(TransportInterface $transport, ?Uuid $sessionId,
11331138
}
11341139

11351140
$session = $this->sessionManager->create();
1141+
if (null !== $principal) {
1142+
$session->set(self::SESSION_PRINCIPAL, self::fingerprint($principal));
1143+
}
1144+
11361145
$this->logger->debug('Created new session for initialize', [
11371146
'session_id' => $session->getId()->toRfc4122(),
11381147
]);
@@ -1171,7 +1180,36 @@ private function resolveSession(TransportInterface $transport, ?Uuid $sessionId,
11711180
return null;
11721181
}
11731182

1174-
return $this->sessionManager->createWithId($sessionId);
1183+
$session = $this->sessionManager->createWithId($sessionId);
1184+
1185+
if (!$this->servesPrincipal($session, $principal)) {
1186+
$this->logger->warning('Refused a request of another principal than the one that opened the session.', [
1187+
'session_id' => $sessionId->toRfc4122(),
1188+
]);
1189+
1190+
// Answered like an unknown session, so that another principal cannot tell the session exists.
1191+
$error = Error::forInvalidRequest('Session not found or has expired.');
1192+
$this->sendResponse($transport, $error, null, ['status_code' => 404]);
1193+
1194+
return null;
1195+
}
1196+
1197+
return $session;
1198+
}
1199+
1200+
/**
1201+
* Whether the session serves the principal: the one that opened it, or no principal for a session opened without one.
1202+
*/
1203+
private function servesPrincipal(SessionInterface $session, ?string $principal): bool
1204+
{
1205+
$fingerprint = $session->get(self::SESSION_PRINCIPAL);
1206+
1207+
return (\is_string($fingerprint) ? $fingerprint : null) === self::fingerprint($principal);
1208+
}
1209+
1210+
private static function fingerprint(?string $principal): ?string
1211+
{
1212+
return null === $principal ? null : hash('sha256', $principal);
11751213
}
11761214

11771215
/**
@@ -1189,6 +1227,22 @@ private static function findRequestId(array $messages): string|int|null
11891227
};
11901228
}
11911229

1230+
/**
1231+
* Ends a session at the request of a client, which must be the principal that opened it.
1232+
*/
1233+
private function endSession(Uuid $sessionId, ?string $principal = null): void
1234+
{
1235+
if ($this->sessionManager->exists($sessionId) && !$this->servesPrincipal($this->sessionManager->createWithId($sessionId), $principal)) {
1236+
$this->logger->warning('Refused to end a session for another principal than the one that opened it.', [
1237+
'session_id' => $sessionId->toRfc4122(),
1238+
]);
1239+
1240+
return;
1241+
}
1242+
1243+
$this->destroySession($sessionId);
1244+
}
1245+
11921246
/**
11931247
* Destroy a specific session.
11941248
*/

‎src/Server/Transport/BaseTransport.php‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -145,17 +145,17 @@ protected function handleFiberYield(mixed $yielded, ?Uuid $sessionId, \Fiber $fi
145145
}
146146
}
147147

148-
protected function handleMessage(string $payload, ?Uuid $sessionId, ?AccessToken $accessToken = null): void
148+
protected function handleMessage(string $payload, ?Uuid $sessionId, ?AccessToken $accessToken = null, ?string $principal = null): void
149149
{
150150
if (\is_callable($this->messageListener)) {
151-
($this->messageListener)($this, $payload, $sessionId, $accessToken);
151+
($this->messageListener)($this, $payload, $sessionId, $accessToken, $principal);
152152
}
153153
}
154154

155-
protected function handleSessionEnd(?Uuid $sessionId): void
155+
protected function handleSessionEnd(?Uuid $sessionId, ?string $principal = null): void
156156
{
157157
if ($sessionId && \is_callable($this->sessionEndListener)) {
158-
($this->sessionEndListener)($sessionId);
158+
($this->sessionEndListener)($sessionId, $principal);
159159
}
160160
}
161161
}

‎src/Server/Transport/Http/Middleware/AuthorizationMiddleware.php‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@
3535
* - Returns 403 insufficient_scope when the token lacks a scope the {@see ScopePolicy} requires
3636
* - Hands the validated {@see AccessToken} to the transport as request attribute,
3737
* from where handlers read it via {@see \Mcp\Server\RequestContext::getAccessToken()}
38+
* - Identifies the principal by the token's issuer, subject and client, so that a session
39+
* only serves the principal that opened it, see {@see StreamableHttpTransport::PRINCIPAL_ATTRIBUTE}
3840
*
3941
* @see https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization
4042
*
@@ -113,7 +115,15 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
113115
$token = new AccessToken($granted, $token->getClaims());
114116
}
115117

116-
return $handler->handle($request->withAttribute(AccessToken::class, $token));
118+
$request = $request->withAttribute(AccessToken::class, $token);
119+
120+
if (null !== $subject = $token->getSubject()) {
121+
// Kept across token refreshes, unlike the token itself or its scopes.
122+
$principal = json_encode([$token->getClaim('iss'), $subject, $token->getClientId()], \JSON_THROW_ON_ERROR);
123+
$request = $request->withAttribute(StreamableHttpTransport::PRINCIPAL_ATTRIBUTE, $principal);
124+
}
125+
126+
return $handler->handle($request);
117127
}
118128

119129
private function buildErrorResponse(AuthorizationResult $result): ResponseInterface

‎src/Server/Transport/ManagesTransportCallbacks.php‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,10 @@
2828
* */
2929
trait ManagesTransportCallbacks
3030
{
31-
/** @var callable(TransportInterface<mixed>, string, ?Uuid, ?AccessToken): void */
31+
/** @var callable(TransportInterface<mixed>, string, ?Uuid, ?AccessToken, ?string): void */
3232
protected $messageListener;
3333

34-
/** @var callable(Uuid): void */
34+
/** @var callable(Uuid, ?string): void */
3535
protected $sessionEndListener;
3636

3737
/** @var callable(Uuid): array<int, array{message: string, context: array<string, mixed>}> */

‎src/Server/Transport/StreamableHttpTransport.php‎

Lines changed: 21 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,14 @@ class StreamableHttpTransport extends BaseTransport implements StatelessAwareTra
5959
public const SESSION_HEADER = 'Mcp-Session-Id';
6060
public const PROTOCOL_VERSION_HEADER = 'Mcp-Protocol-Version';
6161

62+
/**
63+
* PSR-7 request attribute holding a string that identifies the authenticated principal.
64+
*
65+
* A session only serves the principal that opened it. {@see Http\Middleware\AuthorizationMiddleware}
66+
* sets it; an application authenticating requests itself sets it instead.
67+
*/
68+
public const PRINCIPAL_ATTRIBUTE = 'mcp.principal';
69+
6270
/**
6371
* Upper bound on the request body read for a POST, guarding against memory
6472
* exhaustion from an oversized (or unbounded chunked) payload.
@@ -207,10 +215,11 @@ protected function handleOptionsRequest(): ResponseInterface
207215
/**
208216
* @param string $body the request body, already read and bounded by {@see self::handleRequest()}
209217
* @param AccessToken|null $accessToken the token the request was authorized with, see {@see self::accessToken()}
218+
* @param string|null $principal the principal the request was authenticated as, see {@see self::PRINCIPAL_ATTRIBUTE}
210219
*/
211-
protected function handlePostRequest(string $body, ?AccessToken $accessToken = null): ResponseInterface
220+
protected function handlePostRequest(string $body, ?AccessToken $accessToken = null, ?string $principal = null): ResponseInterface
212221
{
213-
$this->handleMessage($body, $this->sessionId, $accessToken);
222+
$this->handleMessage($body, $this->sessionId, $accessToken, $principal);
214223

215224
// Consume the immediate response exactly once, so a transport instance
216225
// reused for a later POST does not replay it.
@@ -236,13 +245,16 @@ protected function handlePostRequest(string $body, ?AccessToken $accessToken = n
236245
return $this->createJsonResponse();
237246
}
238247

239-
protected function handleDeleteRequest(): ResponseInterface
248+
/**
249+
* @param string|null $principal the principal the request was authenticated as, see {@see self::PRINCIPAL_ATTRIBUTE}
250+
*/
251+
protected function handleDeleteRequest(?string $principal = null): ResponseInterface
240252
{
241253
if (!$this->sessionId) {
242254
return $this->createErrorResponse(Error::forInvalidRequest(self::SESSION_HEADER.' header is required.'), 400);
243255
}
244256

245-
$this->handleSessionEnd($this->sessionId);
257+
$this->handleSessionEnd($this->sessionId, $principal);
246258

247259
return $this->responseFactory->createResponse(200);
248260
}
@@ -512,9 +524,12 @@ private function handleHandshakeRequest(ServerRequestInterface $request, ?string
512524
return $this->createErrorResponse(Error::forInvalidRequest(self::SESSION_HEADER.' header must be a valid UUID.'), 400);
513525
}
514526

527+
$principal = $request->getAttribute(self::PRINCIPAL_ATTRIBUTE);
528+
$principal = \is_string($principal) && '' !== $principal ? $principal : null;
529+
515530
return match ($request->getMethod()) {
516-
'POST' => $this->handlePostRequest($body ?? '', self::accessToken($request)),
517-
'DELETE' => $this->handleDeleteRequest(),
531+
'POST' => $this->handlePostRequest($body ?? '', self::accessToken($request), $principal),
532+
'DELETE' => $this->handleDeleteRequest($principal),
518533
default => $this->createErrorResponse(Error::forInvalidRequest('Method Not Allowed'), 405),
519534
};
520535
}

‎src/Server/Transport/TransportInterface.php‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,17 +73,19 @@ public function close(): void;
7373
* The transport calls this whenever ANY message arrives, regardless of source.
7474
*
7575
* The access token is the one the message was authorized with, if the transport authorizes requests.
76+
* The principal identifies who the message was authenticated as, if the transport authenticates requests.
7677
*
77-
* @param callable(TransportInterface<TResult> $transport, string $message, ?Uuid $sessionId, ?AccessToken $accessToken): void $listener
78+
* @param callable(TransportInterface<TResult> $transport, string $message, ?Uuid $sessionId, ?AccessToken $accessToken, ?string $principal): void $listener
7879
*/
7980
public function onMessage(callable $listener): void;
8081

8182
/**
8283
* Register a listener for when a session is terminated.
8384
*
8485
* The transport calls this when a client disconnects or explicitly ends their session.
86+
* The principal identifies who ended it, if the transport authenticates requests.
8587
*
86-
* @param callable(Uuid $sessionId): void $listener The callback function to execute when destroying a session
88+
* @param callable(Uuid $sessionId, ?string $principal): void $listener The callback function to execute when destroying a session
8789
*/
8890
public function onSessionEnd(callable $listener): void;
8991

‎tests/Unit/Server/BuilderTest.php‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -222,7 +222,7 @@ public function testSetSessionLockIsWiredIntoTheProtocol(): void
222222
'{"jsonrpc":"2.0","id":2,"method":"ping"}',
223223
]));
224224

225-
$this->assertCount(11, $log, implode(', ', $log));
225+
$this->assertCount(12, $log, implode(', ', $log));
226226
$sessionId = substr($log[0], \strlen('read '));
227227
$this->assertSame([
228228
// initialize: the session is new, nobody else can know it yet
@@ -235,7 +235,8 @@ public function testSetSessionLockIsWiredIntoTheProtocol(): void
235235
"read $sessionId",
236236
"write $sessionId",
237237
"release $sessionId",
238-
// the transport ends the session when it is done
238+
// the transport ends the session when it is done, which checks who opened it first
239+
"read $sessionId",
239240
"acquire $sessionId",
240241
"destroy $sessionId",
241242
"release $sessionId",

0 commit comments

Comments
 (0)