| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
c5dbfb64e5 |
[Server][Capability] Do not announce an externally loaded registry as changed (#490)
* [Capability] Do not announce an externally loaded registry as changed `Registry` suppresses its `*ListChangedEvent`s while it is loading — `dispatch()` returns early on the `loading` guard, so the elements a loader registers are the registry's initial contents rather than a change to them. `testListChangedEventsAreSuppressedDuringTheDeferredLoad` pins that. The guard only covers `Registry::load()`, which needs the loader the constructor took. A registry the caller built cannot be given one that way, so `Builder::resolve()` loads it from the outside instead — by calling `$chainLoader->load($registry)` directly, which never sets the guard. Every element then dispatches on the way in. With a notification bus configured that is not quiet. `PublishingEventDispatcher` turns each event into a published notification, so every `build()` puts one `list_changed` per element on the bus for a registry that did not change. Under PHP-FPM, where the server is built per request and `Psr16NotificationBus` is shared and persistent, every request broadcasts its whole element list to every open `subscriptions/listen` stream and consumes the 256-entry backlog — after which a reader that fell behind silently skips real notifications. Split the guarded body of `load()` into `loadFrom(LoaderInterface $loader)` and route the custom-registry branch through it. `loadFrom()` takes only the `loading` guard, not the `loaded` bookkeeping, which stays with `load()`. The loader it runs belongs to the caller, so it cannot stand in for the one the registry was constructed with: marking the registry loaded would retire a constructor loader that never ran, and would make a second `loadFrom()` — one registry handed to two builders — a silent no-op. Keeping `loaded` out of it also keeps `load()`'s promise that a transient failure is retried on the next read, including when the failing loader reads the registry during its own run. `RegistryInterface` declares no `load()`, so this stays on the concrete `Registry`, and a third-party implementation keeps the path it has today. * Apply batched suggestions from code review Co-authored-by: Christopher Hertel <mail@christopher-hertel.de> |
||
|
|
312c621417 |
[Capability] Suppress list-changed events during the initial registry load (#480)
* [Capability] Suppress list-changed events during the initial registry load * Shorten dispatch() comment to a one-liner * Use multi-line docblock format for dispatch() comment |
||
|
|
f84d8f5aa9 |
[Schema][Server] Close the 2025-11-25 schema gaps and add the 2026-07-28 surface (#421)
* [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. |
||
|
|
becce29c41 |
[Capability] Harden structuredContent extraction (#417)
* 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. |
||
|
|
fc456125e2 |
[Schema] Add resource_link content block (#400)
* 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> |
||
|
|
ff91ca6d60 |
[Server] Defer element loading to first registry read (#389)
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. |
||
|
|
0347dc85b4 |
[Server] Allow runtime-resolved element handlers (#294)
* [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> |
||
|
|
967c5cda4d |
[Server] Untangle origin tracking from Registry (#302)
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. |
||
|
|
fb2c8c2ee4 |
[Schema][Server] Add top-level title to Tool (#288)
* 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> |
||
|
|
c081b90d74 |
Update codestyle based on updated Symfony rules (#229) | ||
|
|
1de4ea933f |
Rename schema to resource in Capability and related classes (#217)
|
||
|
|
c0938a19bd |
feat: Add output schema support to MCP tools (#153) | ||
|
|
7cd281d0c7 |
Rework registry to combine provider and registry interface, move capabilities out and enable Registry injection in Builder (#150) |
Renamed from tests/Unit/Capability/Registry/RegistryTest.php (Previous history)