Skip to content
Merged
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 @@ -10,6 +10,8 @@ All notable changes to `mcp/sdk` will be documented in this file.
* Add `Builder::setReferenceHandler()` to allow custom `ReferenceHandlerInterface` implementations (e.g. authorization decorators)
* Add elicitation enum schema types per SEP-1330: `TitledEnumSchemaDefinition`, `MultiSelectEnumSchemaDefinition`, `TitledMultiSelectEnumSchemaDefinition`
* [BC break] Make Symfony Finder component optional. Users would need to install `symfony/finder` now themselves
* 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.

9 changes: 5 additions & 4 deletions examples/server/oauth-microsoft/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,9 +148,8 @@ curl -X POST http://localhost:8000/mcp \
- `Dockerfile` - PHP-FPM container
- `nginx/default.conf` - Nginx configuration
- `env.example` - Environment variables template
- `server.php` - MCP server with OAuth middleware
- `server.php` - MCP server with OAuth middleware (uses built-in `LenientOidcDiscoveryMetadataPolicy` for metadata validation)
- `MicrosoftJwtTokenValidator.php` - Example-specific validator for Graph/non-Graph tokens
- `MicrosoftOidcMetadataPolicy.php` - Lenient metadata validation policy
- `McpElements.php` - MCP tools including Graph API integration

## Environment Variables
Expand Down Expand Up @@ -198,8 +197,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.

23 changes: 23 additions & 0 deletions src/Exception/ClientRegistrationException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?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
{
public function __construct(
string $message,
public readonly string $errorCode = 'invalid_client_metadata',
?\Throwable $previous = null,
) {
parent::__construct($message, 0, $previous);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
<?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
{
$contentType = $request->getHeaderLine('Content-Type');
if (!str_starts_with($contentType, 'application/json')) {
return $this->jsonResponse(400, [
'error' => 'invalid_client_metadata',
'error_description' => 'Content-Type must be application/json.',
], ['Cache-Control' => 'no-store']);
}

$body = $request->getBody()->__toString();

try {
$decoded = json_decode($body, false, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException) {
return $this->jsonResponse(400, [
'error' => 'invalid_client_metadata',
'error_description' => 'Request body must be valid JSON.',
], ['Cache-Control' => 'no-store']);
}

if (!$decoded instanceof \stdClass) {
return $this->jsonResponse(400, [
'error' => 'invalid_client_metadata',
'error_description' => 'Request body must be a JSON object.',
], ['Cache-Control' => 'no-store']);
}

// Re-decode with assoc=true so nested objects become arrays (safe — already validated above)
/** @var array<string, mixed> $data */
$data = json_decode($body, true, 512, \JSON_THROW_ON_ERROR);

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

return $this->jsonResponse(201, $result, [
'Cache-Control' => 'no-store',
]);
}

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

$stream = $response->getBody();

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

try {
$metadata = json_decode($stream->__toString(), true, 512, \JSON_THROW_ON_ERROR);
} catch (\JsonException) {
if ($stream->isSeekable()) {
$stream->rewind();
}

return $response;
}

if (!\is_array($metadata) || ([] !== $metadata && array_is_list($metadata))) {
if ($stream->isSeekable()) {
$stream->rewind();
}

return $response;
}

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

return $response
->withBody($this->streamFactory->createStream(
json_encode($metadata, \JSON_THROW_ON_ERROR | \JSON_UNESCAPED_SLASHES),
))
->withHeader('Content-Type', 'application/json')
->withoutHeader('Content-Length');
}

/**
* @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;
}
}
Loading