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.
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>
- Add a shields.io badge row to the README header (version, CI, PHP
version, license, conformance scores, protocol/spec) to match the
other official MCP SDKs.
- Expand "PHP Libraries Using the MCP SDK" into a curated, alphabetically
sorted list of downstream projects.
- Add tests/Conformance/bin/score.php, a Symfony Console command that
turns a conformance run's --output-dir into a shields.io endpoint JSON.
- Extend the weekly conformance workflow to score each run and publish
the client/server pass-rate to the orphan `badges` branch that the
README badges read.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
#301 added the `title` field to the `Resource`/`ResourceTemplate` schema
classes and the `McpResource`/`McpResourceTemplate` attributes, but the
manual registration methods on `Builder` were never updated — so manual
registration could not set a resource title, unlike tools and prompts.
Add a `$title` parameter between `$name` and `$description` (matching
`addTool()`/`addPrompt()`) and propagate it through `ArrayLoader` when
constructing the `Resource`/`ResourceTemplate` objects.
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
The MCP specification (2025-11-25) defines an optional title field for
Resource and ResourceTemplate as a human-readable display label, distinct
from name (a short identifier). Tool and Prompt already implement this
field; Resource and ResourceTemplate were missing it.
Changes:
- Add title parameter to Resource and ResourceTemplate constructors
- Add title to fromArray(), jsonSerialize(), and PHPStan type arrays
- Add title to McpResource and McpResourceTemplate attributes
- Pass title through Discoverer when constructing schema objects
- Add tests for deserialization, serialization, and null omission
Fixes#296
Drop the isManual flag from ElementReference and the discovery-state methods
from RegistryInterface. The Registry becomes a flat last-write-wins map;
DiscoveryLoader owns its own owned-set bookkeeping so re-running discovery
only removes elements it itself contributed. Adds ChainLoader for explicit
composition. Manual-over-discovered precedence is preserved via loader
ordering, not a flag on the reference.
The PR pipeline only catches conformance changes when someone opens a
PR. Upstream `@modelcontextprotocol/conformance` releases between PRs
go untested. This adds a weekly cron + `workflow_dispatch` trigger
pinned to `@latest`, and opens a tracking issue on scheduled failures.
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>
* fix: allow URIs without double slash in Resource and ResourceTemplate (RFC 3986)
The URI regex required "://" after the scheme, rejecting valid URIs
like urn:isbn:123, mailto:user@example.com, config:key, and data:
URIs. RFC 3986 only requires ":" after the scheme; the "//" is part
of the authority component which is optional.
Changed both Resource.URI_PATTERN and ResourceTemplate.URI_TEMPLATE_PATTERN
to require ":" instead of "://".
Adds data-provider tests for URIs without double slash in both classes.
Fixes#293
* Reword unit tests
---------
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
* 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>
* style: apply php-cs-fixer to test files
Addresses drift flagged by the default PHP-CS-Fixer config — mostly
adds missing `: void` return types on pre-existing test methods.
No behavioural changes.
* fix: resolve phpstan errors surfaced by qa
- Drop the obsolete `Method ::test*() has no return type specified`
ignore rule — every test method now declares a return type, so
the pattern never matches and phpstan reports it as unmatched.
- Remove `?? []` from two reads of `CallToolRequest::$arguments`;
the property is typed `array` (non-nullable), so the coalesce is
a no-op that phpstan flags.
---------
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
* feat: relax OIDC discovery policy and add Dynamic Client Registration middleware (RFC 7591)
- Add LenientOidcDiscoveryMetadataPolicy for providers that omit
code_challenge_methods_supported (e.g. FusionAuth, Microsoft Entra ID)
- Keep StrictOidcDiscoveryMetadataPolicy RFC-aligned
- Add ClientRegistrationMiddleware handling POST /register and enriching
/.well-known/oauth-authorization-server with registration_endpoint
- Update Microsoft example to use built-in LenientOidcDiscoveryMetadataPolicy
* fix: move metadata policy note under server.php in Files section
Address review comment: the LenientOidcDiscoveryMetadataPolicy bullet
was a behavioral note, not a file entry. Inline it into the server.php
description to keep the Files list consistent.
* fix: address Copilot review comments on ClientRegistrationMiddleware
- Decode JSON with assoc=true for registrar data so nested objects
are associative arrays, not stdClass instances
- Add Cache-Control: no-store to all error responses (400), not just
the success response (201)
- Rewind response body stream before returning unmodified response
when metadata is not valid JSON, preventing empty body on read
* fix: harden ClientRegistrationMiddleware and improve test coverage
- Revert spurious .gitignore trailing newline
- Use JSON_THROW_ON_ERROR consistently in enrichAuthServerMetadata()
- Add comment clarifying the second json_decode in handleRegistration()
- Assert Cache-Control: no-store on registrar exception error response
- Add test for non-object JSON body in metadata enrichment path
- Extract createPlainTextHandler helper for non-JSON response tests
* fix: reject JSON array bodies in metadata enrichment
Treat JSON list arrays (e.g. [] or ["..."]) as invalid metadata in
enrichAuthServerMetadata() to prevent corrupting the response shape
by adding registration_endpoint to a non-object.
* fix: add RFC 7591 error codes, Content-Type validation, and docblock safety warning
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* 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>