php-sdk/docs/run/authorization.md
Christopher Hertel 0cd5d56164
[Docs] Render the guides with Zensical instead of phpDocumentor (#414)
* [Docs] Render guides with Zensical, deploy via GitHub Pages actions

phpDocumentor's guide renderer copies the markdown through mostly verbatim:
relative links between pages keep pointing at `*.md` targets that do not exist
in the built site, and nothing validates them, so the published guides are full
of dead links.

Zensical (the Material for MkDocs team's successor to MkDocs) resolves internal
links against the page tree and fails the build on a broken one. `zensical
build --strict` already found four dead links on the first run — three
repo-relative links escaping docs/ (fixed to point at GitHub) and one wrong
in-page anchor.

phpDocumentor stays on for the class-level API reference only; `make docs`
builds the guides into site/ and mounts the reference at site/api/, so its two
header links back to the guides now target the site root.

Deployment moves from pushing a gh-pages branch to the official GitHub Pages
actions, and from release-only to every push on main, with pull requests
building (but not deploying) so a broken link fails review instead of the site.

NOTE: this needs the repository's Pages source switched to "GitHub Actions"
(Settings -> Pages) once.

* [Docs] Adopt the Python SDK's documentation look and feel

The docs site now uses the same theme configuration as
https://py.sdk.modelcontextprotocol.io/ so the language SDKs read as one set
of docs: the MCP mark as logo and favicon, Inter/JetBrains Mono, the
black/slate palette with a three-way (system/light/dark) toggle, instant
navigation, code copy/annotate, and a right-hand table of contents.

The markdown extension set is widened to the same list (tabbed blocks,
task lists, footnotes, emoji/icons, mermaid fences), which the content
restructure builds on.

Styling is otherwise stock: no custom stylesheet, and Zensical's own
`modern` theme variant, pinned explicitly rather than left to the default.

The one departure is code highlighting, which is broken out of the box here:
Pygments only highlights PHP after a `<?php` tag, so the guides — whose code
blocks are almost all fragments — rendered as flat plain text. The `php`
lexer is extended with `startinline`, and complete-file blocks use a
`php-file` lexer that keeps the literal open tag highlighted.

* [Docs] Restructure the guides into task-oriented sections

The guides were ten flat pages, each opening with a hand-maintained table of
contents and each mixing several audiences: `mcp-elements.md` covered tools,
prompts, schema generation and handler-side logging, `transports.md` covered
both transports plus framework integration, and `server-builder.md` covered
configuration, sessions and custom message handlers.

They are now split along the same lines as the Python SDK's documentation
(https://py.sdk.modelcontextprotocol.io/), one topic per page:

  Get started        installation, first server, the Inspector
  Servers            tools, resources, resource templates, prompts,
                     completions, schema generation, registration
  Inside your handler  the ClientGateway, logging
  Running your server  builder, STDIO, HTTP, framework integration,
                     sessions, authorization
  Clients            connecting, transports, capabilities, server-initiated
                     requests, error handling
  Advanced           events, protocol extensions, custom message handlers

Prose is carried over as-is apart from the seams; what is new is the landing
page and one index page per section, which say what the section is for and
where to go next, so no page is a dead end.

The per-page "Table of Contents" lists are gone — the theme renders one from
the headings — and GitHub's `> [!IMPORTANT]` blockquotes became admonitions,
which Zensical renders as callouts rather than plain quotes.

Every code sample and factual claim was then checked against src/ and the
runnable examples, which turned up long-standing errors in the carried-over
prose. Samples that could not run: a prompt using a `system` role (MCP has
only user/assistant), `Mcp\Schema\PromptMessage` (it is under `Schema\Content`)
constructed with an array instead of a single content object,
`Mcp\Capability\Prompt\Completion\ProviderInterface` (it is
`Mcp\Capability\Completion\ProviderInterface`), `new EmbeddedResource(type:,
resource: [...])` (neither parameter exists), a `: resource` return type
(not a PHP type), `#[McpResource]` with a `{path}` variable (that is a
template), a stray quote in the builder example, a `middlewares:` argument
(it is `middleware:`), and `getRequest()->getAttribute()` in the OAuth guide
(no such method — the values arrive on the request meta). Claims corrected:
sampling's `system_prompt` option (it is `systemPrompt`), `SampleMessage`
(it is `SamplingMessage`), `Notification` called an interface (abstract
class), "parameter order matters" for URI templates (bound by name), full
RFC 6570 support (only simple `{var}`), the tool description fallback chain,
`void` returning empty content, a non-zero STDIO exit code, `ErrorEvent`
being null for parse errors, handlers being "prepended", `Psr16StoreSession`,
and PSR-3 log context being sent to the client (it is dropped). Sixteen
`examples/` paths were missing their `server/` segment.

README, the OAuth ADR and one source comment now point at the published site
instead of at markdown files that moved.

* [Docs] Run the docs workflow unfiltered, keep README links relative

The `paths:` filters were mostly noise: `src/**` had to be in the list for
the phpDocumentor build, which meant the workflow ran on nearly every PR
anyway. They also missed two real inputs — `.phpdoc/template/**` and
`composer.lock` — so a template tweak or a phpDocumentor bump could change
the rendered site without triggering a build.

README links go back to relative repo paths. The README is not part of the
Zensical site (`docs_dir` is `docs/`), so those links are only ever resolved
by GitHub and Packagist, where absolute URLs break in-repo navigation for no
gain. The site pointer and the generated API reference stay absolute.

* [Docs] Adopt the doc changes that landed on main into the new structure

Twelve commits landed while the restructure was open, seven of them touching
the flat guides this branch replaces. Renames merged on their own; the three
files that were split apart needed their new sections placed by hand:

- Connection retries, protocol version negotiation, sampling with tools and
  roots from `client.md` into `client/connecting.md` and
  `client/server-requests.md`
- `ResourceLink` and structured output from `mcp-elements.md` into
  `servers/tools.md`
- Protocol version negotiation from `server-builder.md` into
  `run/server-builder.md`

The `setMaxRetries()` note claiming the value is never acted on is gone —
#413 implemented it. Callouts became admonitions and cross-links were
repointed at the new paths, as everywhere else in this branch.

* [Docs] Document the elicitation and roots client examples

Both were missing from the examples guide: the elicitation client predates
this branch, the roots client arrived with #395.

* [Docs] Fold the 2026-07-28 lifecycle into the new structure

Main's stateless-lifecycle.md becomes a docs/lifecycle/ section, and the pages
main touched — deprecations, the middleware split, the client's modern era —
land where the restructure moved them.

* [Docs] Link the Inspector to its documentation, not its repo

* [Docs] Distribute the 2026-07-28 material into the task sections

The Python and TypeScript SDKs file each feature where the task lives and keep
only an era comparison on its own page. Follow them: input-required moves next
to the other handler concerns, caching, subscriptions and era routing to
"Running your server", and one Protocol versions page carries the rest.

* [Docs] Move protocol version negotiation onto the Protocol versions page

The builder page keeps the setProtocolVersion() knob and links out; how a
revision is agreed now sits beside the era it belongs to.

* [Docs] Slim the README to a funnel, turn Examples into an index

* [Docs] Fix the code samples and API listings flagged by the audit

* [Docs] Link the negotiation spec section at latest, not draft
2026-08-20 00:03:54 +02:00

14 KiB

Authorization

The PHP MCP SDK provides OAuth 2.1 authorization support for HTTP transports, implementing the MCP Authorization specification.

Scope: what this SDK does and does not do

The MCP server is an OAuth 2.1 Resource Server. It validates the tokens it receives and may delegate the OAuth flow to your upstream Identity Provider. It is not an authorization server and it does not issue tokens.

Role What it does Status Scope
Resource Server Validates incoming bearer tokens, serves Protected Resource Metadata (RFC 9728), emits WWW-Authenticate Supported (AuthorizationMiddleware, JwtTokenValidator, ProtectedResourceMetadata) In scope
Delegation / proxy to an upstream AS Forwards /authorize and /token to your existing IdP Supported (OAuthProxyMiddleware) In scope — delegation only
Authorization Server / Identity Provider Mints its own tokens, registers clients, runs login and consent Not implemented Out of scope: being an authorization server / issuing tokens is out of scope

To issue tokens, front the MCP server with an external IdP (Keycloak, Auth0, Microsoft Entra ID, Okta) or run league/oauth2-server in your own application, and let the MCP server validate those tokens as a Resource Server. See adr/0001-oauth-authorization-server-out-of-scope.md.

Overview

Authorization in MCP is implemented at the transport level using PSR-15 middleware. The SDK provides:

  • AuthorizationMiddleware - PSR-15 middleware that enforces bearer token authentication
  • ProtectedResourceMetadataMiddleware - Serves RFC 9728 metadata at well-known endpoints
  • OAuthProxyMiddleware - Delegates OAuth flows (/authorize, /token) to your upstream IdP; the SDK never issues tokens itself
  • OAuthRequestMetaMiddleware - Bridges HTTP OAuth attributes to JSON-RPC request meta
  • JwtTokenValidator - Validates JWT tokens using JWKS from OAuth 2.0 / OIDC providers
  • OidcDiscovery - Discovers authorization server metadata from well-known endpoints
┌─────────────┐     ┌────────────────────┐     ┌─────────────────┐
│ MCP Client  │────▶│ AuthorizationMiddleware │────▶│  MCP Handlers   │
└─────────────┘     └────────────────────┘     └─────────────────┘
      │                      │
      │                      │ Validate JWT
      ▼                      ▼
┌─────────────┐     ┌─────────────────┐
│ Auth Server │◀────│ JwtTokenValidator│
│  (Keycloak, │     │    + JWKS       │
│   Entra ID) │     └─────────────────┘
└─────────────┘

Quick Start

use Mcp\Server;
use Mcp\Server\Transport\Http\Middleware\AuthorizationMiddleware;
use Mcp\Server\Transport\Http\Middleware\OAuthRequestMetaMiddleware;
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\OidcDiscovery;
use Mcp\Server\Transport\Http\OAuth\ProtectedResourceMetadata;
use Mcp\Server\Transport\StreamableHttpTransport;

// 1. Set up OIDC discovery and JWKS provider
$discovery = new OidcDiscovery();
$jwksProvider = new JwksProvider($discovery);

// 2. Create JWT validator for your OAuth provider
$validator = new JwtTokenValidator(
    issuer: 'https://auth.example.com/realms/mcp',
    audience: 'mcp-server',
    jwksProvider: $jwksProvider,
);

// 3. Create Protected Resource Metadata (RFC 9728)
$metadata = new ProtectedResourceMetadata(
    authorizationServers: ['https://auth.example.com/realms/mcp'],
    scopesSupported: ['mcp:read', 'mcp:write'],
);

// 4. Create middleware stack
$authMiddleware = new AuthorizationMiddleware(
    validator: $validator,
    resourceMetadata: $metadata,
);

$metadataMiddleware = new ProtectedResourceMetadataMiddleware(
    metadata: $metadata,
);

// 5. Create transport with middleware
$transport = new StreamableHttpTransport(
    $request,
    middleware: [
        ...StreamableHttpTransport::defaultMiddleware(),
        $metadataMiddleware,
        $authMiddleware,
        // Bridges the OAuth attributes onto the JSON-RPC request meta, which is
        // what makes them reachable from a handler (see Scope-Based Access Control).
        new OAuthRequestMetaMiddleware(),
    ],
);

// 6. Run server
$server = Server::builder()
    ->setServerInfo('Protected MCP Server', '1.0.0')
    ->setDiscovery(__DIR__, excludeDirs: ['vendor'])
    ->build();

$response = $server->run($transport);

Components

AuthorizationMiddleware

The main middleware that enforces authentication:

$middleware = new AuthorizationMiddleware(
    validator: $validator,         // AuthorizationTokenValidatorInterface
    resourceMetadata: $metadata,   // ProtectedResourceMetadata instance
    responseFactory: null,         // PSR-17 (auto-discovered)
);

Behavior:

Request Response
Missing Authorization header 401 with WWW-Authenticate: Bearer resource_metadata="..."
Invalid/expired token 401 with error details
Valid token Passes to next handler with OAuth attributes on request

ProtectedResourceMetadataMiddleware

Serves Protected Resource Metadata at configured well-known paths:

$metadataMiddleware = new ProtectedResourceMetadataMiddleware(
    metadata: $metadata,           // ProtectedResourceMetadata instance
    responseFactory: null,         // PSR-17 (auto-discovered)
    streamFactory: null,           // PSR-17 (auto-discovered)
);

JwtTokenValidator

Validates JWT access tokens:

$validator = new JwtTokenValidator(
    issuer: 'https://auth.example.com',  // Expected issuer claim
    audience: 'mcp-server',              // Expected audience (string or array)
    jwksProvider: $jwksProvider,          // JwksProviderInterface
    jwksUri: null,                       // Explicit JWKS URI (auto-discovered)
    algorithms: ['RS256', 'RS384', 'RS512'], // Allowed algorithms (this is the default)
    scopeClaim: 'scope',                 // Claim name for scopes
);

Request Attributes:

After successful validation, these attributes are added to the request:

Attribute Description
oauth.claims All JWT claims as array
oauth.scopes Extracted scopes as array
oauth.subject The sub claim
oauth.client_id The client_id claim (if present)
oauth.authorized_party The azp claim (if present)

ProtectedResourceMetadata

Represents RFC 9728 Protected Resource Metadata:

$metadata = new ProtectedResourceMetadata(
    authorizationServers: [              // Required: authorization server URLs
        'https://auth.example.com',
    ],
    scopesSupported: [                   // Optional: supported scopes
        'mcp:read',
        'mcp:write',
    ],
    resource: 'https://mcp.example.com', // Optional: resource identifier
    resourceName: 'My MCP Server',       // Optional: human-readable name
    metadataPaths: [                     // Paths to serve metadata (default: /.well-known/oauth-protected-resource)
        '/.well-known/oauth-protected-resource',
    ],
    extra: [                             // Optional: additional fields
        'custom_field' => 'value',
    ],
);

OidcDiscovery

Discovers OAuth/OIDC server metadata:

$discovery = new OidcDiscovery(
    httpClient: null,      // PSR-18 (auto-discovered)
    requestFactory: null,  // PSR-17 (auto-discovered)
    cache: $cache,         // PSR-16 cache (optional)
    cacheTtl: 3600,        // Cache TTL
);

// Discover metadata
$metadata = $discovery->discover('https://auth.example.com/realms/mcp');

// Get specific endpoints
$jwksUri = $discovery->getJwksUri($issuer);
$tokenEndpoint = $discovery->getTokenEndpoint($issuer);
$authEndpoint = $discovery->getAuthorizationEndpoint($issuer);

JwksProvider

Fetches and caches JWKS key sets:

$jwksProvider = new JwksProvider(
    discovery: $discovery,     // OidcDiscoveryInterface
    httpClient: null,          // PSR-18 (auto-discovered)
    requestFactory: null,      // PSR-17 (auto-discovered)
    cache: $cache,             // PSR-16 cache (optional)
    cacheTtl: 3600,            // JWKS cache TTL
);

JWT Token Validation

Keycloak

$validator = new JwtTokenValidator(
    issuer: 'https://keycloak.example.com/realms/mcp',
    audience: 'mcp-server',
    jwksProvider: $jwksProvider,
);

Microsoft Entra ID (Azure AD)

$tenantId = 'your-tenant-id';
$clientId = 'your-client-id';

$validator = new JwtTokenValidator(
    issuer: "https://login.microsoftonline.com/{$tenantId}/v2.0",
    audience: $clientId,
    jwksProvider: $jwksProvider,
);

Auth0

$validator = new JwtTokenValidator(
    issuer: 'https://your-tenant.auth0.com/',
    audience: 'https://api.example.com',
    jwksProvider: $jwksProvider,
);

Okta

$validator = new JwtTokenValidator(
    issuer: 'https://your-org.okta.com/oauth2/default',
    audience: 'api://default',
    jwksProvider: $jwksProvider,
);

Protected Resource Metadata

The ProtectedResourceMetadataMiddleware serves Protected Resource Metadata at configured paths, enabling clients to discover the authorization server:

{
  "authorization_servers": ["https://auth.example.com/realms/mcp"],
  "scopes_supported": ["mcp:read", "mcp:write"],
  "resource": "https://mcp.example.com/mcp"
}

Clients request this from /.well-known/oauth-protected-resource before authenticating.

WWW-Authenticate Header

On 401 responses, the middleware includes:

WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource",
                         scope="mcp:read mcp:write"

Custom Token Validators

Implement AuthorizationTokenValidatorInterface for custom validation:

use Mcp\Server\Transport\Http\OAuth\AuthorizationTokenValidatorInterface;
use Mcp\Server\Transport\Http\OAuth\AuthorizationResult;

final class ApiKeyValidator implements AuthorizationTokenValidatorInterface
{
    public function __construct(
        private array $validKeys,
    ) {}

    public function validate(string $accessToken): AuthorizationResult
    {
        if (!isset($this->validKeys[$accessToken])) {
            return AuthorizationResult::unauthorized(
                'invalid_token',
                'Unknown API key'
            );
        }

        $keyInfo = $this->validKeys[$accessToken];

        return AuthorizationResult::allow([
            'api_key.name' => $keyInfo['name'],
            'api_key.scopes' => $keyInfo['scopes'],
        ]);
    }
}

// Usage
$validator = new ApiKeyValidator([
    'sk_live_abc123' => ['name' => 'Production', 'scopes' => ['read', 'write']],
]);

AuthorizationResult

Factory methods for different outcomes:

// Allow access with attributes
AuthorizationResult::allow(['user_id' => '123']);

// Deny - missing/invalid token (401)
AuthorizationResult::unauthorized('invalid_token', 'Token expired');

// Deny - valid token but insufficient permissions (403)
AuthorizationResult::forbidden('insufficient_scope', 'Requires admin scope', ['admin']);

// Deny - malformed request (400)
AuthorizationResult::badRequest('invalid_request', 'Malformed header');

Scope-Based Access Control

Checking Scopes in Handlers

#[McpTool(name: 'admin_action')]
public function adminAction(RequestContext $context): array
{
    // The OAuth attributes arrive on the request meta, under the `oauth` key.
    // This requires OAuthRequestMetaMiddleware in the transport's middleware stack.
    $meta = $context->getRequest()->getMeta() ?? [];
    $scopes = $meta['oauth']['oauth.scopes'] ?? [];

    if (!in_array('mcp:admin', $scopes, true)) {
        throw new \RuntimeException('Admin scope required');
    }

    // Perform admin action
    return ['status' => 'success'];
}

Using JwtTokenValidator::requireScopes

// In a custom middleware or handler
$result = $validator->validate($token);

if ($result->isAllowed()) {
    // Check for specific scopes
    $result = $validator->requireScopes($result, ['mcp:write']);
}

if (!$result->isAllowed()) {
    // Handle insufficient scope (returns 403)
}

Examples

Complete working examples are available in the examples/server/ directory:

Keycloak Example

cd examples/server/oauth-keycloak
docker-compose up -d

# Test credentials: demo / demo123

See oauth-keycloak/README.md

Microsoft Entra ID Example

cd examples/server/oauth-microsoft
cp env.example .env
# Edit .env with your Azure credentials
docker-compose up -d

See oauth-microsoft/README.md

Security Considerations

  1. Always use HTTPS in production for token transmission
  2. Validate audience claims to prevent token confusion attacks
  3. Use short-lived tokens and implement token refresh
  4. Cache JWKS to reduce latency but allow for key rotation
  5. Never log tokens - log only non-sensitive claims like subject
  6. Validate scopes before performing sensitive operations

Troubleshooting

"Invalid issuer" error

The iss claim in the token must exactly match the configured issuer URL, including trailing slashes.

"Invalid audience" error

Check the aud claim matches your configured audience. Some providers use the client ID, others use a custom URI.

JWKS fetch timeout

  • Ensure network connectivity to the authorization server
  • Consider using a cache to reduce dependency on the auth server
  • Check firewall rules allow outbound HTTPS

Token expired

  • Check clock synchronization between servers
  • Tokens typically have a 5-minute clock skew tolerance
  • Ensure clients refresh tokens before expiration