[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
This commit is contained in:
parent
7fe88677ad
commit
0cd5d56164
10 changed files with 4245 additions and 4069 deletions
447
docs/run/authorization.md
Normal file
447
docs/run/authorization.md
Normal file
|
|
@ -0,0 +1,447 @@
|
|||
# Authorization
|
||||
|
||||
The PHP MCP SDK provides OAuth 2.1 authorization support for HTTP transports, implementing the
|
||||
[MCP Authorization specification](https://modelcontextprotocol.io/specification/2025-11-25/basic/authorization).
|
||||
|
||||
## 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](https://github.com/modelcontextprotocol/php-sdk/blob/main/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
|
||||
|
||||
```php
|
||||
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:
|
||||
|
||||
```php
|
||||
$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:
|
||||
|
||||
```php
|
||||
$metadataMiddleware = new ProtectedResourceMetadataMiddleware(
|
||||
metadata: $metadata, // ProtectedResourceMetadata instance
|
||||
responseFactory: null, // PSR-17 (auto-discovered)
|
||||
streamFactory: null, // PSR-17 (auto-discovered)
|
||||
);
|
||||
```
|
||||
|
||||
### JwtTokenValidator
|
||||
|
||||
Validates JWT access tokens:
|
||||
|
||||
```php
|
||||
$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:
|
||||
|
||||
```php
|
||||
$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:
|
||||
|
||||
```php
|
||||
$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:
|
||||
|
||||
```php
|
||||
$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
|
||||
|
||||
```php
|
||||
$validator = new JwtTokenValidator(
|
||||
issuer: 'https://keycloak.example.com/realms/mcp',
|
||||
audience: 'mcp-server',
|
||||
jwksProvider: $jwksProvider,
|
||||
);
|
||||
```
|
||||
|
||||
### Microsoft Entra ID (Azure AD)
|
||||
|
||||
```php
|
||||
$tenantId = 'your-tenant-id';
|
||||
$clientId = 'your-client-id';
|
||||
|
||||
$validator = new JwtTokenValidator(
|
||||
issuer: "https://login.microsoftonline.com/{$tenantId}/v2.0",
|
||||
audience: $clientId,
|
||||
jwksProvider: $jwksProvider,
|
||||
);
|
||||
```
|
||||
|
||||
### Auth0
|
||||
|
||||
```php
|
||||
$validator = new JwtTokenValidator(
|
||||
issuer: 'https://your-tenant.auth0.com/',
|
||||
audience: 'https://api.example.com',
|
||||
jwksProvider: $jwksProvider,
|
||||
);
|
||||
```
|
||||
|
||||
### Okta
|
||||
|
||||
```php
|
||||
$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:
|
||||
|
||||
```json
|
||||
{
|
||||
"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:
|
||||
|
||||
```php
|
||||
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:
|
||||
|
||||
```php
|
||||
// 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
|
||||
|
||||
```php
|
||||
#[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
|
||||
|
||||
```php
|
||||
// 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
|
||||
|
||||
```bash
|
||||
cd examples/server/oauth-keycloak
|
||||
docker-compose up -d
|
||||
|
||||
# Test credentials: demo / demo123
|
||||
```
|
||||
|
||||
See [oauth-keycloak/README.md](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/server/oauth-keycloak/README.md)
|
||||
|
||||
### Microsoft Entra ID Example
|
||||
|
||||
```bash
|
||||
cd examples/server/oauth-microsoft
|
||||
cp env.example .env
|
||||
# Edit .env with your Azure credentials
|
||||
docker-compose up -d
|
||||
```
|
||||
|
||||
See [oauth-microsoft/README.md](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/server/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
|
||||
28
docs/run/caching.md
Normal file
28
docs/run/caching.md
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
# Caching
|
||||
|
||||
> Caching hints belong to protocol revision `2026-07-28`; see [Protocol versions](../protocol-versions.md).
|
||||
> A handshake-era client is served by the same server and simply never sees them.
|
||||
|
||||
`server/discover`, the four list methods and `resources/read` **must** carry `ttlMs` and
|
||||
`cacheScope`. The default is `ttlMs: 0, cacheScope: "private"` — conformant, and a flat
|
||||
refusal to let anything be cached. Say what you actually mean:
|
||||
|
||||
```php
|
||||
use Mcp\Schema\Enum\CacheScope;
|
||||
use Mcp\Server\Wire\CachePolicy;
|
||||
|
||||
->setCachePolicy(
|
||||
CachePolicy::default(30_000)
|
||||
->withMethod('tools/list', 3_600_000, CacheScope::Public)
|
||||
->withMethod('server/discover', 3_600_000, CacheScope::Public),
|
||||
)
|
||||
```
|
||||
|
||||
`public` lets a shared proxy serve one caller's answer to another, so use it only for
|
||||
results that do not vary by caller. Only the operator can make that call, which is why the
|
||||
conservative default stands until you change it.
|
||||
|
||||
A `ReadResourceResult` may set its own `ttlMs`/`cacheScope`, which win over the policy.
|
||||
|
||||
Results produced by an [MRTR retry](../handlers/input-required.md) are never given hints: their inputs
|
||||
are not part of any cache key.
|
||||
202
docs/run/framework-integration.md
Normal file
202
docs/run/framework-integration.md
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
# Framework integration
|
||||
|
||||
The HTTP transport is a PSR-7 request handler, not a web server. This page
|
||||
covers how it fits into an application you already have.
|
||||
|
||||
## Architecture
|
||||
|
||||
The HTTP transport doesn't run its own web server. Instead, it processes PSR-7 requests and returns PSR-7 responses that
|
||||
your application can handle however it needs to:
|
||||
|
||||
```
|
||||
Your Web App → PSR-7 Request → StreamableHttpTransport → PSR-7 Response → Your Web App
|
||||
```
|
||||
|
||||
This design allows integration with any PHP framework or application that supports PSR-7.
|
||||
|
||||
## Basic Usage (Standalone)
|
||||
|
||||
Here's a simplified example using PSR-17 discovery and Laminas emitter:
|
||||
|
||||
```php
|
||||
use Http\Discovery\Psr17Factory;
|
||||
use Mcp\Server;
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
use Mcp\Server\Session\FileSessionStore;
|
||||
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
|
||||
|
||||
$psr17Factory = new Psr17Factory();
|
||||
$request = $psr17Factory->createServerRequestFromGlobals();
|
||||
|
||||
$server = Server::builder()
|
||||
->setServerInfo('HTTP Server', '1.0.0')
|
||||
->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor'])
|
||||
->setSession(new FileSessionStore(__DIR__ . '/sessions')) // HTTP needs persistent sessions
|
||||
->build();
|
||||
|
||||
$transport = new StreamableHttpTransport($request);
|
||||
|
||||
$response = $server->run($transport);
|
||||
|
||||
(new SapiEmitter())->emit($response);
|
||||
```
|
||||
|
||||
## Framework Integration
|
||||
|
||||
### Symfony Integration
|
||||
|
||||
First install the required PSR libraries:
|
||||
|
||||
```bash
|
||||
composer require symfony/psr-http-message-bridge nyholm/psr7
|
||||
```
|
||||
|
||||
Then create a controller that uses Symfony's PSR-7 bridge:
|
||||
|
||||
> **Note**: This example assumes your MCP `Server` instance is configured in Symfony's service container.
|
||||
|
||||
```php
|
||||
// In a Symfony controller
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Bridge\PsrHttpMessage\Factory\PsrHttpFactory;
|
||||
use Symfony\Bridge\PsrHttpMessage\Factory\HttpFoundationFactory;
|
||||
use Mcp\Server;
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
|
||||
class McpController
|
||||
{
|
||||
#[Route('/mcp', name: 'mcp_endpoint')]
|
||||
public function handle(Request $request, Server $server): Response
|
||||
{
|
||||
// Convert Symfony request to PSR-7 (PSR-17 factories auto-discovered)
|
||||
$psrHttpFactory = new PsrHttpFactory();
|
||||
$httpFoundationFactory = new HttpFoundationFactory();
|
||||
$psrRequest = $psrHttpFactory->createRequest($request);
|
||||
|
||||
// Process with MCP (factories auto-discovered)
|
||||
$transport = new StreamableHttpTransport($psrRequest);
|
||||
$psrResponse = $server->run($transport);
|
||||
|
||||
// Convert PSR-7 response back to Symfony
|
||||
return $httpFoundationFactory->createResponse($psrResponse);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Laravel Integration
|
||||
|
||||
First install the required PSR libraries:
|
||||
|
||||
```bash
|
||||
composer require symfony/psr-http-message-bridge nyholm/psr7
|
||||
```
|
||||
|
||||
Then create a controller that type-hints `ServerRequestInterface`:
|
||||
|
||||
> **Note**: This example assumes your MCP `Server` instance is constructed and bound in a Laravel service provider for dependency injection.
|
||||
|
||||
```php
|
||||
// In a Laravel controller
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Mcp\Server;
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
|
||||
class McpController
|
||||
{
|
||||
public function handle(ServerRequestInterface $request, Server $server): ResponseInterface
|
||||
{
|
||||
// Create the MCP HTTP transport
|
||||
$transport = new StreamableHttpTransport($request);
|
||||
|
||||
// Process MCP request and return PSR-7 response
|
||||
// Laravel automatically handles PSR-7 responses
|
||||
return $server->run($transport);
|
||||
}
|
||||
}
|
||||
|
||||
// Route registration
|
||||
Route::any('/mcp', [McpController::class, 'handle']);
|
||||
```
|
||||
|
||||
### Slim Framework Integration
|
||||
|
||||
Slim Framework works natively with PSR-7.
|
||||
|
||||
Create a route handler using Slim's built-in factories and container:
|
||||
|
||||
```php
|
||||
use Slim\Factory\AppFactory;
|
||||
use Mcp\Server;
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
|
||||
$app = AppFactory::create();
|
||||
|
||||
$app->any('/mcp', function ($request, $response) {
|
||||
$server = Server::builder()
|
||||
->setServerInfo('My MCP Server', '1.0.0')
|
||||
->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor'])
|
||||
->build();
|
||||
|
||||
$transport = new StreamableHttpTransport($request);
|
||||
|
||||
return $server->run($transport);
|
||||
});
|
||||
```
|
||||
|
||||
## HTTP Method Handling
|
||||
|
||||
The transport handles all HTTP methods automatically:
|
||||
|
||||
- **POST**: Send MCP requests
|
||||
- **GET**: Not implemented (returns 405)
|
||||
- **DELETE**: End session
|
||||
- **OPTIONS**: CORS preflight
|
||||
|
||||
You should route **all methods** to your MCP endpoint, not just POST.
|
||||
|
||||
## Session Management
|
||||
|
||||
HTTP transport requires persistent sessions since PHP doesn't maintain state between requests. Unlike STDIO transport
|
||||
where in-memory sessions work fine, HTTP transport needs a persistent session store:
|
||||
|
||||
```php
|
||||
use Mcp\Server\Session\FileSessionStore;
|
||||
|
||||
// ✅ Good for HTTP
|
||||
$server = Server::builder()
|
||||
->setSession(new FileSessionStore(__DIR__ . '/sessions'))
|
||||
->build();
|
||||
|
||||
// ❌ Not recommended for HTTP (sessions lost between requests)
|
||||
$server = Server::builder()
|
||||
->setSession(new InMemorySessionStore())
|
||||
->build();
|
||||
```
|
||||
|
||||
## Recommended Route
|
||||
|
||||
It's recommended to mount the MCP endpoint at `/mcp`, but this is not enforced:
|
||||
|
||||
```php
|
||||
// Recommended
|
||||
Route::any('/mcp', [McpController::class, 'handle']);
|
||||
|
||||
// Also valid
|
||||
Route::any('/', [McpController::class, 'handle']);
|
||||
Route::any('/api/mcp', [McpController::class, 'handle']);
|
||||
```
|
||||
|
||||
## Testing HTTP Transport
|
||||
|
||||
Use the MCP Inspector to test HTTP servers:
|
||||
|
||||
```bash
|
||||
# Start your PHP server
|
||||
php -S localhost:8000 server.php
|
||||
|
||||
# Connect with MCP Inspector
|
||||
npx @modelcontextprotocol/inspector http://localhost:8000
|
||||
```
|
||||
260
docs/run/http.md
Normal file
260
docs/run/http.md
Normal file
|
|
@ -0,0 +1,260 @@
|
|||
# HTTP Transport
|
||||
|
||||
The HTTP transport was designed to sit between any PHP project, regardless of the HTTP implementation or how they receive
|
||||
and process requests and send responses. It provides a flexible architecture that can integrate with any PSR-7 compatible application.
|
||||
|
||||
```php
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
|
||||
// PSR-17 factories are automatically discovered
|
||||
$transport = new StreamableHttpTransport(
|
||||
request: $serverRequest, // PSR-7 server request
|
||||
responseFactory: null, // Optional: PSR-17 response factory (auto-discovered if null)
|
||||
streamFactory: null, // Optional: PSR-17 stream factory (auto-discovered if null)
|
||||
logger: $logger // Optional PSR-3 logger
|
||||
);
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
- **`request`** (required): `ServerRequestInterface` - The incoming PSR-7 HTTP request
|
||||
- **`responseFactory`** (optional): `ResponseFactoryInterface` - PSR-17 factory for creating HTTP responses. Auto-discovered if not provided.
|
||||
- **`streamFactory`** (optional): `StreamFactoryInterface` - PSR-17 factory for creating response body streams. Auto-discovered if not provided.
|
||||
- **`logger`** (optional): `LoggerInterface` - PSR-3 logger for debugging. Defaults to `NullLogger`.
|
||||
- **`middleware`** (optional): `iterable<MiddlewareInterface>|null` - PSR-15 middleware chain. `null` (omitted) installs the [default stack](#default-middleware). `[]` disables all defaults — useful when the surrounding application already handles CORS, host validation, etc.
|
||||
- **`maxBodyBytes`** (optional): `int` - Upper bound on the POST request body read, in bytes. Defaults to 4 MiB (`StreamableHttpTransport::DEFAULT_MAX_BODY_BYTES`). See [Request Body Size Limit](#request-body-size-limit).
|
||||
|
||||
## PSR-17 Auto-Discovery
|
||||
|
||||
The transport automatically discovers PSR-17 factory implementations from these popular packages:
|
||||
|
||||
- `nyholm/psr7`
|
||||
- `guzzlehttp/psr7`
|
||||
- `slim/psr7`
|
||||
- `laminas/laminas-diactoros`
|
||||
- And other PSR-17 compatible implementations
|
||||
|
||||
```bash
|
||||
# Install any PSR-17 package - discovery works automatically
|
||||
composer require nyholm/psr7
|
||||
```
|
||||
|
||||
If auto-discovery fails or you want to use a specific implementation, you can pass factories explicitly:
|
||||
|
||||
```php
|
||||
use Nyholm\Psr7\Factory\Psr17Factory;
|
||||
|
||||
$psr17Factory = new Psr17Factory();
|
||||
$transport = new StreamableHttpTransport($request, $psr17Factory, $psr17Factory);
|
||||
```
|
||||
|
||||
## Default Middleware
|
||||
|
||||
When the `middleware` argument is omitted (or set to `null`), the transport installs a secure default stack:
|
||||
|
||||
| Order | Middleware | Purpose |
|
||||
|-------|------------|---------|
|
||||
| 1 | `CorsMiddleware` | Applies CORS headers to every response. By default does **not** set `Access-Control-Allow-Origin` (cross-origin requests are blocked). |
|
||||
| 2 | `DnsRebindingProtectionMiddleware` | Validates `Origin`/`Host` against an allowlist. Defaults to localhost variants only. |
|
||||
|
||||
```php
|
||||
// Zero-config, secure-by-default — local servers get full protection automatically.
|
||||
$transport = new StreamableHttpTransport($request);
|
||||
```
|
||||
|
||||
The default stack can be inspected and recomposed via the public factory:
|
||||
|
||||
```php
|
||||
$middleware = StreamableHttpTransport::defaultMiddleware();
|
||||
```
|
||||
|
||||
These run at the edge, before the request's protocol era is known, because what they enforce is true of
|
||||
both eras. `ProtocolVersionMiddleware` is not in that stack: the `MCP-Protocol-Version` header rule belongs
|
||||
to the handshake era, so the transport applies it only to requests it classified as handshake-era traffic,
|
||||
and the modern leg answers for its own revisions. It is available as
|
||||
`StreamableHttpTransport::handshakeMiddleware()` and is applied whether or not you replace the edge stack.
|
||||
See [Serving both eras](protocol-eras.md).
|
||||
|
||||
## CORS Configuration
|
||||
|
||||
CORS is handled by `CorsMiddleware`. To enable cross-origin browser requests, configure it explicitly and pass it
|
||||
in place of (or alongside) the defaults:
|
||||
|
||||
```php
|
||||
use Mcp\Server\Transport\Http\Middleware\CorsMiddleware;
|
||||
use Mcp\Server\Transport\Http\Middleware\DnsRebindingProtectionMiddleware;
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
|
||||
// Reflect a specific origin
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
middleware: [
|
||||
new CorsMiddleware(allowedOrigins: ['https://myapp.com']),
|
||||
new DnsRebindingProtectionMiddleware(),
|
||||
],
|
||||
);
|
||||
|
||||
// Allow all origins (development only)
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
middleware: [
|
||||
new CorsMiddleware(allowedOrigins: ['*']),
|
||||
new DnsRebindingProtectionMiddleware(),
|
||||
],
|
||||
);
|
||||
```
|
||||
|
||||
When the allowlist is a concrete set of origins (not `['*']`), `CorsMiddleware` automatically adds `Vary: Origin`
|
||||
so shared caches/CDNs do not serve a response generated for one origin to a request from another.
|
||||
|
||||
Headers already present on a response (e.g. set by inner middleware) are preserved — `CorsMiddleware` only adds
|
||||
defaults when they are absent.
|
||||
|
||||
!!! warning
|
||||
`Access-Control-Allow-Origin: *` is incompatible with credentialed browser requests (those carrying
|
||||
`Authorization`, cookies, or client certificates). If your MCP server runs OAuth/Bearer auth and serves
|
||||
a browser client, configure `allowedOrigins` with the explicit origin(s) you trust rather than `['*']`.
|
||||
The middleware reflects the matching origin verbatim, which is the form browsers accept with credentials.
|
||||
|
||||
## DNS Rebinding Protection
|
||||
|
||||
`DnsRebindingProtectionMiddleware` validates the `Origin` header against an allowlist (falling back to `Host`
|
||||
when `Origin` is absent). The default allowlist is localhost-only:
|
||||
|
||||
```php
|
||||
use Mcp\Server\Transport\Http\Middleware\DnsRebindingProtectionMiddleware;
|
||||
|
||||
new DnsRebindingProtectionMiddleware(allowedHosts: ['myapp.local', 'mcp.internal']);
|
||||
```
|
||||
|
||||
If the server is fronted by a reverse proxy that already validates `Host`, drop this middleware from the chain
|
||||
or supply a permissive allowlist.
|
||||
|
||||
## Protocol Version Validation
|
||||
|
||||
`ProtocolVersionMiddleware` rejects requests whose `MCP-Protocol-Version` header is not in the SDK's supported
|
||||
set with `400 Bad Request`. Requests without the header pass through, since the `initialize` round-trip and some
|
||||
legacy clients do not send it.
|
||||
|
||||
It is applied by the transport itself, to handshake-era traffic only — do not add it to a custom `middleware`
|
||||
list, where it would run before the era is classified and reject every modern-era request. Construct it
|
||||
yourself only to narrow the supported set on a server that also pins its handshake:
|
||||
|
||||
```php
|
||||
use Mcp\Schema\Enum\ProtocolVersion;
|
||||
use Mcp\Server\Transport\Http\Middleware\ProtocolVersionMiddleware;
|
||||
|
||||
// Only accept the latest spec version
|
||||
new ProtocolVersionMiddleware(supportedVersions: [ProtocolVersion::V2025_11_25]);
|
||||
```
|
||||
|
||||
The default set is `ProtocolVersion::handshakeVersions()` — every revision the server can actually negotiate over
|
||||
`initialize`, rather than every revision the enum declares. A request without the header is treated as
|
||||
`ProtocolVersion::DEFAULT_HEADER_VERSION` (`2025-03-26`), the revision that introduced both Streamable HTTP and the
|
||||
header itself, so a header-less request cannot be newer than that.
|
||||
|
||||
This header check is separate from, and happens after, the handshake itself. See
|
||||
[Protocol versions](../protocol-versions.md#negotiating-in-the-handshake-era) for how the revision is agreed in the
|
||||
first place. Being separate also means it is unaffected by `setProtocolVersion()`: the middleware validates against
|
||||
the set it was constructed with, not against the revision a given session negotiated, so a server that pins the
|
||||
handshake has to pass that revision here as well.
|
||||
|
||||
Modern revisions never reach it. A `2026-07-28` request declares its revision in `params._meta` rather than in a
|
||||
header, and is routed away from this check entirely — see
|
||||
[Serving both eras](protocol-eras.md).
|
||||
|
||||
## Request Body Size Limit
|
||||
|
||||
`StreamableHttpTransport` caps the POST body it reads to guard against memory exhaustion from an oversized or
|
||||
unbounded (chunked) payload. The default cap is 4 MiB. A body over the cap is rejected with `413` and never reaches
|
||||
message parsing.
|
||||
|
||||
```php
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
|
||||
// Raise the cap to 16 MiB
|
||||
$transport = new StreamableHttpTransport($request, maxBodyBytes: 16 * 1024 * 1024);
|
||||
```
|
||||
|
||||
When the request stream advertises a size, the transport rejects it up-front. Otherwise (e.g. chunked transfer with
|
||||
unknown size) the body is read incrementally and aborted as soon as it crosses the cap, so an unbounded stream cannot
|
||||
exhaust memory. A value below `1` throws `InvalidArgumentException`.
|
||||
|
||||
## JSON-RPC Batch Size Limit
|
||||
|
||||
A JSON-RPC batch (top-level array) is capped at 100 messages. Oversized batches are rejected before any
|
||||
message is constructed, so a single small request cannot amplify into arbitrarily many operations. The cap
|
||||
lives on `Mcp\JsonRpc\MessageFactory` and is not currently configurable through the builder — a server built
|
||||
with `Server::builder()` always uses the default of 100.
|
||||
|
||||
Single-message vs batch is determined from the decoded JSON type — a JSON object is a single message, a JSON array
|
||||
is a batch. Scalars, empty payloads, and non-object batch elements are returned as `InvalidInputMessageException`
|
||||
entries (the existing per-message error contract), not parse errors or crashes. A `maxBatchSize` below `1` throws
|
||||
`InvalidArgumentException`.
|
||||
|
||||
## Custom PSR-15 Middleware
|
||||
|
||||
`StreamableHttpTransport` accepts any PSR-15 middleware chain. To extend the defaults, spread them and append
|
||||
your own middleware — the defaults stay outermost so CORS headers are applied to every response, including
|
||||
short-circuited ones:
|
||||
|
||||
```php
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
use Psr\Http\Message\ResponseFactoryInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Psr\Http\Message\ServerRequestInterface;
|
||||
use Psr\Http\Server\MiddlewareInterface;
|
||||
use Psr\Http\Server\RequestHandlerInterface;
|
||||
|
||||
final class AuthMiddleware implements MiddlewareInterface
|
||||
{
|
||||
public function __construct(private ResponseFactoryInterface $responses)
|
||||
{
|
||||
}
|
||||
|
||||
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
|
||||
{
|
||||
if (!$request->hasHeader('Authorization')) {
|
||||
return $this->responses->createResponse(401);
|
||||
}
|
||||
|
||||
return $handler->handle($request);
|
||||
}
|
||||
}
|
||||
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
logger: $logger,
|
||||
middleware: [
|
||||
...StreamableHttpTransport::defaultMiddleware(),
|
||||
new AuthMiddleware($responseFactory),
|
||||
],
|
||||
);
|
||||
```
|
||||
|
||||
To selectively drop one default (for example DNS rebinding when running behind a proxy), filter the default list:
|
||||
|
||||
```php
|
||||
use Mcp\Server\Transport\Http\Middleware\DnsRebindingProtectionMiddleware;
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
middleware: [
|
||||
...array_filter(
|
||||
StreamableHttpTransport::defaultMiddleware(),
|
||||
fn ($m) => !$m instanceof DnsRebindingProtectionMiddleware,
|
||||
),
|
||||
new AuthMiddleware($responseFactory),
|
||||
],
|
||||
);
|
||||
```
|
||||
|
||||
Pass `middleware: []` to disable every default and run only your own chain:
|
||||
|
||||
```php
|
||||
$transport = new StreamableHttpTransport(
|
||||
$request,
|
||||
middleware: [new AuthMiddleware($responseFactory)],
|
||||
);
|
||||
```
|
||||
41
docs/run/index.md
Normal file
41
docs/run/index.md
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
# Running your server
|
||||
|
||||
`Server::builder()` configures a server; `run()` puts it on a transport and starts
|
||||
answering. Every transport implements `TransportInterface` and is used the same way:
|
||||
|
||||
```php
|
||||
$server = Server::builder()
|
||||
->setServerInfo('My Server', '1.0.0')
|
||||
->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor'])
|
||||
->build();
|
||||
|
||||
$transport = new SomeTransport();
|
||||
|
||||
$result = $server->run($transport); // Blocks for STDIO, returns a response for HTTP
|
||||
```
|
||||
|
||||
## Choosing a transport
|
||||
|
||||
The choice depends on the client you want to integrate with:
|
||||
|
||||
* The client runs **locally** and launches your server as a subprocess (Claude Desktop,
|
||||
most editors) → **[STDIO](stdio.md)**.
|
||||
* The client is **remote**, or your server lives in a web application →
|
||||
**[HTTP](http.md)**, the Streamable HTTP transport.
|
||||
|
||||
The rest of this section:
|
||||
|
||||
* **[Server builder](server-builder.md)** — every configuration knob: server info,
|
||||
discovery, dependency injection, logging, pagination.
|
||||
* **[Framework integration](framework-integration.md)** — mounting the HTTP transport in
|
||||
a Symfony, Laravel, or Slim application, or running it standalone.
|
||||
* **[Sessions](sessions.md)** — where per-client state lives, which matters as soon as
|
||||
you serve HTTP from more than one process.
|
||||
* **[Serving both eras](protocol-eras.md)** — the same endpoint also answers protocol
|
||||
revision `2026-07-28`, which has no handshake and no sessions; what a modern request
|
||||
carries, and how each one is routed.
|
||||
* **[Caching](caching.md)** — the `ttlMs` / `cacheScope` hints a modern-era result carries.
|
||||
* **[Subscriptions](subscriptions.md)** — `subscriptions/listen` and the notification bus
|
||||
behind it.
|
||||
* **[Authorization](authorization.md)** — validating OAuth 2 access tokens in front of
|
||||
the HTTP transport.
|
||||
136
docs/run/protocol-eras.md
Normal file
136
docs/run/protocol-eras.md
Normal file
|
|
@ -0,0 +1,136 @@
|
|||
# Serving both eras
|
||||
|
||||
`Server::builder()->build()` produces a server carrying a dispatcher for each
|
||||
[protocol era](../protocol-versions.md), and `StreamableHttpTransport` decides per request
|
||||
which of them answers. There is nothing to configure:
|
||||
|
||||
```php
|
||||
use Mcp\Server;
|
||||
use Mcp\Server\Transport\StreamableHttpTransport;
|
||||
|
||||
$server = Server::builder()
|
||||
->setServerInfo('My Server', '1.0.0')
|
||||
->addTool(static fn (string $city): string => "17°C in {$city}", name: 'get_weather', description: '…')
|
||||
->build();
|
||||
|
||||
(new SapiEmitter())->emit($server->run(new StreamableHttpTransport($request)));
|
||||
```
|
||||
|
||||
That one endpoint answers `initialize` and `server/discover` alike. Modern-era requests
|
||||
accept `POST` only; a `GET` or `DELETE` is a handshake-era session operation and is routed as
|
||||
one.
|
||||
|
||||
A full example lives in
|
||||
[`examples/server/stateless-lifecycle/server.php`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/stateless-lifecycle),
|
||||
described in [Examples](../examples.md#the-2026-07-28-lifecycle).
|
||||
|
||||
## What a modern request carries
|
||||
|
||||
There is no handshake to remember anything, so every request carries what the server needs to
|
||||
answer it. Two members in `params._meta` are **required**, and the HTTP layer mirrors some of
|
||||
them into headers so an intermediary can route without parsing the body:
|
||||
|
||||
| `_meta` key | Required | Header |
|
||||
| --- | --- | --- |
|
||||
| `io.modelcontextprotocol/protocolVersion` | yes | `MCP-Protocol-Version` |
|
||||
| `io.modelcontextprotocol/clientCapabilities` | yes | — |
|
||||
| `io.modelcontextprotocol/clientInfo` | no | — |
|
||||
| `io.modelcontextprotocol/logLevel` | no | — |
|
||||
| `progressToken` | no | — |
|
||||
| `traceparent`, `tracestate`, `baggage` | no | — |
|
||||
|
||||
Plus `Mcp-Method` on every request, and `Mcp-Name` on `tools/call`, `prompts/get` and
|
||||
`resources/read`. A header that disagrees with the body is refused with `-32020`; a missing
|
||||
required `_meta` member with `-32602`; an unsupported version with `-32022`, carrying the
|
||||
supported set for the client to retry from.
|
||||
|
||||
What a handler can read off all this is
|
||||
[Talking back to the client](../handlers/client-communication.md#request-metadata).
|
||||
|
||||
### Mirroring a tool argument into a header
|
||||
|
||||
A tool parameter annotated with `x-mcp-header` is mirrored into `Mcp-Param-{Name}` by the
|
||||
client, and the server checks that the two agree:
|
||||
|
||||
```php
|
||||
->addTool(
|
||||
static fn (string $region, string $query): string => …,
|
||||
name: 'execute_sql',
|
||||
inputSchema: [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'region' => ['type' => 'string', 'x-mcp-header' => 'Region'],
|
||||
'query' => ['type' => 'string'],
|
||||
],
|
||||
'required' => ['region', 'query'],
|
||||
],
|
||||
)
|
||||
```
|
||||
|
||||
The annotation must name a valid HTTP field, be unique case-insensitively, and sit on a
|
||||
`string`, `integer` or `boolean` property reachable through `properties` keys alone. `Tool`
|
||||
refuses a definition that breaks any of those rather than letting it fail later as a header
|
||||
mismatch. See [Schema generation](../servers/schemas.md) for where a hand-written
|
||||
`inputSchema` fits.
|
||||
|
||||
## How a request is routed
|
||||
|
||||
Every request is classified once, before anything else looks at it. The decision is
|
||||
**body-primary**:
|
||||
|
||||
| Evidence | Routed to |
|
||||
| --- | --- |
|
||||
| `params._meta` names a modern revision | modern era |
|
||||
| `params._meta` names a handshake revision | handshake era |
|
||||
| no such member | handshake era — `initialize` included |
|
||||
| a notification with no member, under a modern header | modern era |
|
||||
| `GET` / `DELETE` | handshake era |
|
||||
|
||||
The `MCP-Protocol-Version` header never decides. It is cross-checked against the body, and a
|
||||
request whose header contradicts its `_meta` is refused with `-32020` before either leg sees
|
||||
it — the check has to happen at the edge, because a body claiming a handshake revision routes
|
||||
to a leg that has no such check of its own. A modern header on a request carrying no envelope
|
||||
is refused with `-32602` naming the member it wants.
|
||||
|
||||
An unrecognised revision goes to whichever leg can answer it best: claimed in the envelope,
|
||||
the modern leg answers, naming the modern revisions it serves; named only in a header, the
|
||||
handshake leg answers, naming the handshake ones.
|
||||
|
||||
Both legs come from **one** builder configuration — one registry, one set of handler
|
||||
instances, one session manager. A tool registered once is reachable from both, and a change
|
||||
made through one is visible to the other.
|
||||
|
||||
## Middleware
|
||||
|
||||
The [default middleware stack](http.md#default-middleware) runs at the edge, before the
|
||||
request's era is known, because what it enforces is true of both. `ProtocolVersionMiddleware`
|
||||
is not in that stack: the `MCP-Protocol-Version` header rule belongs to the handshake era, so
|
||||
the transport applies it only to requests it classified as handshake-era traffic, and the
|
||||
modern leg answers for its own revisions. It is available as
|
||||
`StreamableHttpTransport::handshakeMiddleware()` and is applied whether or not you replace the
|
||||
edge stack.
|
||||
|
||||
## Serving one era only
|
||||
|
||||
To serve the handshake era alone, say so:
|
||||
|
||||
```php
|
||||
$server = Server::builder()
|
||||
->setServerInfo('My Server', '1.0.0')
|
||||
->withoutModernEra()
|
||||
->build();
|
||||
```
|
||||
|
||||
That server refuses a modern claim with `-32022`, naming the handshake revisions it does
|
||||
serve. `setModernVersions()` narrows the modern leg instead of removing it.
|
||||
|
||||
For the opposite — an endpoint that serves the modern era and nothing else — build the
|
||||
dispatcher on its own and mount it on `StatelessHttpTransport`:
|
||||
|
||||
```php
|
||||
$protocol = Server::builder()
|
||||
->setServerInfo('My Server', '1.0.0')
|
||||
->buildStateless([ProtocolVersion::V2026_07_28]);
|
||||
|
||||
(new SapiEmitter())->emit((new StatelessHttpTransport($protocol))->handle($request));
|
||||
```
|
||||
336
docs/run/server-builder.md
Normal file
336
docs/run/server-builder.md
Normal file
|
|
@ -0,0 +1,336 @@
|
|||
# Server builder
|
||||
|
||||
The server `Builder` is a fluent builder class that simplifies the creation and configuration of an MCP server instance.
|
||||
It provides methods for setting server information, configuring discovery, registering capabilities, and customizing
|
||||
various aspects of the server behavior.
|
||||
|
||||
## Basic Usage
|
||||
|
||||
There are two ways to obtain a server builder instance:
|
||||
|
||||
### Method 1: Static Builder Method (Recommended)
|
||||
|
||||
```php
|
||||
use Mcp\Server;
|
||||
|
||||
$server = Server::builder()
|
||||
->setServerInfo('My MCP Server', '1.0.0')
|
||||
->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor'])
|
||||
->build();
|
||||
```
|
||||
|
||||
### Method 2: Direct Instantiation
|
||||
|
||||
```php
|
||||
use Mcp\Server\Builder;
|
||||
|
||||
$server = (new Builder())
|
||||
->setServerInfo('My MCP Server', '1.0.0')
|
||||
->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor'])
|
||||
->build();
|
||||
```
|
||||
|
||||
Both methods return a `Builder` instance that you can configure with fluent methods. The `build()` method returns the
|
||||
final `Server` instance ready for use.
|
||||
|
||||
## Server Configuration
|
||||
|
||||
### Server Information
|
||||
|
||||
Set the server's identity with name, version, and optional description:
|
||||
|
||||
```php
|
||||
use Mcp\Schema\Icon;
|
||||
use Mcp\Server;
|
||||
|
||||
$server = Server::builder()
|
||||
->setServerInfo(
|
||||
name: 'Calculator Server',
|
||||
version: '1.2.0',
|
||||
description: 'Advanced mathematical calculations',
|
||||
icons: [new Icon('https://example.com/icon.png', 'image/png', ['64x64'])],
|
||||
websiteUrl: 'https://example.com',
|
||||
);
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `$name` (string): The server name
|
||||
- `$version` (string): Version string (semantic versioning recommended)
|
||||
- `$description` (string|null): Optional description
|
||||
- `$icons` (Icon[]|null): Optional array of server icons
|
||||
- `$websiteUrl` (string|null): Optional server website URL
|
||||
- `$title` (string|null): Optional human-readable display title, distinct from `$name`
|
||||
|
||||
### Pagination Limit
|
||||
|
||||
Configure the maximum number of items returned in paginated responses:
|
||||
|
||||
```php
|
||||
$server = Server::builder()
|
||||
->setPaginationLimit(100); // Default: 50
|
||||
```
|
||||
|
||||
### Instructions
|
||||
|
||||
Provide hints to help AI models understand how to use your server:
|
||||
|
||||
```php
|
||||
$server = Server::builder()
|
||||
->setInstructions('This calculator supports basic arithmetic operations. Use the calculate tool for math operations and check the config resource for current settings.');
|
||||
```
|
||||
|
||||
### Protocol Version
|
||||
|
||||
By default the server negotiates the protocol revision with each client during the `initialize` handshake, and you do
|
||||
not need to configure anything. `setProtocolVersion()` pins that handshake to exactly one revision instead:
|
||||
|
||||
```php
|
||||
use Mcp\Schema\Enum\ProtocolVersion;
|
||||
|
||||
$server = Server::builder()
|
||||
->setProtocolVersion(ProtocolVersion::V2025_06_18);
|
||||
```
|
||||
|
||||
See [Protocol versions](../protocol-versions.md#negotiating-in-the-handshake-era) for how negotiation resolves and
|
||||
what pinning changes. It only pins the handshake era; to narrow or remove what the modern leg answers for, use
|
||||
`setModernVersions()` / `withoutModernEra()` — see
|
||||
[Serving both eras](protocol-eras.md#serving-one-era-only).
|
||||
|
||||
## Modern-Era Options
|
||||
|
||||
`build()` returns a server that answers both [protocol eras](../protocol-versions.md), and none of the following is
|
||||
required to serve either one. Each knob is covered in depth elsewhere:
|
||||
[Asking for input](../handlers/input-required.md) for the first two,
|
||||
[Caching](caching.md), [Subscriptions](subscriptions.md), and
|
||||
[Serving both eras](protocol-eras.md) for the last.
|
||||
|
||||
```php
|
||||
use Mcp\Schema\Enum\CacheScope;
|
||||
use Mcp\Schema\Enum\ProtocolVersion;
|
||||
use Mcp\Server\Subscription\Psr16NotificationBus;
|
||||
use Mcp\Server\Wire\CachePolicy;
|
||||
|
||||
$server = Server::builder()
|
||||
// Signs the state a multi round-trip request carries through the client.
|
||||
// The same key must reach every process that might serve the retry.
|
||||
->setRequestState($_ENV['MCP_REQUEST_STATE_KEY'], ttl: 600)
|
||||
|
||||
// Bounds the input-required shim, which fulfils an `InputRequiredResult`
|
||||
// over a handshake-era connection. `withoutInputRequiredShim()` turns it off.
|
||||
->setInputRequiredLimits(maxRounds: 4, roundTimeout: 120)
|
||||
|
||||
// Caching hints stamped on cacheable results. Defaults to `ttlMs: 0, private`.
|
||||
->setCachePolicy(CachePolicy::default(30_000)->withMethod('tools/list', 3_600_000, CacheScope::Public))
|
||||
|
||||
// Delivery for `subscriptions/listen`, and how long such a stream is held.
|
||||
->setNotificationBus(new Psr16NotificationBus($cache))
|
||||
->setSubscriptionLifetime(0)
|
||||
|
||||
// Narrow the modern leg, or drop it entirely.
|
||||
->setModernVersions([ProtocolVersion::V2026_07_28])
|
||||
->build();
|
||||
```
|
||||
|
||||
`buildStateless()` returns the modern dispatcher alone, for an endpoint that serves no handshake-era traffic at all.
|
||||
Its requests are checked against the SEP-2243 standard headers — that `Mcp-Method`, `Mcp-Name` and `Mcp-Param-*` agree
|
||||
with the body they travel with. `setHeaderValidator(false)` turns that check off, which is needed only when the
|
||||
dispatcher is served by a transport that has no header layer to check.
|
||||
|
||||
## Discovery Configuration
|
||||
|
||||
**Required when using MCP attributes.** If you're using PHP attributes (`#[McpTool]`, `#[McpResource]`, `#[McpResourceTemplate]`, `#[McpPrompt]`) to define your MCP elements, you **MUST** configure discovery to tell the server where to look for these attributes.
|
||||
|
||||
```php
|
||||
$server = Server::builder()
|
||||
->setDiscovery(
|
||||
basePath: __DIR__,
|
||||
scanDirs: ['.', 'src', 'lib'], // Where to look for MCP attributes
|
||||
excludeDirs: ['vendor', 'tests'], // Where NOT to look
|
||||
cache: $cacheInstance, // Optional: cache discovered elements
|
||||
namePatterns: ['*.php', '*.inc'], // Optional: list of filename patterns to match
|
||||
);
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `$basePath` (string): Base directory for discovery (typically `__DIR__`)
|
||||
- `$scanDirs` (array): Directories to recursively scan for `#[McpTool]`, `#[McpResource]`, etc. All subdirectories are included. (default: `['.', 'src']`)
|
||||
- `$excludeDirs` (array): Directory names to exclude **within** the scanned directories during recursive scanning
|
||||
- `$cache` (CacheInterface|null): Optional PSR-16 cache to store discovered elements for performance
|
||||
- `$namePatterns` (array): Optional list of patterns (regexp, glob, or string) for file names (default: `['*.php']`)
|
||||
|
||||
**Basic Discovery (scans current directory and `src/`):**
|
||||
```php
|
||||
$server = Server::builder()
|
||||
->setDiscovery(__DIR__, excludeDirs: ['vendor']) // Scans '.' and 'src'
|
||||
->build();
|
||||
```
|
||||
|
||||
!!! warning
|
||||
Always exclude `vendor/` when the scanned directories contain it. The recursive scan
|
||||
tries to load every class it finds, and a single file that cannot be loaded makes the
|
||||
scan abort — the server then reports an **empty** element list instead of an error.
|
||||
|
||||
**Production Setup with Caching:**
|
||||
```php
|
||||
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
|
||||
use Symfony\Component\Cache\Psr16Cache;
|
||||
|
||||
// Cache discovered elements to avoid filesystem scanning on every server start
|
||||
$cache = new Psr16Cache(new FilesystemAdapter('mcp-discovery'));
|
||||
|
||||
$server = Server::builder()
|
||||
->setDiscovery(
|
||||
basePath: __DIR__,
|
||||
scanDirs: ['src', 'lib'], // Scan these directories recursively
|
||||
excludeDirs: ['vendor', 'tests', 'temp'], // Skip these directory names within scanned dirs
|
||||
cache: $cache // Cache for performance
|
||||
)
|
||||
->build();
|
||||
```
|
||||
|
||||
**How `excludeDirs` works:**
|
||||
- If scanning `src/` and there's `src/vendor/`, it will be excluded
|
||||
- If scanning `lib/` and there's `lib/tests/`, it will be excluded
|
||||
- But if `vendor/` and `tests/` are at the same level as `src/`, they're not scanned anyway (not in `scanDirs`)
|
||||
|
||||
> **Performance**: Always use a cache in production. The first run scans and caches all discovered MCP elements, making
|
||||
> subsequent server startups nearly instantaneous.
|
||||
|
||||
## Service Dependencies
|
||||
|
||||
### Container
|
||||
|
||||
The container is used to resolve handlers and their dependencies when handlers inject dependencies in their constructors.
|
||||
The SDK includes a basic container with simple auto-wiring capabilities.
|
||||
|
||||
```php
|
||||
use Mcp\Capability\Registry\Container;
|
||||
|
||||
// Use the default basic container
|
||||
$container = new Container();
|
||||
$container->set(DatabaseService::class, new DatabaseService($pdo));
|
||||
$container->set(\PDO::class, $pdo);
|
||||
|
||||
$server = Server::builder()
|
||||
->setContainer($container)
|
||||
->build();
|
||||
```
|
||||
|
||||
**Basic Container Features:**
|
||||
- Supports constructor auto-wiring for classes with parameterless constructors
|
||||
- Resolves dependencies where all parameters are type-hinted classes/interfaces known to the container
|
||||
- Supports parameters with default values
|
||||
- Does NOT support scalar/built-in type injection without defaults
|
||||
- Detects circular dependencies
|
||||
|
||||
You can also use any PSR-11 compatible container (Symfony DI, PHP-DI, Laravel Container, etc.).
|
||||
|
||||
### Logger
|
||||
|
||||
Provide a PSR-3 logger instance for internal server logging (request/response processing, errors, session management, transport events):
|
||||
|
||||
```php
|
||||
use Monolog\Logger;
|
||||
use Monolog\Handler\StreamHandler;
|
||||
|
||||
$logger = new Logger('mcp-server');
|
||||
$logger->pushHandler(new StreamHandler('mcp.log', Logger::INFO));
|
||||
|
||||
$server = Server::builder()
|
||||
->setLogger($logger);
|
||||
```
|
||||
|
||||
### Event Dispatcher
|
||||
|
||||
Configure event dispatching:
|
||||
|
||||
```php
|
||||
$server = Server::builder()
|
||||
->setEventDispatcher($eventDispatcher);
|
||||
```
|
||||
|
||||
## Complete Example
|
||||
|
||||
Here's a comprehensive example showing all major configuration options:
|
||||
|
||||
```php
|
||||
use Mcp\Server;
|
||||
use Mcp\Server\Session\FileSessionStore;
|
||||
use Mcp\Capability\Registry\Container;
|
||||
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
|
||||
use Symfony\Component\Cache\Psr16Cache;
|
||||
use Monolog\Logger;
|
||||
use Monolog\Handler\StreamHandler;
|
||||
|
||||
// Setup dependencies
|
||||
$logger = new Logger('mcp-server');
|
||||
$logger->pushHandler(new StreamHandler('mcp.log', Logger::INFO));
|
||||
|
||||
$cache = new Psr16Cache(new FilesystemAdapter('mcp-discovery'));
|
||||
$sessionStore = new FileSessionStore(__DIR__ . '/sessions');
|
||||
|
||||
// Setup container with dependencies
|
||||
$container = new Container();
|
||||
$container->set(\PDO::class, new \PDO('sqlite::memory:'));
|
||||
$container->set(DatabaseService::class, new DatabaseService($container->get(\PDO::class)));
|
||||
|
||||
// Build server
|
||||
$server = Server::builder()
|
||||
// Server identity
|
||||
->setServerInfo('Advanced Calculator', '2.1.0')
|
||||
|
||||
// Performance and behavior
|
||||
->setPaginationLimit(100)
|
||||
->setInstructions('Use calculate tool for math operations. Check config resource for current settings.')
|
||||
|
||||
// Discovery with caching
|
||||
->setDiscovery(__DIR__, ['src'], ['vendor', 'tests'], $cache)
|
||||
|
||||
// Session management
|
||||
->setSession($sessionStore)
|
||||
|
||||
// Services
|
||||
->setLogger($logger)
|
||||
->setContainer($container)
|
||||
|
||||
// Manual capability registration
|
||||
->addTool([Calculator::class, 'advancedCalculation'], 'advanced_calc')
|
||||
->addResource([Config::class, 'getSettings'], 'config://app/settings', 'app_settings')
|
||||
|
||||
// Build the server
|
||||
->build();
|
||||
```
|
||||
|
||||
## Method Reference
|
||||
|
||||
| Method | Parameters | Description |
|
||||
|--------|------------|-------------|
|
||||
| `setServerInfo()` | name, version, description? | Set server identity |
|
||||
| `setPaginationLimit()` | limit | Set max items per page |
|
||||
| `setInstructions()` | instructions | Set usage instructions |
|
||||
| `setProtocolVersion()` | protocolVersion | Pin the handshake to one protocol revision |
|
||||
| `setModernVersions()` | versions | Narrow the revisions the modern (2026-07-28) leg answers for |
|
||||
| `withoutModernEra()` | - | Serve the handshake era only |
|
||||
| `setRequestState()` | key, ttl? | Signing key and lifetime for multi round-trip request state |
|
||||
| `setInputRequiredLimits()` | maxRounds, roundTimeout | Bound the input-required shim on handshake-era connections |
|
||||
| `withoutInputRequiredShim()` | - | Do not fulfil an `InputRequiredResult` over a handshake-era connection |
|
||||
| `setCachePolicy()` | policy | Set the `ttlMs`/`cacheScope` hints on cacheable results |
|
||||
| `setNotificationBus()` | bus | Delivery for `subscriptions/listen` streams |
|
||||
| `setSubscriptionLifetime()` | seconds | How long a subscription stream is held open (`0` = unbounded) |
|
||||
| `setHeaderValidator()` | enabled | Toggle the SEP-2243 standard-header check on `buildStateless()` |
|
||||
| `setDiscovery()` | basePath, scanDirs?, excludeDirs?, cache? | Configure attribute discovery |
|
||||
| `setSession()` | sessionStore?, sessionManager?, gcProbability?, gcDivisor? | Configure session management |
|
||||
| `setLogger()` | logger | Set PSR-3 logger |
|
||||
| `setContainer()` | container | Set PSR-11 container |
|
||||
| `setEventDispatcher()` | dispatcher | Set PSR-14 event dispatcher |
|
||||
| `addRequestHandler()` | handler | Prepend a single custom request handler |
|
||||
| `addRequestHandlers()` | handlers | Prepend multiple custom request handlers |
|
||||
| `addNotificationHandler()` | handler | Prepend a single custom notification handler |
|
||||
| `addNotificationHandlers()` | handlers | Prepend multiple custom notification handlers |
|
||||
| `addTool()` | handler, name?, title?, description?, annotations?, inputSchema?, ... | Register tool |
|
||||
| `addResource()` | handler, uri, name?, title?, description?, mimeType?, size?, annotations?, icons?, meta? | Register resource |
|
||||
| `addResourceTemplate()` | handler, uriTemplate, name?, title?, description?, mimeType?, annotations?, meta? | Register resource template |
|
||||
| `addPrompt()` | handler, name?, title?, description?, icons?, meta? | Register prompt |
|
||||
| `add()` | definition, handler | Register an element from a schema VO + handler pair |
|
||||
| `build()` | - | Create the server instance |
|
||||
| `buildStateless()` | supportedVersions? | Create the modern dispatcher alone, for `StatelessHttpTransport` |
|
||||
127
docs/run/sessions.md
Normal file
127
docs/run/sessions.md
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
# Session Management
|
||||
|
||||
> Sessions belong to the handshake era. Protocol revision `2026-07-28` removed them, along with
|
||||
> `Mcp-Session-Id`, because every request carries what is needed to answer it — see
|
||||
> [The 2026-07-28 lifecycle](../protocol-versions.md). One server serves both, so the configuration below still
|
||||
> applies to the handshake-era clients it answers.
|
||||
|
||||
Configure session storage and lifecycle. By default, the SDK uses `InMemorySessionStore`:
|
||||
|
||||
```php
|
||||
use Mcp\Server\Session\FileSessionStore;
|
||||
use Mcp\Server\Session\InMemorySessionStore;
|
||||
use Mcp\Server\Session\Psr16SessionStore;
|
||||
use Symfony\Component\Cache\Psr16Cache;
|
||||
use Symfony\Component\Cache\Adapter\RedisAdapter;
|
||||
|
||||
// Override with file-based storage
|
||||
$server = Server::builder()
|
||||
->setSession(new FileSessionStore(__DIR__ . '/sessions'))
|
||||
->build();
|
||||
|
||||
// Override with in-memory storage and custom TTL
|
||||
$server = Server::builder()
|
||||
->setSession(new InMemorySessionStore(3600))
|
||||
->build();
|
||||
|
||||
// Override with PSR-16 cache-based storage
|
||||
// Requires psr/simple-cache and symfony/cache (or any other PSR-16 implementation)
|
||||
// composer require psr/simple-cache symfony/cache
|
||||
$redisAdapter = new RedisAdapter(
|
||||
RedisAdapter::createConnection('redis://localhost:6379'),
|
||||
'mcp_sessions'
|
||||
);
|
||||
|
||||
$server = Server::builder()
|
||||
->setSession(new Psr16SessionStore(
|
||||
cache: new Psr16Cache($redisAdapter),
|
||||
prefix: 'mcp-',
|
||||
ttl: 3600
|
||||
))
|
||||
->build();
|
||||
```
|
||||
|
||||
## Garbage Collection Configuration
|
||||
|
||||
The SDK periodically runs garbage collection to clean up expired sessions, similar to PHP's native
|
||||
`session.gc_probability` and `session.gc_divisor` settings. The probability that GC runs on any given
|
||||
request is `gcProbability / gcDivisor`.
|
||||
|
||||
```php
|
||||
// Default: 1/100 (1% chance per request)
|
||||
$server = Server::builder()
|
||||
->setSession(new FileSessionStore(__DIR__ . '/sessions'))
|
||||
->build();
|
||||
|
||||
// Higher frequency: 1/10 (10% chance per request)
|
||||
$server = Server::builder()
|
||||
->setSession(
|
||||
new FileSessionStore(__DIR__ . '/sessions'),
|
||||
gcProbability: 1,
|
||||
gcDivisor: 10,
|
||||
)
|
||||
->build();
|
||||
|
||||
// Run GC on every request
|
||||
$server = Server::builder()
|
||||
->setSession(gcProbability: 1, gcDivisor: 1)
|
||||
->build();
|
||||
|
||||
// Disable GC entirely (e.g. when using an external cleanup process)
|
||||
$server = Server::builder()
|
||||
->setSession(gcProbability: 0)
|
||||
->build();
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `$gcProbability` (int): The numerator of the GC probability fraction (default: `1`). Set to `0` to disable GC.
|
||||
- `$gcDivisor` (int): The denominator of the GC probability fraction (default: `100`). Must be >= 1.
|
||||
|
||||
> **Note**: When providing a custom `SessionManagerInterface` via the `$sessionManager` parameter,
|
||||
> the `gcProbability` and `gcDivisor` settings are ignored — you control GC behavior in your own implementation.
|
||||
|
||||
**Available Session Stores:**
|
||||
- `InMemorySessionStore`: Fast in-memory storage (default)
|
||||
- `FileSessionStore`: Persistent file-based storage
|
||||
- `Psr16SessionStore`: PSR-16 compliant cache-based storage
|
||||
|
||||
**Custom Session Stores:**
|
||||
|
||||
Implement `SessionStoreInterface` to create custom session storage:
|
||||
|
||||
```php
|
||||
use Mcp\Server\Session\SessionStoreInterface;
|
||||
use Symfony\Component\Uid\Uuid;
|
||||
|
||||
class RedisSessionStore implements SessionStoreInterface
|
||||
{
|
||||
public function __construct(private $redis, private int $ttl = 3600) {}
|
||||
|
||||
public function exists(Uuid $id): bool
|
||||
{
|
||||
return $this->redis->exists($id->toRfc4122());
|
||||
}
|
||||
|
||||
public function read(Uuid $sessionId): string|false
|
||||
{
|
||||
$data = $this->redis->get($sessionId->toRfc4122());
|
||||
return $data !== false ? $data : false;
|
||||
}
|
||||
|
||||
public function write(Uuid $sessionId, string $data): bool
|
||||
{
|
||||
return $this->redis->setex($sessionId->toRfc4122(), $this->ttl, $data);
|
||||
}
|
||||
|
||||
public function destroy(Uuid $sessionId): bool
|
||||
{
|
||||
return $this->redis->del($sessionId->toRfc4122()) > 0;
|
||||
}
|
||||
|
||||
public function gc(): array
|
||||
{
|
||||
// Redis handles TTL automatically
|
||||
return [];
|
||||
}
|
||||
}
|
||||
```
|
||||
64
docs/run/stdio.md
Normal file
64
docs/run/stdio.md
Normal file
|
|
@ -0,0 +1,64 @@
|
|||
# STDIO Transport
|
||||
|
||||
The STDIO transport communicates via standard input/output streams, ideal for command-line tools and MCP client integrations.
|
||||
|
||||
```php
|
||||
$transport = new StdioTransport(
|
||||
input: STDIN, // Input stream (default: STDIN)
|
||||
output: STDOUT, // Output stream (default: STDOUT)
|
||||
logger: $logger // Optional PSR-3 logger
|
||||
);
|
||||
```
|
||||
|
||||
## Parameters
|
||||
|
||||
- **`input`** (optional): Input stream resource. Defaults to `STDIN`.
|
||||
- **`output`** (optional): Output stream resource. Defaults to `STDOUT`.
|
||||
- **`logger`** (optional): `LoggerInterface` - PSR-3 logger for debugging. Defaults to `NullLogger`.
|
||||
- **`runnerControl`** (optional): `RunnerControlInterface` - controls the read loop; the default runs until the input stream closes.
|
||||
- **`maxLineBytes`** (optional): Maximum accepted line length in bytes. Oversized lines are rejected as invalid messages.
|
||||
|
||||
!!! warning
|
||||
When using STDIO transport, **never** write to `STDOUT` in your handlers as it's reserved for JSON-RPC communication.
|
||||
Use `STDERR` for debugging instead.
|
||||
|
||||
## Example Server Script
|
||||
|
||||
```php-file
|
||||
#!/usr/bin/env php
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
require_once __DIR__ . '/vendor/autoload.php';
|
||||
|
||||
use Mcp\Server;
|
||||
use Mcp\Server\Transport\StdioTransport;
|
||||
|
||||
$server = Server::builder()
|
||||
->setServerInfo('STDIO Calculator', '1.0.0')
|
||||
->addTool(function(int $a, int $b): int { return $a + $b; }, 'add_numbers')
|
||||
->addTool(InvokableCalculator::class)
|
||||
->build();
|
||||
|
||||
$transport = new StdioTransport();
|
||||
|
||||
$status = $server->run($transport);
|
||||
|
||||
exit($status); // listen() returns 0 when the input stream closes
|
||||
```
|
||||
|
||||
## Client Configuration
|
||||
|
||||
For MCP clients like Claude Desktop:
|
||||
|
||||
```json
|
||||
{
|
||||
"mcpServers": {
|
||||
"my-php-server": {
|
||||
"command": "php",
|
||||
"args": ["/absolute/path/to/server.php"]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
40
docs/run/subscriptions.md
Normal file
40
docs/run/subscriptions.md
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
# Subscriptions
|
||||
|
||||
> `subscriptions/listen` belongs to protocol revision `2026-07-28`; see
|
||||
> [Protocol versions](../protocol-versions.md). Handshake-era clients keep using the HTTP `GET` stream and
|
||||
> `resources/subscribe`, which the same server still answers.
|
||||
|
||||
`subscriptions/listen` replaces the HTTP `GET` stream and `resources/subscribe`. The client
|
||||
opens a long-lived POST whose response stream carries the notification types it asked for;
|
||||
the server acknowledges first with `notifications/subscriptions/acknowledged`, reporting the
|
||||
subset it agreed to honour.
|
||||
|
||||
## The notification bus
|
||||
|
||||
Delivery needs a bus, because the process that publishes and the process holding the stream
|
||||
open are often not the same one:
|
||||
|
||||
```php
|
||||
use Mcp\Server\Subscription\InMemoryNotificationBus;
|
||||
use Mcp\Server\Subscription\Psr16NotificationBus;
|
||||
|
||||
// stdio, or a persistent runtime where the whole server is one process
|
||||
->setNotificationBus(new InMemoryNotificationBus())
|
||||
|
||||
// PHP-FPM: the publisher and the stream are different workers
|
||||
->setNotificationBus(new Psr16NotificationBus($cache))
|
||||
```
|
||||
|
||||
Registry changes (`registerTool()`, `unregisterPrompt()`, …) are published automatically.
|
||||
Anything else — `notifications/resources/updated` above all — is published by the
|
||||
application:
|
||||
|
||||
```php
|
||||
$bus->publish(new ResourceUpdatedNotification('file:///project/config.json'));
|
||||
```
|
||||
|
||||
## How long a stream lives
|
||||
|
||||
`Builder::setSubscriptionLifetime()` bounds how long a stream is held before the server
|
||||
closes it gracefully. The real ceiling is the runtime's: under PHP-FPM a stream cannot
|
||||
outlive `max_execution_time`. Pass `0` for "until the client or the runtime ends it".
|
||||
Loading…
Reference in a new issue