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`
* Add `LenientOidcDiscoveryMetadataPolicy` for identity providers that omit `code_challenge_methods_supported` (e.g. FusionAuth, Microsoft Entra ID)
* Add OAuth 2.0 Dynamic Client Registration middleware (RFC 7591)

0.4.0
-----
Expand Down
38 changes: 0 additions & 38 deletions examples/server/oauth-microsoft/MicrosoftOidcMetadataPolicy.php

This file was deleted.

8 changes: 5 additions & 3 deletions examples/server/oauth-microsoft/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ curl -X POST http://localhost:8000/mcp \
- `env.example` - Environment variables template
- `server.php` - MCP server with OAuth middleware
- `MicrosoftJwtTokenValidator.php` - Example-specific validator for Graph/non-Graph tokens
- `MicrosoftOidcMetadataPolicy.php` - Lenient metadata validation policy
- Uses built-in `LenientOidcDiscoveryMetadataPolicy` for metadata validation
- `McpElements.php` - MCP tools including Graph API integration

## Environment Variables
Expand Down Expand Up @@ -198,8 +198,10 @@ 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` requires `code_challenge_methods_supported`.
Microsoft Entra ID omits this field despite supporting PKCE with S256.
This example uses the built-in `LenientOidcDiscoveryMetadataPolicy` which accepts missing
`code_challenge_methods_supported` (defaults to S256 downstream).

### Graph API errors

Expand Down
4 changes: 2 additions & 2 deletions examples/server/oauth-microsoft/server.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
use Http\Discovery\Psr17Factory;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
use Mcp\Example\Server\OAuthMicrosoft\MicrosoftJwtTokenValidator;
use Mcp\Example\Server\OAuthMicrosoft\MicrosoftOidcMetadataPolicy;
use Mcp\Server;
use Mcp\Server\Session\FileSessionStore;
use Mcp\Server\Transport\Http\Middleware\AuthorizationMiddleware;
Expand All @@ -25,6 +24,7 @@
use Mcp\Server\Transport\Http\Middleware\ProtectedResourceMetadataMiddleware;
use Mcp\Server\Transport\Http\OAuth\JwksProvider;
use Mcp\Server\Transport\Http\OAuth\JwtTokenValidator;
use Mcp\Server\Transport\Http\OAuth\LenientOidcDiscoveryMetadataPolicy;
use Mcp\Server\Transport\Http\OAuth\OidcDiscovery;
use Mcp\Server\Transport\Http\OAuth\ProtectedResourceMetadata;
use Mcp\Server\Transport\StreamableHttpTransport;
Expand All @@ -37,7 +37,7 @@
$localBaseUrl = 'http://localhost:8000';

$discovery = new OidcDiscovery(
metadataPolicy: new MicrosoftOidcMetadataPolicy(),
metadataPolicy: new LenientOidcDiscoveryMetadataPolicy(),
);

$jwtTokenValidator = new JwtTokenValidator(
Expand Down

This file was deleted.

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;
}
Loading