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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ All notable changes to `mcp/sdk` will be documented in this file.
0.5.0
-----

* **[BC BREAK]** Extract CORS handling from `StreamableHttpTransport` into `CorsMiddleware`. The `$corsHeaders` constructor parameter has been removed — pass a configured `CorsMiddleware` via the `$middleware` array instead (a default is prepended automatically if omitted). Default `Access-Control-Allow-Origin` is no longer set (was `*`).
* Add built-in authentication middleware for HTTP transport using OAuth
* Add client component for building MCP clients
* Add `Builder::setReferenceHandler()` to allow custom `ReferenceHandlerInterface` implementations (e.g. authorization decorators)
Expand Down
3 changes: 3 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@
"symfony/http-client": "^5.4 || ^6.4 || ^7.3 || ^8.0",
"symfony/process": "^5.4 || ^6.4 || ^7.3 || ^8.0"
},
"conflict": {
"php-cs-fixer/shim": "3.95.0"
},
"autoload": {
"psr-4": {
"Mcp\\": "src/"
Expand Down
62 changes: 35 additions & 27 deletions docs/transports.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,45 +139,55 @@ $transport = new StreamableHttpTransport($request, $psr17Factory, $psr17Factory)

### CORS Configuration

The transport sets secure CORS defaults that can be customized or disabled:
CORS is handled by the `CorsMiddleware`, which is automatically prepended to the middleware chain. By default,
no `Access-Control-Allow-Origin` header is set, which effectively blocks cross-origin browser requests.

```php
// Default CORS headers (backward compatible)
$transport = new StreamableHttpTransport($request, $responseFactory, $streamFactory);
use Mcp\Server\Transport\Http\Middleware\CorsMiddleware;
use Mcp\Server\Transport\StreamableHttpTransport;

// Default: cross-origin requests are blocked (no Access-Control-Allow-Origin header)
$transport = new StreamableHttpTransport($request);

// Restrict to specific origin
// Allow specific origins
$transport = new StreamableHttpTransport(
$request,
$responseFactory,
$streamFactory,
['Access-Control-Allow-Origin' => 'https://myapp.com']
middleware: [
new CorsMiddleware(
allowedOrigins: ['https://myapp.com', 'https://staging.myapp.com'],
),
],
);

// Disable CORS for proxy scenarios
// Allow all origins (e.g. for development)
$transport = new StreamableHttpTransport(
$request,
$responseFactory,
$streamFactory,
['Access-Control-Allow-Origin' => '']
middleware: [new CorsMiddleware(allowedOrigins: ['*'])],
);

// Custom headers with logger
// Full configuration
$transport = new StreamableHttpTransport(
$request,
$responseFactory,
$streamFactory,
[
'Access-Control-Allow-Origin' => 'https://api.example.com',
'Access-Control-Max-Age' => '86400'
middleware: [
new CorsMiddleware(
allowedOrigins: ['https://myapp.com'],
allowedMethods: ['GET', 'POST', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Accept', 'Authorization', 'Content-Type', 'Last-Event-ID', 'Mcp-Protocol-Version', 'Mcp-Session-Id'],
exposedHeaders: ['Mcp-Session-Id'],
),
],
$logger
);
```

Default CORS headers:
- `Access-Control-Allow-Origin: *`
Default CORS headers (always set unless overridden by middleware):
- `Access-Control-Allow-Methods: GET, POST, DELETE, OPTIONS`
- `Access-Control-Allow-Headers: Content-Type, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID, Authorization, Accept`
- `Access-Control-Allow-Headers: Accept, Authorization, Content-Type, Last-Event-ID, Mcp-Protocol-Version, Mcp-Session-Id`
- `Access-Control-Expose-Headers: Mcp-Session-Id`

If no `CorsMiddleware` is provided, a default instance is automatically prepended — ensuring CORS headers are applied
to all responses, including those from other middleware that short-circuit (e.g. an auth middleware returning `401`).
When you provide your own `CorsMiddleware` in the array, it is used at the position you place it and no default is added.
The transport itself handles `OPTIONS` preflight requests by returning a `204` response.

### PSR-15 Middleware

Expand Down Expand Up @@ -209,15 +219,13 @@ final class AuthMiddleware implements MiddlewareInterface

$transport = new StreamableHttpTransport(
$request,
$responseFactory,
$streamFactory,
[],
$logger,
[new AuthMiddleware($responseFactory)],
logger: $logger,
middleware: [new AuthMiddleware($responseFactory)],
);
```

If middleware returns a response, the transport will still ensure CORS headers are present unless you set them yourself.
If you don't include a `CorsMiddleware` in your middleware array, a default one is automatically prepended,
so CORS headers are applied to all responses even when middleware short-circuits.

### Architecture

Expand Down
86 changes: 86 additions & 0 deletions src/Server/Transport/Http/Middleware/CorsMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
<?php

/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Mcp\Server\Transport\Http\Middleware;

use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

/**
* Applies CORS headers to all responses.
*
* By default, no Access-Control-Allow-Origin header is set, which effectively
* blocks cross-origin browser requests. Configure $allowedOrigins to allow
* specific origins or use ['*'] to allow all.
*
* @author Christopher Hertel <mail@christopher-hertel.de>
*/
final class CorsMiddleware implements MiddlewareInterface
{
/**
* @param list<string> $allowedOrigins Origins to allow (empty = no Access-Control-Allow-Origin header). Use ['*'] to allow all origins.
* @param list<string> $allowedMethods HTTP methods for Access-Control-Allow-Methods
* @param list<string> $allowedHeaders Request headers for Access-Control-Allow-Headers
* @param list<string> $exposedHeaders Response headers for Access-Control-Expose-Headers
*/
public function __construct(
private readonly array $allowedOrigins = [],
private readonly array $allowedMethods = ['GET', 'POST', 'DELETE', 'OPTIONS'],
private readonly array $allowedHeaders = ['Accept', 'Authorization', 'Content-Type', 'Last-Event-ID', 'Mcp-Protocol-Version', 'Mcp-Session-Id'],
private readonly array $exposedHeaders = ['Mcp-Session-Id'],
) {
}

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
$response = $handler->handle($request);

$origin = $request->getHeaderLine('Origin');
$allowedOrigin = $this->resolveAllowedOrigin($origin);

if (null !== $allowedOrigin && !$response->hasHeader('Access-Control-Allow-Origin')) {
$response = $response->withHeader('Access-Control-Allow-Origin', $allowedOrigin);
}

if (!$response->hasHeader('Access-Control-Allow-Methods')) {
$response = $response->withHeader('Access-Control-Allow-Methods', implode(', ', $this->allowedMethods));
}

if (!$response->hasHeader('Access-Control-Allow-Headers')) {
$response = $response->withHeader('Access-Control-Allow-Headers', implode(', ', $this->allowedHeaders));
}

if ([] !== $this->exposedHeaders && !$response->hasHeader('Access-Control-Expose-Headers')) {
$response = $response->withHeader('Access-Control-Expose-Headers', implode(', ', $this->exposedHeaders));
}

return $response;
}

private function resolveAllowedOrigin(string $origin): ?string
{
if ([] === $this->allowedOrigins) {
return null;
}

if (\in_array('*', $this->allowedOrigins, true)) {
return '*';
}

if ('' !== $origin && \in_array($origin, $this->allowedOrigins, true)) {
return $origin;
}

return null;
}
}
42 changes: 10 additions & 32 deletions src/Server/Transport/StreamableHttpTransport.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Http\Discovery\Psr17FactoryDiscovery;
use Mcp\Exception\InvalidArgumentException;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Server\Transport\Http\Middleware\CorsMiddleware;
use Mcp\Server\Transport\Http\MiddlewareRequestHandler;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
Expand All @@ -32,36 +33,22 @@ class StreamableHttpTransport extends BaseTransport
{
private const SESSION_HEADER = 'Mcp-Session-Id';

private const ALLOWED_HEADER = [
'Accept',
'Authorization',
'Content-Type',
'Last-Event-ID',
'Mcp-Protocol-Version',
self::SESSION_HEADER,
];

private ResponseFactoryInterface $responseFactory;
private StreamFactoryInterface $streamFactory;

private ?string $immediateResponse = null;
private ?int $immediateStatusCode = null;

/** @var array<string, string> */
private array $corsHeaders;

/** @var list<MiddlewareInterface> */
private array $middleware = [];

/**
* @param array<string, string> $corsHeaders
* @param iterable<MiddlewareInterface> $middleware
*/
public function __construct(
private ServerRequestInterface $request,
?ResponseFactoryInterface $responseFactory = null,
?StreamFactoryInterface $streamFactory = null,
array $corsHeaders = [],
?LoggerInterface $logger = null,
iterable $middleware = [],
) {
Expand All @@ -70,19 +57,21 @@ public function __construct(
$this->responseFactory = $responseFactory ?? Psr17FactoryDiscovery::findResponseFactory();
$this->streamFactory = $streamFactory ?? Psr17FactoryDiscovery::findStreamFactory();

$this->corsHeaders = array_merge([
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, DELETE, OPTIONS',
'Access-Control-Allow-Headers' => implode(',', self::ALLOWED_HEADER),
'Access-Control-Expose-Headers' => self::SESSION_HEADER,
], $corsHeaders);
$hasCorsMiddleware = false;

foreach ($middleware as $m) {
if (!$m instanceof MiddlewareInterface) {
throw new InvalidArgumentException('Streamable HTTP middleware must implement Psr\\Http\\Server\\MiddlewareInterface.');
}
if ($m instanceof CorsMiddleware) {
$hasCorsMiddleware = true;
}
$this->middleware[] = $m;
}

if (!$hasCorsMiddleware) {
array_unshift($this->middleware, new CorsMiddleware());
}
}

public function send(string $data, array $context): void
Expand All @@ -98,7 +87,7 @@ public function listen(): ResponseInterface
\Closure::fromCallable([$this, 'handleRequest']),
);

return $this->withCorsHeaders($handler->handle($this->request));
return $handler->handle($this->request);
}

protected function handleOptionsRequest(): ResponseInterface
Expand Down Expand Up @@ -273,17 +262,6 @@ protected function createErrorResponse(Error $jsonRpcError, int $statusCode): Re
return $response;
}

protected function withCorsHeaders(ResponseInterface $response): ResponseInterface
{
foreach ($this->corsHeaders as $name => $value) {
if (!$response->hasHeader($name)) {
$response = $response->withHeader($name, $value);
}
}

return $response;
}

private function handleRequest(ServerRequestInterface $request): ResponseInterface
{
$this->request = $request;
Expand Down
Loading
Loading