* [Schema] Refuse an invalid x-mcp-header annotation at definition time
SEP-2243 calls a tool definition invalid when its x-mcp-header annotation is
empty, is not an HTTP field name, collides case-insensitively with another,
or sits on a number, array or object property - none of which can be
mirrored onto a header.
Nothing said so. The earliest place to is where the tool is defined, rather
than on the request that trips over it.
* Clarify x-mcp-header validation only reaches properties
* Make checkHeaderAnnotations() a private instance method
* Make headerAnnotations() a private instance method
* Apply suggestion from @chr-hertel
* [Schema] Stop rejecting elicitation schemas the specification allows
The specification makes `title` optional on every elicitation schema
definition. AbstractSchemaDefinition required it, so a client reading a
conformant server's elicitation/create refused the request - and a server
building one could not omit it either.
`title` is now nullable on all seven definitions, omitted from the
serialized form when absent, and rejected only when present and not a
string.
* Fix stale title docblocks; allow omitting title where safe
* Give Number's title param a default too
* Apply suggestions from code review
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* Preserve request id in JSON-RPC error responses instead of fabricating id:""
When the server received input it could not turn into a valid message, the
error response carried a fabricated empty-string id that was never in the
request, breaking JSON-RPC client correlation.
The id default for the error factories was '' and that default reached the
wire unchanged: unrecoverable parse errors emitted id:"", and for invalid-
but-parseable messages MessageFactory discarded the decoded id so it also
fell back to "".
Now unrecoverable parse errors (-32700) return id: null per JSON-RPC 2.0,
and invalid-but-parseable requests (-32600) preserve the original request
id. Error::$id / getId() and the $id parameter of forParseError() /
forInvalidRequest() are widened to string|int|null, and the recoverable id
is threaded through InvalidInputMessageException.
Fixes#333
* Preserve nullable request id consistently across Error factories and fromArray
- Widen the remaining for*() factories (forMethodNotFound, forInvalidParams,
forInternalError, forServerError, forResourceNotFound) to string|int|null
defaulting to null, so no error path can fabricate id:"" again. The only
defaulting call site (ProtocolVersionMiddleware) now emits id:null instead
of id:"" for a pre-parse rejection, which is the spec-correct value.
- Accept a null id in Error::fromArray(): require the id key to be present
(JSON-RPC responses must carry it) but allow its value to be null, so a
spec-compliant id:null error response round-trips and incoming error
responses with id:null are accepted instead of rejected.
- Widen the @phpstan-type ErrorData id to string|int|null to match the ctor,
getId(), and jsonSerialize() shape.
* Document intentional id recovery guard in MessageFactory
* Cover id: 0 and string ids in recoverable-id preservation test
* Fixed client handling of null-id error responses
* [Schema] Omit the id of an error response that never had one
An error response whose id could not be read sent `"id": ""`, which claims
the peer issued a request with an empty-string id - a different statement
from "the id could not be read". JSON-RPC spells the latter as a null id,
and a receiver that cannot read the id is exactly the case the code covers.
[BC Break] Error::$id accepts null and getId() may return it. All the for*()
factories default to null, fromArray() accepts a missing or explicitly-null
id, and the member is omitted from the serialized form when absent.
* Guard null response id in Client/Server Protocol handlers
Also fix Error::jsonSerialize()'s phpdoc: data belongs inside error, not beside it.
* [Capability] Apply a parameter's complete schema definition
Schema(definition:) is documented as taking precedence over the individual
keywords, and generate() unwraps it that way at method level. At parameter
level it was merged as an ordinary key instead, in both the plain and the
variadic path, so the property reached clients carrying a literal
"definition" member - not JSON Schema, read by nothing, and everything
inside it lost.
Both paths now replace the schema with the definition. The variadic one
still forces type: array afterwards, since a variadic arrives as an array
however the definition describes it, and the signature default survives a
definition that states none - it is what the handler receives when the
argument is omitted, and default is an annotation rather than a constraint.
* Fix docblock description overwriting definition on variadic params
* Apply suggestion from @chr-hertel
* [Schema] Serialize a settingless extension as an object
An extension declaring support with no settings was advertised as `[]`, an
empty JSON array, which the wire schema rejects - `extensions` maps an id to
a settings *object*. Both ServerCapabilities and ClientCapabilities now cast
each entry, so it goes out as `{}`.
* Apply suggestion from @chr-hertel
* [Capability] Stop a union type losing a branch
mapPhpTypeToJsonSchemaType() tested for array syntax before splitting the
union, so string[]|int mapped to array alone; applyArrayConstraints() then
overwrote the type with array whenever the union contained one, dropping the
scalar branch a second time. A tool declaring such a parameter rejected a
valid integer argument.
The split now happens first and only at the top level, so array<int|string>
and array{a: int|string} stay one type rather than two that do not exist, and
the array branch keeps its items alongside the others - which is what 2020-12
means by items: a constraint that applies only when the instance is an array.
* Apply suggestion from @chr-hertel
* Isolate the array branch before inferring its element type
* Don't apply items to arrays whose union branches disagree on element type
* [Examples][Tests] Make the MCP Apps example work over HTTP, and pin it
It was the only example without a session store, so every request under
`php -S` or php-fpm - each its own process - was answered "Session not found
or has expired". It now uses a FileSessionStore like the others.
Inspector snapshots pin what the extension actually puts on the wire: the
ui:// resource's `text/html;profile=mcp-app` MIME type and `ui` marker, and
the `_meta.ui` on the tool that links the two.
* Apply suggestion from @chr-hertel
* Apply suggestion from @chr-hertel
* [Schema] Drop SDK-only name pattern on resources and resource templates
* Update src/Schema/ResourceDefinition.php
* Update src/Schema/ResourceTemplate.php
* [Schema][Server] Close the 2025-11-25 schema gaps and add the 2026-07-28 surface
Ports the type definitions this SDK still misses outside of sampling tool use,
which #409 and #420 already cover. Every addition is optional and defaults to
current behaviour, so a connection negotiated on an older revision is
unaffected.
From 2025-11-25, elicitation gains modes. ElicitationMode splits `form` —
build a form from the requested schema — from `url`, which sends the user out
of band and returns only the accept/decline/cancel outcome. That is why
requestedSchema becomes optional and `url` appears beside it.
ClientCapabilities learns the matching sub-capabilities, where an
`elicitation` naming no mode declares form, the only shape that existed
before. Icon gains `theme` from the same revision, and Implementation gains
the `title` BaseMetadata has carried since 2025-06-18.
From 2026-07-28, schemas loosen where the revision loosens them: SEP-2106
drops the object-only restriction, so Tool::outputSchema may describe any JSON
value and CallToolResult::structuredContent follows.
The same revision defines three error codes (-32020 header mismatch, -32021
missing required client capability, -32022 unsupported protocol version).
ProtocolVersionMiddleware switches to the last of them, so a rejected version
carries the supported set as structured data the client can retry from rather
than only as prose.
* [Schema] Reject what the 2026-07-28 types cannot represent
`Implementation::title` reached the typed constructor unchecked, so malformed
wire data raised a TypeError instead of InvalidArgumentException.
`ToolUseContent::input` accepted a list and serialized it as a JSON array,
where the protocol requires an object. The empty array stays exempt: it is
also an empty map and still emits `{}`.
`ToolChoice` and `ElicitRequest` read their mode with isset(), which is false
for an explicit null, so `{"mode": null}` silently became the default instead
of being rejected. Both use array_key_exists() now, letting the existing type
check refuse null.
* [Client][Server] Advertise the implementation title through both builders
`Implementation::title` could be parsed but never sent: neither
`Client\Builder::setClientInfo()` nor `Server\Builder::setServerInfo()`
accepted one, so every SDK user emitted null.
Both gain a trailing optional `$title`. On the server it sits where the
Implementation constructor already puts it, so existing positional calls keep
their meaning; the client builder forwards it by name, leaving the icons and
websiteUrl slots defaulted.
* [Schema] Serialize every non-null structuredContent
The object-only hydration guard was never that: `!is_array()` admitted
`[1, 2, 3]` and `[]`, which serialize to JSON arrays, while rejecting the
scalars 2026-07-28 permits. The truthiness emission gate was backwards in the
same way — it dropped `[]`, `0`, `false` and `""`, yet emitted lists, strings
and an empty stdClass.
Hydration now accepts any JSON value, and `null` alone means absent, matching
`ToolResultContent` which already carries this field that way. Which values a
given revision permits is a question for version-aware serialization, which
results cannot answer yet.
* [Schema][Server] Make url elicitation reachable
`ElicitRequest::forUrl()` built a request no SDK user could send: the only
public gateway method always constructed form mode from an ElicitationSchema,
and `request()` is private.
`elicitUrl()` joins `elicit()`, and both funnel through one send path that
hydrates the result with the request's own mode. Without that, a url-mode
accept — contentless by design — threw, because ElicitResult requires content
whenever the action is accept. The result carries no discriminator of its own,
so the mode has to come from the request it answers.
`supportsElicitationUrl()` reports whether the client named the mode, reusing
the sub-capability reader the sampling checks already use.
* [Schema] Add CHANGELOG entry for the 2026-07-28 surface
* [Capability][Schema][Server] Carry the widened structuredContent end to end
Review follow-up on the SEP-2106 widening, which stopped at the type.
`ToolReference::extractStructuredContent()` returned `?array`, so a tool
declaring a scalar `outputSchema` had its result dropped and logged as
unsendable. It returns `mixed` now and keeps a scalar — but only from
2026-07-28 on, and only when the tool declared an outputSchema: without one
the value is already carried in `content`, and advertising it twice is not an
improvement.
`CallToolHandler` only warned about list-shaped `structuredContent` on a
self-built `CallToolResult`, so a scalar reached revisions that require an
object unremarked. The check is on the shape now, not on the list case alone.
`ElicitResult` retained a `content` the spec says is absent from url-mode
results, leaving a malformed response indistinguishable from a valid one.
`Tool::jsonSerialize()` emitted the empty root schema as `[]`, which is not a
schema at all. Sub-schemas already had this treatment.
* harden sampling tools against the spec
Report tool-flow violations as -32602 instead of dropping the request,
accept resource_link in tool results, gate tools on sampling.tools, and
reject empty content.
* normalize keyed content arrays to lists
array_filter() and friends preserve keys, and a keyed array serializes as a
JSON object instead of the content-block array the schema requires.
* Address review feedback on resource_link
Three follow-ups from review of the resource_link work:
* PromptResultFormatter: add a regression test proving the optional
fields of a typed resource_link block (title, description, mimeType,
size, annotations, _meta) survive formatting. The delegation to
ResourceLink::fromArray() already landed while rebasing onto the
PromptResultFormatter refactor, but the existing test only supplied
uri/name and so could not catch a reintroduced field drop.
* ResourceLink::fromArray(): validate optional fields consistently, the
way the equivalent ResourceDefinition::fromArray() already does.
description, mimeType and size now raise InvalidArgumentException
instead of surfacing a TypeError (or silently coercing, for size's
(int) cast); annotations goes through Annotations::tryFromArray(),
which carries the is_array() guard that icons already had; icons uses
Icon::listFromArray() so a non-array entry is reported in context.
* ToolReference::extractStructuredContent(): never emit a list as
structuredContent. The Content guard added earlier fixed only one
instance of the real invariant - structuredContent must be a JSON
object, and a PHP list can never be one. Tool::fromArray() already
enforces the matching rule by rejecting an outputSchema whose type is
not "object", so this aligns the runtime path with it. The test
asserting the opposite for an array-typed outputSchema contradicted
the phpstan type and the fromArray() check introduced alongside it in
the same commit, so it is replaced by tests for the two list shapes.
* Apply the structuredContent object rule to object results too
`extractStructuredContent()` guards raw array results against being emitted
as a JSON array, but the object branch handed back whatever `json_decode()`
produced. A `JsonSerializable` returning a list or a scalar slipped straight
through, producing exactly the `structuredContent` the array guard exists to
prevent — and a return value that contradicts the method's own
`array<string, mixed>|null` signature.
Check the decoded value before returning it, and cover the object branch,
which had no tests at all.
* Document structured tool output
`outputSchema` and `structuredContent` were undocumented: the tool return
value docs covered only the `content` side, and the schema generation
section is about tool parameters.
Add a "Structured Output" subsection covering how to declare the schema,
which return values populate `structuredContent`, and why a list has to be
wrapped in a key to get structured output at all.
* Gate structuredContent on the negotiated protocol revision
SEP-2106 (revision 2026-07-28) widens structuredContent to any JSON value;
earlier revisions require an object. Resolve the revision per request and
apply the matching rule, and warn when a declared outputSchema yields none.
* Resolve the protocol revision on RequestContext
Keeps the `_meta`-then-session lookup in one place instead of per handler,
and exposes the negotiated revision to tool handlers.
* Document reading the negotiated revision from RequestContext
* Warn when a self-built CallToolResult carries an invalid structuredContent
Returning a CallToolResult opts out of the extraction rules, so the value is
still sent unchanged — but a JSON array is not valid before SEP-2106.
* feat: support sampling with tools
* address sampling tools review feedback
* tighten sampling tools spec compliance
* drop SamplingStopReason enum in favor of open string
The spec leaves stopReason open for provider-specific values, so upcasting
the four known ones to enum cases makes every future enum addition a silent
BC break for string comparisons.
---------
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* [Client] Implement setMaxRetries connection retries
* [Client] Reject a negative retry count in Configuration
* [Client] Use a positive init timeout in the retry test
* [Client] Drop redundant docblock note on setMaxRetries
* [Client] Clear the initialized flag on a failed connection
* [Client] Trim comments to the non-obvious ones
* [Client] Cover retries and timeout cleanup with integration tests
The retry fixture counts the processes it was started as, which is what
separates a real retry from a second call into the same server. The timeout
fixture outlives the client's patience and then goes idle, so the next
request runs on a connection the client already gave up on once.
* [Tests] Introduce client-server integration tests
* Add an in-process loopback that connects a real client transport to a real
server transport, draining both Fiber loops in one synchronous pass instead
of polling. A stalled exchange fails where it happened rather than hanging.
* Cover protocol version negotiation across both implementations, where the
unit tests only ever drive one side against a canned counter-offer.
* Cover the server-to-client round-trips end to end: elicitation, sampling,
roots, plus progress and logging notifications.
* Add the `integration` test suite and a `make integration-tests` target.
* [Tests] Run the integration suite in CI
The unit job pins `--testsuite=unit`, so the new suite would never have run on
GitHub. It goes in that job rather than its own: the loopback leans on Fibers,
and the matrix is what covers them down to the PHP 8.1 floor.
* [Tests] Run integration tests against a real server process
Replaces the in-process loopback with the setup from examples/client: the
client spawns a fixture server over the real StdioTransport, so the tests
exercise the shipped transports and no longer nest both sides' Fibers.
Moves the suite into its own CI job, matrixed over PHP 8.1-8.5.
Sampling was the one client capability a tool could not check before asking.
`supportsRoots()` and `supportsElicitation()` both read the capabilities the
client advertised during the handshake; sampling is stored in that same session
data but had no accessor, so a tool had to issue the request and catch the
refusal.
* [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
* Add resource_link content block
The spec's `resource_link` content type (protocol revision 2025-06-18,
still present in 2025-11-25) had no corresponding schema class: it lets a
tool result or prompt message reference a resource by URI/name without
embedding its full contents, the way `EmbeddedResource` does. Without it,
tools returning many or large resource references (e.g. search results
over a DAM) are stuck smuggling URIs through text/structured content.
Add `Mcp\Schema\Content\ResourceLink`, mirroring the spec's `Resource`
shape (uri, name, title, description, mimeType, annotations, size, icons,
_meta) with a fixed `type: "resource_link"`, following the conventions of
the sibling `EmbeddedResource`/`ResourceDefinition` classes.
Register it everywhere `resource` content blocks are (de)serialized by
type per the spec's `ContentBlock` union:
- `CallToolResult::fromArray()`
- `PromptMessage` (constructor type, `fromArray()`, phpstan types)
- `PromptResultFormatter` (typed-array and direct-instance paths)
`SamplingMessage`/`CreateSamplingMessageResult` are intentionally left
unchanged: the spec's `SamplingMessageContentBlock` does not include
`ResourceLink`.
Fixes#399
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Add resource_link example coverage to discovery-userprofile
Add a lookup_user tool to the discovery-userprofile example: given a
userId, it returns a short text summary plus a resource_link pointing
at the existing user://{userId}/profile resource template, instead of
embedding the profile. This mirrors the PR's motivating use case (a
tool referencing many/large resources by URI rather than inlining
them) and exercises resource_link through the example's own inspector
snapshot tests (tools_call-lookup_user[_not_found], tools_list).
Wiring this up surfaced a real bug: ToolReference::extractStructuredContent()
passed any raw array return value straight through as structuredContent,
even when it held Content instances (e.g. the TextContent/ResourceLink
pair above). That serializes to a JSON list, which fails the spec's
requirement that structuredContent be an object - the inspector's MCP
client rejected the tool call outright until fixed. Skip structuredContent
extraction whenever the raw result contains a Content item, since those
are already represented in `content` and were never meant to double as
structured data.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Alex Rothberg <51059+cancan101@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
* [Client][Server] Add Roots support
Wire up the MCP "roots" capability on both sides:
Client (php-sdk as client):
- RootsCallbackInterface + ListRootsRequestHandler answer server roots/list
requests, mirroring the Sampling handler.
- Client::sendRootsListChanged() emits notifications/roots/list_changed.
Server (php-sdk as server):
- ClientGateway::listRoots() requests the client's roots, and
supportsRoots() reports whether the client advertised the capability,
normalizing the stored capabilities to an array so an empty
capabilities object (\stdClass) doesn't cause a TypeError.
- Add ListRootsResult::fromArray() (used by listRoots()).
- ListRootsRequestHandler forwards RootsException messages to the server
(new Mcp\Exception\RootsException), mirroring SamplingRequestHandler.
- Client::sendRootsListChanged() throws when the client did not advertise
the roots.listChanged capability.
Examples, docs and tests:
- examples/README/docs advertise
`new ClientCapabilities(roots: true, rootsListChanged: true)` before
sending notifications/roots/list_changed.
- CHANGELOG entry for Roots (unreleased 0.7.0 section at the time).
- Unit tests for capability serialization/round-trip, sendRootsListChanged
gating, and RootsException message forwarding.
phpunit, php-cs-fixer and phpstan green.
* [Client][Server] Address review: schema validation, changelog section, connection guard, working example
Responds to chr-hertel's review of the Roots support:
- ListRootsResult::fromArray() rejects non-array root elements instead of
accepting malformed entries silently.
- CHANGELOG entry moved to the next unreleased section as the release
train advanced past it (0.7.0 -> 0.8.0).
- Client::sendRootsListChanged() went straight to
Protocol::sendNotification(), which sends via
`$this->transport?->send()` -- on a client that is not connected the
notification was silently dropped. It now throws a ConnectionException
like sendRequest() does.
- The stdio example only advertised the roots capability, so the
roots/list handler never actually ran. The client-communication demo
server gets an `inspect_workspace_roots` tool that calls
ClientGateway::supportsRoots()/listRoots(); the example calls it, so
the server actually issues roots/list and the client answers it.
Dropped the try/catch wrapper from the example.
- ClientTest's connected-client mock now goes through setState() so
isConnected() reflects a real handshake instead of a stubbed flag.
phpunit, php-cs-fixer and phpstan green.
* Preserve optional content fields in PromptResultFormatter
The formatter's typed-content path rebuilt each Content object from only
its required fields, silently dropping everything else a prompt returned
(annotations on every type, _meta and explicit mimeType on embedded
resource contents). Delegate to the schema classes' fromArray() instead,
keeping the historical mimeType defaulting and RuntimeException-with-
index error contract.
ImageContent was the only content class without annotations support, so
it gains the same constructor/fromArray()/jsonSerialize() handling as
TextContent and AudioContent.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* Reword CHANGELOG entry to be user-facing
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
HttpTransport looked for an event boundary with strpos($buffer, "\n\n") and
split event lines on "\n". Servers that terminate SSE lines with CRLF therefore
never produced a recognised event: the response accumulated in the buffer, no
message was ever dispatched, and connect() failed with "Initialization failed:
Request timed out".
This affects every MCP server built on the Python SDK. FastMCP's
streamable_http_app() returns sse_starlette's EventSourceResponse without a sep
argument, and its DEFAULT_SEPARATOR is "\r\n". The bug is invisible from within
this repository because the PHP server implementation emits LF, so client and
server agree in the test suite while disagreeing with most servers in the wild.
The SSE specification requires a parser to accept CRLF, LF or CR, so the
previous behaviour was non-compliant rather than merely unlucky.
Event extraction now accepts all three terminators, choosing whichever appears
first so a buffer split mid-sequence is handled correctly, and line splitting
uses the same set. A stream that ends without a trailing blank line now
dispatches its final event instead of discarding it.
Adds the first tests for src/Client/Transport/, covering LF, CRLF and CR
framing, an id field, a comment preamble, and a missing trailing blank line.
Without the fix four of the six fail with the timeout above.
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
* Never let a throwable escape Protocol::processInput()
* Validate payload types in the schema hydration methods
* Stop leaking handler exception messages to the client
* [Schema] Always emit {} for empty tool schema properties
Normalize empty properties arrays (including nested object schemas and
outputSchema) in Tool::__construct so tools/list never serializes
invalid JSON Schema properties: [].
Fixes#405
* [Schema] Normalize every empty sub-schema, not only properties
Walking into `items` and `additionalProperties` without normalizing an empty
sub-schema at those positions left the `[]`-instead-of-`{}` bug intact one
level down. Most notably it regressed #151 on a `Tool::fromArray()`
round-trip: `SchemaGenerator` emits `items: {}` for untyped array parameters,
which decodes to `[]` and was re-serialized as `[]` — the exact schema strict
clients reject.
Empty sub-schemas are now replaced with a `\stdClass` at every schema
position, and the keyword list is completed to cover draft-07 through
2020-12: `$defs`, `definitions`, `dependentSchemas`, `patternProperties`,
`propertyNames`, `contains`, `not`, `if`/`then`/`else`, `additionalItems`,
and `unevaluatedItems`/`unevaluatedProperties`. Keywords holding plain JSON
arrays (`allOf: []`, `enum: []`, `dependentRequired`) keep encoding as `[]`.
---------
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
The constructor guarded its unwritable-directory case with the global
`\RuntimeException`, the only throw in `src/` still outside
`Mcp\Exception\ExceptionInterface`. A consumer wrapping server setup in a
`catch (ExceptionInterface)` missed it and got an unhandled SPL exception on
a misconfigured session directory instead.
`Mcp\Exception\RuntimeException` extends `\RuntimeException`, so this is
additive: existing `catch (\RuntimeException)` blocks keep working.
The constructor had no test coverage at all, so this adds one for the throw
plus the directory-creation and write/read paths around it.
processInput() called fgets($this->input) with no length argument. PHP
fgets() reads until a newline or EOF, so a peer that streams bytes
without ever sending a newline forced the whole stream into a single
allocation and exhausted the process memory limit (GHSA-vm75-qjc7-xh6w).
Bound each read with fgets($this->input, $this->maxLineBytes) (default
4 MiB, configurable via the constructor). When a read fills the cap with
no trailing newline the line exceeds the limit: discard it and keep
discarding one bounded chunk per tick until its terminating newline,
rather than buffering it. The discard is stateful so the run loop keeps
servicing fibers and outgoing messages instead of blocking on a drain
loop, and the over-length line is logged once.
Reimplements tonghuaroot's advisory fix: makes the cap configurable
rather than a hardcoded constant, drains the over-length line without an
inner blocking loop (responsive run loop, single log line), and adds
regression tests.
Co-authored-by: tonghuaroot <23011166+tonghuaroot@users.noreply.github.com>
processInput() appended every 8 KiB stdout chunk to $inputBuffer and only
drained it on a "\n". A spawned server that streams stdout without ever
emitting a newline grew the buffer without bound, exhausting client
memory (GHSA-6vrr-g4hw-f3hj).
Cap the buffer (default 4 MiB, configurable via the constructor). When
appending the next chunk would exceed the cap before a newline is seen,
abort the read and resolve the in-flight request with an error
immediately, so the caller fails fast instead of spinning until its
request timeout.
Based on localden's suggested fix in the advisory: makes the cap
configurable, but resolves the pending request with an error (keeping
runRequest's Response|Error contract) instead of throwing a
TransportException out of the read loop, and leaves connection teardown
to the caller. Adds regression tests.
Co-authored-by: localden <53200638+localden@users.noreply.github.com>
processSSEStream() appended every 4 KiB chunk to $sseBuffer and only
flushed on the "\n\n" SSE event delimiter. A server streaming data
without ever sending the delimiter grew the buffer without bound,
exhausting client memory (GHSA-7m52-jw36-44r3).
Cap the buffer (default 8 MiB, configurable via the constructor). When
appending the next chunk would exceed the cap before a complete event is
seen, abort the stream and resolve the in-flight request with an error
immediately, so the caller fails fast instead of spinning until its
request timeout.
Reimplements tonghuaroot's advisory fix: makes the cap configurable
rather than a hardcoded constant, fails the pending request fast instead
of relying on the timeout, and adds regression tests.
Co-authored-by: tonghuaroot <23011166+tonghuaroot@users.noreply.github.com>
* [Server] Expose OAuth protected resource metadata as a reusable request handler
* docs: show handler DI wiring in Symfony/Laravel controller examples
* Focus PR on transport refactor: drop docs and example changes
* docs: add changelog entry for ProtectedResourceMetadataHandler
* [Tests] Bump MCP Inspector to 0.22.0 for 2025-11-25 protocol
The pinned inspector 0.17.2 predates the protocol version bump to
2025-11-25 (v0.6.0) and rejects the handshake with "Server's protocol
version is not supported", failing every inspector snapshot test. 0.22.0
negotiates the current protocol; the full inspector suite passes against
it (95 tests, 7 pre-existing skips).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* [Examples] Demo pre-built instance handler in combined-registration
Extends the combined-registration example with a third handler style:
a pre-built object instance `[$instance, 'method']`, alongside the
existing discovered and manual class-string handlers. PreconfiguredGreeter
takes a scalar constructor argument neither the container-less
`new $className()` fallback nor the auto-wiring container can build, so it
can only be registered as an already-constructed instance — exercising the
resolver path added in the parent branch.
Adds an inspector snapshot case (tools/call instance_greeter) and updates
the tools/list snapshot.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Array tool parameters without an inferable element type generated `{"type":"array"}` with no `items`, which strict MCP clients (VS Code / Copilot) reject. Always emit `items` (`{}` when the element type is unknown) and recover the element type for nullable typed arrays such as `string[]|null`.
Fixes#151
Builder::build() runs all loaders eagerly and snapshots capabilities from
the resulting registry. Both are computed once, when the server is built.
Under a persistent runtime (e.g. FrankenPHP worker mode) the server is
built a single time, so a loader whose data source is not yet ready at
that moment (cold cache, un-warmed metadata) leaves the registry empty for
the whole process — tools/list stays empty while tools/call still works.
Make deferred loading the default behavior of Registry itself: it takes a
loader and runs it on the first read (has*/get*), moving loading to
request time when the application is initialized. The load runs once; the
loaded flag is set only after a successful load, so a transient failure is
retried on the next read. A re-entrancy guard lets loaders that read the
registry during their own run (e.g. discovery's identity check) observe
the partial state instead of recursing. Registrations made before the
first read survive it.
Expose the switch on Builder via setLazyLoading() (default on) so callers
can opt back into eager loading at build time. In lazy mode capabilities
are advertised from the configured sources so the initialize handshake
does not force a load; in eager mode (or for a registry supplied via
setRegistry(), which is always loaded eagerly) they are read from the
loaded registry.
* [Client] Add client-side elicitation support
The SDK could send elicitation/create requests from a server tool via
ClientGateway::elicit(), but the client could not receive them: there was
no request handler, and ElicitRequest was not registered in MessageFactory,
so incoming elicitation/create messages failed to parse.
This adds the client half, mirroring the existing Sampling pattern:
- Register ElicitRequest in MessageFactory so elicitation/create parses.
- ElicitationRequestHandler wraps a user callback and returns an
ElicitResult (accept/decline/cancel) or an Error.
- ElicitationCallbackInterface defines the callback contract.
- ElicitationException forwards a specific message to the server; any
other throwable returns a generic error.
Includes unit tests, a runnable client example against the elicitation
demo server, and client docs/README updates.
* [Client] Simplify elicitation example labelFor() per review
Type the parameter as AbstractSchemaDefinition and read ->title directly
instead of matching on each concrete definition type. title is a required
non-null string on the base class, so the match and the $name fallback were
redundant.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
* [Schema] Fix Implementation::fromArray rejecting falsy-but-valid name/version
`empty()` treats the string "0" as empty, so a valid clientInfo/serverInfo
with `"version": "0"` (or `"name": "0"`) was rejected with an
InvalidArgumentException. During initialize this aborted request parsing and
surfaced as a misleading "A valid session id is REQUIRED" error.
Replace the `empty()` guards with explicit isset/is_string/empty-string checks
so genuinely missing, non-string, and empty values are still rejected while
"0" is accepted. Adds ImplementationTest covering the regression and the
existing validation paths.
Fixes#392
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* [Schema] Suppress PHPStan argument.type on invalid-input tests
---------
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* Allow pre-built instance handlers in element registration
`HandlerResolver::resolve()` rejected `[$instance, 'methodName']` array
handlers even though the `Handler` type alias and the runtime invoker
already support them, so `Server::builder()->addTool(handler: [$obj, 'bar'])`
threw "Invalid array handler format" at build time.
Relax the array-shape guard to accept an object in slot 0 and normalize it
to its class name for reflection (the same idiom getHandlerDescription()
already uses). This unblocks dependency-injected handler objects that the
container-less `new $className()` fallback cannot build.
Fixes#369
* Use 0.6.1 changelog heading and test instance handler end-to-end
This is a bugfix with no new public API or BC break, so the changelog
entry belongs under 0.6.1 rather than a new 0.7.0 section.
Add an end-to-end test that registers a pre-built instance handler with a
constructor dependency the container-less new $className() fallback cannot
satisfy, then drives a real tools/call through CallToolHandler and asserts
the injected instance is the one invoked.
* Address review: reject Closure array handlers, fix abstract-method message
- HandlerResolver: extract the array-handler guard into a readable
$hasValidTarget check that accepts strings and objects but excludes
\Closure, so [$closure, 'method'] falls through to the format error
instead of the misleading "method not found in class Closure".
- Fix the abstract-method rejection message ("must be abstract" ->
"must not be abstract"), a pre-existing typo in the same branch.
- Tighten the CHANGELOG entry wording.
- Cover Closure rejection with a regression test.
* Move instance-handler entry under 0.7.0 changelog heading
Per review: registering pre-built instance handlers is a feature, not a
patch, so it belongs in a minor release heading.
Record ADR 0001: the MCP server is an OAuth 2.1 Resource Server that MAY
delegate to an upstream authorization server, and will NOT issue tokens or
act as an Identity Provider. Gives a single citable ruling to decline the
recurring "native authorization server" PRs (e.g. #373).
Also remove the surface signal that invites them: reframe the
OAuthProxyMiddleware class docblock to lead with its delegation intent and
state explicit non-goals (never mints/signs/stores/rotates tokens), and add
a "Scope" section to docs/authorization.md describing the three OAuth roles
and what the SDK does not do.
No behavior change — docblock, docs, and ADR only.
* 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.
A non-template resource resolves to a ResourceReference, which has no completionProviders property; only prompts and resource templates do. Read providers from those instead, returning an empty completion result when a resource has none.