* [Client][Docs][Schema][Server] Implement protocol version negotiation
The `initialize` handler never looked at the version the client asked for:
it always answered with the server's configured version (or the SDK default),
so a client offering a revision the server supports could still be told to
speak a different one. The spec requires echoing back a supported request and
only counter-offering when the requested version cannot be honoured.
Turns ProtocolVersion into the registry the other SDKs converged on
(typescript-sdk's protocolEras.ts, python-sdk's mcp_types/version.py):
`latestHandshake()`, `handshakeVersions()`, `modernVersions()` and ordered
comparison through `isAtLeast()`. Comparison goes through declaration order
rather than string collation, so an unrecognized peer string compares
conservatively instead of accidentally sorting above a known revision. The
one throw the enum can produce is the SDK's own LogicException, so a consumer
catching `Mcp\Exception\ExceptionInterface` does not miss it.
Adds 2026-07-28 as a known revision and splits the set into two eras:
handshake (2025-11-25 and earlier, negotiated via `initialize`) and modern
(2026-07-28+, per-request `_meta`). The lists are kept apart so a modern
revision can never leak into an `initialize` exchange, which has no
`initialize` at all. Serving the modern era is follow-up work; this only
teaches the SDK that the revision exists and must not be mis-negotiated.
Deliberately absent is any "newest revision in any era" accessor, which
would hand back the one revision the handshake must never offer.
Server: negotiates and stores the result on the session. A version pinned in
Configuration still pins the handshake to exactly that revision.
Client: validates the counter-offer and fails the handshake instead of
continuing on a revision it cannot speak; records the negotiated version on
the client state, readable through the new Client::getProtocolVersion().
The HTTP middleware now defaults to the handshake versions rather than every
declared case, so it stops accepting a modern version the server cannot yet
serve. When the header is absent it falls back to
ProtocolVersion::DEFAULT_NEGOTIATED_VERSION (2025-03-26), the revision that
introduced both Streamable HTTP and the header itself.
The negotiation behaviour is one provideNegotiationTable() data provider
whose rows are the documented table -- supported revision echoed back,
unknown or malformed counter-offered, modern counter-offered -- so the docs
and the suite cannot drift apart. The supported-revision rows iterate
handshakeVersions() rather than a literal list, so declaring a new handshake
revision extends the table automatically, and the "never answer with a modern
revision" assertion runs on every row.
Documented in server-builder.md (the enum registry, how the server answers a
handshake, what pinning changes), transports.md (the header check) and
client.md (the client's side), all linking the spec's versioning section.
* [Client][Docs][Schema][Server] Warn when the configured protocol version cannot be negotiated
* Log a warning instead of silently falling back when a modern revision is
configured on the client or pinned on the server builder.
* Document that setProtocolVersion() does not restrict the MCP-Protocol-Version
header check, which validates against a fixed set.
* Pin every revision's era in a test, so a new case declared past the modern
boundary fails instead of dropping out of the handshake set.
* Add CHANGELOG entry.
* [Client][Docs][Schema][Server] Rename version fallback constant and trim comments
* fix: harden JSON-RPC input parsing against malformed input and DoS
MessageFactory::create() detected batches via $input[0] === '{', which
mishandled valid-but-non-object JSON: a scalar ("5") or leading-whitespace
object silently returned [] (with a PHP warning) or could reach a foreach
over a non-array. It also had no bound on batch size, letting one small
request expand into arbitrarily many operations (amplification).
- Detect single-vs-batch from the decoded JSON type (object vs list array)
instead of the raw first byte; reject scalars and empty payloads as
InvalidInputMessageException rather than crashing or no-oping.
- Cap batch size (maxBatchSize, default 100) and reject oversized batches.
- Reject non-object batch elements as InvalidInputMessageException instead
of letting them hit a TypeError.
- Bound the StreamableHttpTransport POST body (maxBodyBytes, default 4 MiB),
returning 413, with an incremental read so unknown-size/chunked bodies
cannot exhaust memory.
* docs: document input-hardening limits in CHANGELOG and transports guide
Add CHANGELOG entries and docs/transports.md sections for the JSON-RPC
batch size cap (maxBatchSize) and the StreamableHttpTransport request
body size cap (maxBodyBytes), plus the type-based single-vs-batch
message detection.
* [Server] Add CORS, DNS rebinding and protocol version middleware
Introduce three PSR-15 middleware for `StreamableHttpTransport` exposed
through a public `StreamableHttpTransport::defaultMiddleware()` factory
composed automatically when no middleware is passed.
- `CorsMiddleware`: secure-by-default (no `Access-Control-Allow-Origin`),
configurable allowlist, reflects matching origin with `Vary: Origin`
to protect shared caches.
- `DnsRebindingProtectionMiddleware`: validates `Origin`/`Host` against
a hostname allowlist (localhost-only by default).
- `ProtocolVersionMiddleware`: rejects requests carrying an unsupported
`Mcp-Protocol-Version` header with `400 Bad Request`.
The transport no longer applies CORS via an `instanceof + array_unshift`
post-hook; the middleware parameter is nullable — `null` installs the
secure defaults, `[]` disables them, and users compose by spreading
`StreamableHttpTransport::defaultMiddleware()`. `SESSION_HEADER` and
`PROTOCOL_VERSION_HEADER` are promoted to public constants so middleware
can reuse them.
BC breaks:
- The `corsHeaders` constructor parameter is removed; the `middleware`
parameter shifts one position. Positional callers passing the old
`corsHeaders` argument must switch to named arguments or drop it.
- Default `Access-Control-Allow-Origin` is no longer `*`.
Addresses #260 (DNS rebinding), #277 (CORS extraction) and #306
(protocol version validation).
* [Server] Address review feedback on middleware defaults
- CorsMiddleware: emit Access-Control-Allow-Methods/Headers only on
preflight per CORS spec; tokenize Vary header to avoid substring
false-positives; add allowCredentials flag that emits
Access-Control-Allow-Credentials and throws when combined with
wildcard origin.
- DnsRebindingProtectionMiddleware: return plain-text 403 body
(HTTP-level rejection, not JSON-RPC); use parse_url(..., PHP_URL_HOST)
for origin parsing; drop redundant unbracketed '::1' from default
allowlist.
- ProtocolVersionMiddleware: use Error::forInvalidParams instead of
forInvalidRequest -- JSON-RPC -32602 fits header-value rejection
better.
- JsonRpcErrorResponse::create now accepts a JsonRpc\Error so callers
choose the error code.
- StreamableHttpTransport: emit a warning log when an explicit empty
middleware list is passed, so operators can spot accidental bypass
of the default security stack.
* [Server] Fix CI: switch warning-log tests to PHPUnit mocks
Replace the anonymous AbstractLogger fixture in
StreamableHttpTransportTest with `$this->createMock(LoggerInterface::class)`
so the test does not declare a `log()` signature at all. That sidesteps
both the psr/log v1 LSP incompatibility (untyped parameter) and the
phpstan `missingType.parameter` complaint in one move, and matches how
the rest of the suite (CallToolHandlerTest etc.) fakes loggers.
* Update src/Server/Transport/Http/Middleware/CorsMiddleware.php
Co-authored-by: Antoine Bluchet <soyuka@users.noreply.github.com>
---------
Co-authored-by: Antoine Bluchet <soyuka@users.noreply.github.com>
* feat: make CORS headers configurable in StreamableHttpTransport
* docs: add CORS configuration documentation for HTTP transport
* refactor: streamline request creation and transport initialization in HTTP client example
* feat: replace connect/listen flow with run lifecycle
* feat(transport): add phpstan generics for typed transport returns
* refactor: standardize variable naming for MCP server instances in transport handling
* test: remove unnecessary phpstan-ignore annotation in DocBlockTestFixture
* docs: add more about building servers and updating front readme
* Overhaul documentation structure and content
* fix: remove redundant emoji on docs
* Remove composer install --dev hint
* Add linebreak to make it readable in IDE
* rebase after example renaming
---------
Co-authored-by: Kyrian Obikwelu <koshnawaza@gmail.com>