* 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.
* [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.
* [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>
* [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>
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.
Wrap-up for the v0.6.0 release: capture features/BC breaks merged since
v0.5.0 that were missing from documentation.
- CHANGELOG: add the `title` field on `Resource`/`ResourceTemplate` (#301),
a feature plus three positional-argument BC breaks.
- mcp-elements.md: add the missing `title` parameter to the McpTool,
McpResource, McpResourceTemplate and McpPrompt attribute reference
sections; fix a missing closing paren in an `#[McpPrompt]` example.
- server-builder.md: add `title?` to the `addPrompt()` row of the method
reference table (stale since v0.5.0).
- client.md: bump the protocol-version example to `V2025_11_25` to match
the new default.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* feat: add MCP Apps extension (io.modelcontextprotocol/ui) support
Adds support for the MCP Apps protocol extension, which lets servers
expose interactive HTML UIs as resources rendered by spec-conforming
clients (e.g. Goose) in sandboxed iframes.
- Generic extension plumbing: ServerExtensionInterface and
Builder::enableExtension(), with extensions advertised under
capabilities.extensions during the initialize handshake.
ClientCapabilities/ServerCapabilities gain an extensions field.
- Schema DTOs under Mcp\Schema\Extension\Apps: the McpApps marker,
UiToolMeta, ToolVisibility enum, UiResourceContentMeta,
UiResourceCsp, and UiResourcePermissions (with empty-object
presence markers per spec).
- A worked weather example under examples/server/mcp-apps/ with a
minimal spec-conforming view (ui/initialize handshake, postMessage
JSONRPCMessage objects, and ResizeObserver-driven size reporting).
- docs/extensions.md guide with pointers from index.md and
examples.md to the ext-apps repository for the TypeScript SDK and
richer view-side patterns.
- Unit and inspector snapshot test coverage.
Spec: https://github.com/modelcontextprotocol/ext-apps
* Type UiToolMeta visibility as ToolVisibility enum
Also fix UiResourceContentMeta::jsonSerialize() return phpdoc.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Address review nitpicks for MCP Apps extension
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Apply PR review feedback for MCP Apps extension
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* Add regression tests and CHANGELOG entry for capabilities extensions
- Pin the is_array() guards on extensions in ServerCapabilities and
ClientCapabilities::fromArray() with explicit non-array payload tests.
- Pin the isset()-rejects-null contract in UiResourcePermissions::fromArray().
- Surface the new extensions field on both capability classes in CHANGELOG.
- Inline the ?: idiom in Builder::build() to match the surrounding style.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* [Server] feat: allow runtime handlers
Adds Mcp\Server\Handler\RunTimeHandlerInterface so integrators
(e.g. configuration-driven element sources) can register handlers
whose arguments and execution are resolved at runtime rather than
via PHP reflection of a callable.
ReferenceHandler::handle() dispatches instanceof RunTimeHandler
ahead of the callable/array/string branches, calls filterArguments
to narrow the argument map, and forwards execute() a ClientGateway
built from the active session.
The Registry-layer surface (ElementReference and the four
*Reference subclasses, RegistryInterface, Registry::register*,
ArrayLoader's handler-description helper) is widened to accept the
new type. The Builder/ArrayLoader path keeps its narrow callable
union; exposing runtime handlers there requires reworking
HandlerResolver and is left for a follow-up.
* feat(server): add runtime handler metadata API
Extend RunTimeHandlerInterface with four nullable metadata
accessors (getInputSchema, getOutputSchema, getPromptArguments,
getCompletionProviders) so the loader can obtain element
metadata without reflection.
Add RunTimeHandlerTrait providing null defaults for all four
accessors so single-purpose handlers can override only the
methods relevant to their element kind.
* feat(server): expose runtime handlers via Builder
Widen Builder::addTool, addResource, addResourceTemplate, and
addPrompt to accept RunTimeHandlerInterface instances alongside
the existing closure/array/string handler forms.
Branch ArrayLoader::load() on instanceof RunTimeHandlerInterface
in each of the four registration loops so runtime handlers skip
the reflection-based HandlerResolver/HandlerSchema path and pull
metadata from the interface accessors instead. Require explicit
name and description for runtime handlers and raise
ConfigurationException when missing or when a runtime tool has
no input schema source.
Replace direct $data['handler'] use in error log context with
getHandlerDescription() to avoid serializing large runtime
handler object graphs into log records.
Document the runtime handler API in docs/server-builder.md with a
new Runtime Handlers subsection and add a cross-reference from
docs/mcp-elements.md.
* test(server): cover runtime handler Builder path
Add ArrayLoaderRunTimeHandlerTest covering:
- successful tool registration with handler-supplied input schema,
with kwarg input schema (precedence over the handler), and the
same precedence rule for output schema
- ConfigurationException for tools missing name, description, or
any input schema source
- successful resource registration via Builder kwargs and the
matching missing-name failure mode
- successful resource template registration with completion
providers sourced from the handler and the missing-description
failure mode
- successful prompt registration with arguments and completion
providers sourced from the handler, plus the missing-name
failure mode
- a trait-only fixture verifying the four metadata accessors
return null by default
Update existing ReferenceHandlerTest anonymous classes to use
RunTimeHandlerTrait so they satisfy the widened interface.
* refactor(server): split runtime handler interface
Splits RunTimeHandlerInterface into a minimal base contract (only
execute()) plus element-specific subtypes: RunTimeToolHandlerInterface,
RunTimePromptHandlerInterface, and
RunTimeResourceTemplateHandlerInterface. Each subtype declares only
the metadata accessors relevant to its element kind, so a tool
handler no longer has to no-op out prompt or template methods.
Drops the now-redundant RunTimeHandlerTrait and removes
filterArguments; execute() receives the full argument map directly.
Updates ArrayLoader, ReferenceHandler, and Builder type signatures
to use the per-element interfaces, and rewrites the Runtime
Handlers documentation accordingly.
* refactor(server): rename runtime handler interfaces to Runtime casing
Renames RunTimeHandlerInterface and its element-specific subtypes to
Runtime casing, adds a dedicated RuntimeResourceHandlerInterface so
addResource() rejects mismatched runtime handlers at the type level,
and strips _session and _request from arguments forwarded to runtime
handlers. Hardens ArrayLoader to re-throw ConfigurationException
without wrapping, and extracts inline test fixtures into
tests/Fixtures/Runtime/.
* chore: please the linting gods
* test(server): use Uuid::v4 for symfony/uid 5.4 compatibility
Uuid::v7() was added in symfony/uid 6.2 and breaks the Symfony 5.4
matrix job. Match the convention used elsewhere in the suite.
* refactor(server): split ArrayLoader registration
Extract per-element preparation into dedicated private prepare*
methods for tools, resources, templates, and prompts. Factor the
shared required-field assertion and reflected name/description
resolution into helpers.
* refactor(server): non-null runtime handler types
Drop nullable return types on RuntimeToolHandlerInterface::
getInputSchema(), RuntimePromptHandlerInterface::
getPromptArguments()/getCompletionProviders(), and
RuntimeResourceTemplateHandlerInterface::
getCompletionProviders() in favor of plain arrays.
ArrayLoader no longer needs the null-coalescing
fallbacks, and NullSchemaToolHandler plus its
ConfigurationException test become redundant.
* doc: update docs/server-builder.md
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* feat: peer revie feedback
Introduce a new `Builder::add(...)` pattern for a more generic runtime
handler.
* refactor(server): apply PR 294 review feedback
Move per-interface handler dispatch from ReferenceHandler into
ExplicitElementLoader by wrapping each ElementHandlerInterface in a
Closure that satisfies the existing callable contract, revert the
*Reference / Registry handler-type widening PR 294 introduced, throw
Mcp\Exception\InvalidArgumentException (not \TypeError) on mismatched
Builder::add() pairings, and rename two classes for clarity:
* Mcp\Capability\Registry\Loader\ArrayLoader -> ReflectedElementLoader
* Mcp\Schema\Resource -> Mcp\Schema\ResourceDefinition (no alias)
ReferenceHandler::prepareArguments() now injects ClientGateway by type
and binds an `array $arguments` / `array $variables` closure parameter
from the leftover inbound arguments. This addresses Antoine's coupling
concern (ReferenceHandler no longer knows about the four handler
interfaces) and Chris's package-exception preference, and clears the
phpdoc reserved-word collision Antoine flagged on the resource schema
class. Existing tests are re-targeted to exercise the closure path
through ExplicitElementLoader / ReferenceHandler.
* doc: address PR 294 review feedback
Apply Chris's line-level suggestions on docs/server-builder.md
(rewrap to 120 chars, smoothed Drupal mcp module name-drop in the
explicit-element registration section, exception name reads
Mcp\Exception\InvalidArgumentException), rewrap docs/mcp-elements.md
to 120 chars, and add 0.6.0 CHANGELOG entries covering the
Builder::add() entry point, the new handler interfaces, the new
ExplicitElementLoader, plus three BC breaks (Resource ->
ResourceDefinition rename, ArrayLoader -> ReflectedElementLoader
rename, mismatched-pairing exception swap).
* refactor: address self-review feedback
* CHANGELOG: drop spurious [BC Break] entry for the exception
type Builder::add() raises (method is new in this PR).
* docs/server-builder: revert wrap-only edits to pre-existing
main content; keep 120ch wrapping only for new sections.
* ExplicitElementLoader: trim verbose class docblock.
* ReferenceHandler: rename SPLAT_PARAMETER_NAMES constant to
ARGUMENT_BAG_PARAMETERS.
* refactor: rename CallableHandler to Handler
* style: fix phpdoc param alignment
* refactor: inline $reference->handler access
* fix: maintainer review feedback
docs: mention ExplicitElementLoader in comment
docs: move Drupal reference to README list
docs: drop implementation-only changelog entry
docs: revert rewrap noise from mcp-elements.md
* style: fix phpdoc param alignment
---------
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
Co-authored-by: soyuka <soyuka@users.noreply.github.com>
* [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>
Make session GC probability configurable via gcProbability and gcDivisor
parameters, mirroring PHP's session.gc_probability/session.gc_divisor.
Exposed through both SessionManager constructor and Builder::setSession().
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
* Add optional namePatterns capability to discovery so that the default scan for `*.php` files can be overridden.
* add default to namePatterns docs
* add an error check if we manage to pass in an empty list of patterns
* add unit tests (and a static entry to classmap for composer.json so it autoloads from a non .php file for the test)
* run php-cs-fixer
* change how default namePatterns are set and make sure all the annotations are correct
* Fix bad whitespace
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* switch to a const default instead of nullable with a check in the function to convert null to a default
* make sure we handle empty arrays
* formatting fixes
* Apply suggestion from @chr-hertel
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* Add changelog entry
---------
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* feat(schema): add top-level title to Tool
Mirror PR #278's Prompt change for Tool:
- Add optional ?string $title to Mcp\Schema\Tool between $name
and $inputSchema. fromArray() now reads $data['title'];
jsonSerialize() emits 'title' right after 'name'. The
@phpstan-type ToolData gains title?: string.
- Add ?string $title to the #[McpTool] attribute between $name
and $description.
- Note ToolAnnotations::$title as deprecated-for-display in
favor of Tool::$title per MCP spec 2025-06-18 (PHPDoc only,
field retained for BC).
Phase 1 of plan 01--tool-title-spec-compliance. Later phases
update Discoverer, Builder::addTool(), ArrayLoader, and the
conformance fixture to match the new signature.
* feat(server): thread title through discovery
- Discoverer::processMethod() now propagates McpTool::$title
into every discovered Tool via named arguments.
- Builder::addTool() accepts ?string $title between $name and
$description. [BC Break] positional callers passing the old
$description as 3rd positional argument must switch to named
arguments, matching the precedent set for addPrompt() in
0.5.0.
- tests/Conformance/server.php migrated to named-argument form
for every addTool() call.
Phase 2 of plan 01--tool-title-spec-compliance.
* feat(loader): forward title in ArrayLoader
ArrayLoader now reads 'title' from each tool config entry and
passes it into the Tool constructor, completing the wiring
from Builder::addTool() through array-driven registration.
The $tools @param array-shape typedef gains title: ?string
between name and description.
Phase 3 of plan 01--tool-title-spec-compliance.
* test(schema): cover Tool.title end-to-end
- New tests/Unit/Schema/ToolTest.php: constructor round-trip,
jsonSerialize key-order when title set vs null, fromArray
tolerance.
- New tests/Unit/Capability/Discovery/DiscovererToolTitleTest
plus a TitleFixture class verifying McpTool(title: ...)
propagates through discovery into the registered Tool.
- New tests/Unit/Capability/Registry/Loader/ArrayLoader...
test verifying array-driven title propagation.
- Extend McpToolTest for title named-arg and default-null.
- Extend BuilderTest with addTool(title: 't') propagation.
- Update tests/Unit/.../RegistryTest, CallToolHandlerTest,
ListToolsHandlerTest and examples/.../server.php
new Tool(...) call sites to pass title (named args) so
they match the new constructor signature.
- CHANGELOG 0.6.0 section: feature bullet + [BC Break]
note for addTool() signature, mirroring 0.5.0 Prompt
entries.
- docs/server-builder.md: addTool() row and prose now
list title? between name and description.
Phase 4 of plan 01--tool-title-spec-compliance. All 730
phpunit tests pass; remaining phpstan warnings are
pre-existing and unrelated to Tool.title.
* refactor(schema): make Tool.title non-BC-breaking
Move `title` to the end of the Tool, Builder::addTool, and McpTool
attribute constructors with a default of null. This preserves
positional-argument compatibility and removes the need for
`title: null` boilerplate at call sites. JSON serialization order
(name, title, inputSchema, ...) is unchanged.
Also tighten the new tests: parameterize ToolTest with data
providers, fold the Discoverer title fixture into the existing
DiscoverableToolHandler, and drop the reflection-heavy Builder
test that overlapped with ArrayLoaderToolTitleTest.
* fix: move title after name
---------
Co-authored-by: DDEV User <nobody@example.com>
The MCP 2025-11-25 specification defines an optional `title` property on
Prompt for human-readable display in UI contexts, distinct from the
programmatic `name` identifier. This was missing from the SDK.
BC Break: Builder::addPrompt() signature changed — $title parameter added
between $name and $description. Callers using positional arguments for
$description must switch to named arguments.
Closes#276
* docs: add comprehensive client SDK documentation
- Create new client documentation with examples and API reference
- Restructure README for better clarity and flow
- Add client examples to documentation index
- Update roadmap to mark client component as complete
* Update README.md
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* Apply suggestions from code review
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
---------
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* Add Middleware handlers to StreamableHttpTransport
* OAuth Implementation based on middleware
* OAuth Implementation based on middleware
* Add Middleware handlers to StreamableHttpTransport
* OAuth Implementation based on middleware
* OAuth Implementation based on middleware
Signed-off-by: Volodymyr Panivko <sveneld300@gmail.com>
* Address PR review feedback for OAuth middleware
* Apply php-cs-fixer to satisfy QA
* Use Mcp exception classes in OAuth middleware
* Refactor OAuth HTTP stack and add Microsoft example policies
* Fix QA PHPStan findings in OAuth examples and auth middleware
* Require OIDC discovery in JWKS provider and refine OAuth proxy behavior
* Remove local development docker artifacts from VCS
* Revert .gitignore changes for local docker files
* Fix body retrieval in OAuthRequestMetaMiddleware for proper string conversion
Signed-off-by: Volodymyr Panivko <sveneld300@gmail.com>
* Address OAuth PR review feedback and align example configs
* Fix QA style issues and add authorization docs
* Fix PHPStan typing issues in OAuth middleware
* Remove duplicate Middleware namespace, consolidate under Http\Middleware
Remove old Mcp\Server\Transport\Middleware\ classes that were duplicated
in Mcp\Server\Transport\Http\Middleware\ and Http\OAuth\. Update docs
to reference the correct namespaces.
* Address PR review: replace Throwable catch with specific exceptions, add JSON_THROW_ON_ERROR
- JwtTokenValidator: replace catch(\Throwable) with explicit
\InvalidArgumentException|\UnexpectedValueException|\DomainException,
letting RuntimeException from JwksProvider propagate as infrastructure errors
- OAuthProxyMiddleware: add \JSON_THROW_ON_ERROR to json_encode for metadata response
- Update tests to expect RuntimeException for JWKS infrastructure failures
---------
Signed-off-by: Volodymyr Panivko <sveneld300@gmail.com>
Co-authored-by: Volodymyr Panivko <volodymyr.panivko@togethernetworks.com>
- Add ElicitAction enum (accept/decline/cancel)
- Add schema definitions for elicitation fields (string, number, boolean, enum)
- Add ElicitationSchema wrapper for requestedSchema
- Add ElicitRequest and ElicitResult for elicitation/create method
- Update ClientCapabilities to support elicitation capability
- Add elicit() method to ClientGateway
- Store client capabilities in session during initialization
- Add comprehensive unit tests
- Add elicitation example server with book_restaurant, confirm_action, and collect_feedback tools
* Add API documentation generation with phpDocumentor
- Add phpDocumentor configuration and `docs` Makefile target
- Generate docs during CI to catch errors before releases
- Set up GitHub Pages with Jekyll for hosting generated docs
- Add GitHub Actions workflow to deploy docs to GitHub Pages on releases
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix phpDocumentor errors in type annotations
Change class-string union types to use phpDocumentor-compatible syntax
and reorder docblock tags so class descriptions precede `@author` tags.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fix CI: pin phar-io/composer-distributor ^1.0.2
phar-io/composer-distributor 1.0.0 has a bug where it uses the wrong
package version when determining the phpDocumentor download URL,
causing CI to fail with 404 errors when using --prefer-lowest.
Version 1.0.2 fixes this issue.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Integrate markdown guides into phpDocumentor output
Configure phpDocumentor to generate both API documentation and user
guides in a single unified site. This replaces the previous Jekyll-based
approach where API docs were copied into the docs folder.
- Add `<guide>` configuration to `phpdoc.dist.xml`
- Create custom template with "Guides" navigation link
- Replace `docs/index.html` redirect with `docs/index.md` guide index
- Update workflow to publish `build/docs` directly without Jekyll
- Track `.phpdoc/template/` while still ignoring `.phpdoc/cache/`
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
* Fine-tuning for path, config, and layout
---------
Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* fix: standardize error handling across handlers with MCP specification compliance
* Update mcp-elements.md
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* docs: clarify error handling behavior for all element types
* docs: remove unnecessary whitespace in mcp-elements.md
* fix: simplify exception signatures to accept simple messages
* refactor: use specific exceptions in examples for better error handling
* feat: throw exceptions from reference provider instead of returning null
---------
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* 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>
* refactor: integrate cache parameter into setDiscovery() method
- Add cache as 4th parameter to setDiscovery()
- Rename $cache to $discoveryCache for clarity
- Remove separate setCache() method
- Update example to use new API
* docs: update discovery caching documentation to use new API
- Update examples to use cache parameter in setDiscovery() method
- Remove references to separate setCache() method calls
* feat: implement discovery caching with state-based approach
- Add DiscoveryState class to encapsulate discovered MCP capabilities
- Add exportDiscoveryState and importDiscoveryState methods to Registry
- Modify Discoverer to return DiscoveryState instead of void
- Create CachedDiscoverer decorator for caching discovery results
- Add importDiscoveryState method to ReferenceRegistryInterface
- Update ServerBuilder to use caching with withCache() method
- Update tests to work with new state-based approach
- Add example demonstrating cached discovery functionality
- Add PSR-16 SimpleCache and Symfony Cache dependencies
* docs: add comprehensive discovery caching documentation
- Add detailed documentation explaining discovery caching architecture
- Include usage examples for different cache implementations
- Document performance benefits and best practices
- Add troubleshooting guide and migration instructions
- Include complete API reference for all caching components
- Fix PHPStan issues by regenerating baseline
- Apply PHP CS Fixer formatting to all new files
* refactor: address reviewer feedback and clean up discovery caching
- Make DiscoveryState class final
- Cache DiscoveryState objects directly instead of arrays (no serialization needed)
- Rename exportDiscoveryState/importDiscoveryState to getDiscoveryState/setDiscoveryState
- Add getDiscoveryState method to ReferenceRegistryInterface
- Remove TTL parameter from CachedDiscoverer (no expiration by default)
- Remove unused methods from DiscoveryState (toArray, fromArray, merge)
- Simplify ServerBuilder to handle decoration internally
- Make Discoverer.applyDiscoveryState() internal (no longer public API)
- Simplify documentation to focus on user perspective
- Remove unnecessary development comments
- Update all tests to work with new architecture
- All tests pass, PHPStan clean, code formatting applied
* refactor: clean up comments and formatting in server.php example
* refactor: improve code formatting and consistency in discovery classes and example server
* Fix method names in cached discovery example
- Change withServerInfo() to setServerInfo()
- Change withDiscovery() to setDiscovery()
- Change withLogger() to setLogger()
- Fixes PHPStan static analysis errors
* refactor: update method names in ServerBuilder for consistency
- Change withCache() to setCache() in ServerBuilder
- Update example and documentation to reflect method name changes
- Ensure consistency across caching implementation in examples and documentation
* refactor: reorganize examples and fix PHPStan baseline
- Move cached discovery example from examples/10 to examples/09
- Update composer.json autoload-dev namespace mapping
- Fix PHPStan baseline by removing invalid entries for non-existent files
- Update server.php to follow proper example pattern with logging and lifecycle
* fix: correct formatting in server.php