Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ All notable changes to `mcp/sdk` will be documented in this file.
* Add client component for building MCP clients
* Add `Builder::setReferenceHandler()` to allow custom `ReferenceHandlerInterface` implementations (e.g. authorization decorators)
* Add elicitation enum schema types per SEP-1330: `TitledEnumSchemaDefinition`, `MultiSelectEnumSchemaDefinition`, `TitledMultiSelectEnumSchemaDefinition`
* Allow `StrictOidcDiscoveryMetadataPolicy` to accept metadata without `code_challenge_methods_supported` (defaults to S256 downstream)
* Add OAuth 2.0 Dynamic Client Registration middleware (RFC 7591)

0.4.0
-----
Expand Down
5 changes: 3 additions & 2 deletions examples/server/oauth-microsoft/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,9 @@ Microsoft's JWKS endpoint is public. Ensure your container can reach:

### `code_challenge_methods_supported` missing in discovery metadata

This example configures `OidcDiscovery` with `MicrosoftOidcMetadataPolicy`, so this
field can be missing or malformed and will not fail discovery.
The default `StrictOidcDiscoveryMetadataPolicy` accepts metadata without `code_challenge_methods_supported`
(defaults to S256 downstream). The `MicrosoftOidcMetadataPolicy` in this example demonstrates
how to implement a custom policy via `OidcDiscoveryMetadataPolicyInterface`.

### Graph API errors

Expand Down
16 changes: 16 additions & 0 deletions src/Exception/ClientRegistrationException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?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\Exception;

final class ClientRegistrationException extends \RuntimeException implements ExceptionInterface
{
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
<?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\Server\Transport\Http\Middleware;

use Http\Discovery\Psr17FactoryDiscovery;
use Mcp\Exception\ClientRegistrationException;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Server\Transport\Http\OAuth\ClientRegistrarInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamFactoryInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
* OAuth 2.0 Dynamic Client Registration (RFC 7591) middleware.
*
* Handles POST /register requests by delegating to a ClientRegistrarInterface
* and enriches /.well-known/oauth-authorization-server responses with the
* registration_endpoint.
*/
final class ClientRegistrationMiddleware implements MiddlewareInterface
{
private const REGISTRATION_PATH = '/register';

private ResponseFactoryInterface $responseFactory;
private StreamFactoryInterface $streamFactory;

public function __construct(
private readonly ClientRegistrarInterface $registrar,
private readonly string $localBaseUrl,
?ResponseFactoryInterface $responseFactory = null,
?StreamFactoryInterface $streamFactory = null,
) {
if ('' === trim($localBaseUrl)) {
throw new InvalidArgumentException('The $localBaseUrl must not be empty.');
}

$this->responseFactory = $responseFactory ?? Psr17FactoryDiscovery::findResponseFactory();
$this->streamFactory = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory();
}

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$path = $request->getUri()->getPath();

if ('POST' === $request->getMethod() && self::REGISTRATION_PATH === $path) {
return $this->handleRegistration($request);
}

$response = $handler->handle($request);

if ('GET' === $request->getMethod() && '/.well-known/oauth-authorization-server' === $path) {
return $this->enrichAuthServerMetadata($response);
}

return $response;
}

private function handleRegistration(ServerRequestInterface $request): ResponseInterface
{
$body = $request->getBody()->__toString();
$data = json_decode($body, true);

if (!\is_array($data)) {
return $this->jsonResponse(400, [
'error' => 'invalid_client_metadata',
'error_description' => 'Request body must be valid JSON.',
]);
}

try {
$result = $this->registrar->register($data);
} catch (ClientRegistrationException $e) {
return $this->jsonResponse(400, [
'error' => 'invalid_client_metadata',
'error_description' => $e->getMessage(),
]);
}

return $this->jsonResponse(201, $result);
}

private function enrichAuthServerMetadata(ResponseInterface $response): ResponseInterface
{
if (200 !== $response->getStatusCode()) {
return $response;
}

$stream = $response->getBody();

if ($stream->isSeekable()) {
$stream->rewind();
}

$metadata = json_decode($stream->__toString(), true);

if (!\is_array($metadata)) {
return $response;
}

$metadata['registration_endpoint'] = rtrim($this->localBaseUrl, '/').self::REGISTRATION_PATH;

return $this->jsonResponse(200, $metadata, [
'Cache-Control' => $response->getHeaderLine('Cache-Control'),
]);
}

/**
* @param array<string, mixed> $data
* @param array<string, string> $extraHeaders
*/
private function jsonResponse(int $status, array $data, array $extraHeaders = []): ResponseInterface
{
$response = $this->responseFactory
->createResponse($status)
->withHeader('Content-Type', 'application/json')
->withBody($this->streamFactory->createStream(
json_encode($data, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES),
));

foreach ($extraHeaders as $name => $value) {
if ('' !== $value) {
$response = $response->withHeader($name, $value);
}
}

return $response;
}
}
42 changes: 42 additions & 0 deletions src/Server/Transport/Http/OAuth/ClientRegistrarInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
<?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\Server\Transport\Http\OAuth;

use Mcp\Exception\ClientRegistrationException;

/**
* Interface for OAuth 2.0 Dynamic Client Registration (RFC 7591).
*
* Implementations are responsible for persisting client credentials and
* returning a registration response as defined in RFC 7591 Section 3.2.
*
* @see https://datatracker.ietf.org/doc/html/rfc7591
*/
interface ClientRegistrarInterface
{
/**
* Registers a new OAuth 2.0 client.
*
* The registration request contains metadata fields as defined in RFC 7591
* Section 2 (e.g. redirect_uris, client_name, token_endpoint_auth_method).
*
* The returned array MUST include at least "client_id" and should include
* "client_secret" when the token endpoint auth method requires one.
*
* @param array<string, mixed> $registrationRequest Client metadata from the registration request body
*
* @return array<string, mixed> Registration response including client_id and optional client_secret
*
* @throws ClientRegistrationException If registration fails (e.g. invalid metadata, storage error)
*/
public function register(array $registrationRequest): array;
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,19 +28,20 @@ public function isValid(mixed $metadata): bool
|| '' === trim($metadata['token_endpoint'])
|| !\is_string($metadata['jwks_uri'])
|| '' === trim($metadata['jwks_uri'])
|| !isset($metadata['code_challenge_methods_supported'])
) {
return false;
}

if (!\is_array($metadata['code_challenge_methods_supported']) || [] === $metadata['code_challenge_methods_supported']) {
return false;
}

foreach ($metadata['code_challenge_methods_supported'] as $method) {
if (!\is_string($method) || '' === trim($method)) {
if (isset($metadata['code_challenge_methods_supported'])) {
if (!\is_array($metadata['code_challenge_methods_supported']) || [] === $metadata['code_challenge_methods_supported']) {
return false;
}

foreach ($metadata['code_challenge_methods_supported'] as $method) {
if (!\is_string($method) || '' === trim($method)) {
return false;
}
}
}

return true;
Expand Down
Loading