[Docs] Render the guides with Zensical instead of phpDocumentor (#414)

* [Docs] Render guides with Zensical, deploy via GitHub Pages actions

phpDocumentor's guide renderer copies the markdown through mostly verbatim:
relative links between pages keep pointing at `*.md` targets that do not exist
in the built site, and nothing validates them, so the published guides are full
of dead links.

Zensical (the Material for MkDocs team's successor to MkDocs) resolves internal
links against the page tree and fails the build on a broken one. `zensical
build --strict` already found four dead links on the first run — three
repo-relative links escaping docs/ (fixed to point at GitHub) and one wrong
in-page anchor.

phpDocumentor stays on for the class-level API reference only; `make docs`
builds the guides into site/ and mounts the reference at site/api/, so its two
header links back to the guides now target the site root.

Deployment moves from pushing a gh-pages branch to the official GitHub Pages
actions, and from release-only to every push on main, with pull requests
building (but not deploying) so a broken link fails review instead of the site.

NOTE: this needs the repository's Pages source switched to "GitHub Actions"
(Settings -> Pages) once.

* [Docs] Adopt the Python SDK's documentation look and feel

The docs site now uses the same theme configuration as
https://py.sdk.modelcontextprotocol.io/ so the language SDKs read as one set
of docs: the MCP mark as logo and favicon, Inter/JetBrains Mono, the
black/slate palette with a three-way (system/light/dark) toggle, instant
navigation, code copy/annotate, and a right-hand table of contents.

The markdown extension set is widened to the same list (tabbed blocks,
task lists, footnotes, emoji/icons, mermaid fences), which the content
restructure builds on.

Styling is otherwise stock: no custom stylesheet, and Zensical's own
`modern` theme variant, pinned explicitly rather than left to the default.

The one departure is code highlighting, which is broken out of the box here:
Pygments only highlights PHP after a `<?php` tag, so the guides — whose code
blocks are almost all fragments — rendered as flat plain text. The `php`
lexer is extended with `startinline`, and complete-file blocks use a
`php-file` lexer that keeps the literal open tag highlighted.

* [Docs] Restructure the guides into task-oriented sections

The guides were ten flat pages, each opening with a hand-maintained table of
contents and each mixing several audiences: `mcp-elements.md` covered tools,
prompts, schema generation and handler-side logging, `transports.md` covered
both transports plus framework integration, and `server-builder.md` covered
configuration, sessions and custom message handlers.

They are now split along the same lines as the Python SDK's documentation
(https://py.sdk.modelcontextprotocol.io/), one topic per page:

  Get started        installation, first server, the Inspector
  Servers            tools, resources, resource templates, prompts,
                     completions, schema generation, registration
  Inside your handler  the ClientGateway, logging
  Running your server  builder, STDIO, HTTP, framework integration,
                     sessions, authorization
  Clients            connecting, transports, capabilities, server-initiated
                     requests, error handling
  Advanced           events, protocol extensions, custom message handlers

Prose is carried over as-is apart from the seams; what is new is the landing
page and one index page per section, which say what the section is for and
where to go next, so no page is a dead end.

The per-page "Table of Contents" lists are gone — the theme renders one from
the headings — and GitHub's `> [!IMPORTANT]` blockquotes became admonitions,
which Zensical renders as callouts rather than plain quotes.

Every code sample and factual claim was then checked against src/ and the
runnable examples, which turned up long-standing errors in the carried-over
prose. Samples that could not run: a prompt using a `system` role (MCP has
only user/assistant), `Mcp\Schema\PromptMessage` (it is under `Schema\Content`)
constructed with an array instead of a single content object,
`Mcp\Capability\Prompt\Completion\ProviderInterface` (it is
`Mcp\Capability\Completion\ProviderInterface`), `new EmbeddedResource(type:,
resource: [...])` (neither parameter exists), a `: resource` return type
(not a PHP type), `#[McpResource]` with a `{path}` variable (that is a
template), a stray quote in the builder example, a `middlewares:` argument
(it is `middleware:`), and `getRequest()->getAttribute()` in the OAuth guide
(no such method — the values arrive on the request meta). Claims corrected:
sampling's `system_prompt` option (it is `systemPrompt`), `SampleMessage`
(it is `SamplingMessage`), `Notification` called an interface (abstract
class), "parameter order matters" for URI templates (bound by name), full
RFC 6570 support (only simple `{var}`), the tool description fallback chain,
`void` returning empty content, a non-zero STDIO exit code, `ErrorEvent`
being null for parse errors, handlers being "prepended", `Psr16StoreSession`,
and PSR-3 log context being sent to the client (it is dropped). Sixteen
`examples/` paths were missing their `server/` segment.

README, the OAuth ADR and one source comment now point at the published site
instead of at markdown files that moved.

* [Docs] Run the docs workflow unfiltered, keep README links relative

The `paths:` filters were mostly noise: `src/**` had to be in the list for
the phpDocumentor build, which meant the workflow ran on nearly every PR
anyway. They also missed two real inputs — `.phpdoc/template/**` and
`composer.lock` — so a template tweak or a phpDocumentor bump could change
the rendered site without triggering a build.

README links go back to relative repo paths. The README is not part of the
Zensical site (`docs_dir` is `docs/`), so those links are only ever resolved
by GitHub and Packagist, where absolute URLs break in-repo navigation for no
gain. The site pointer and the generated API reference stay absolute.

* [Docs] Adopt the doc changes that landed on main into the new structure

Twelve commits landed while the restructure was open, seven of them touching
the flat guides this branch replaces. Renames merged on their own; the three
files that were split apart needed their new sections placed by hand:

- Connection retries, protocol version negotiation, sampling with tools and
  roots from `client.md` into `client/connecting.md` and
  `client/server-requests.md`
- `ResourceLink` and structured output from `mcp-elements.md` into
  `servers/tools.md`
- Protocol version negotiation from `server-builder.md` into
  `run/server-builder.md`

The `setMaxRetries()` note claiming the value is never acted on is gone —
#413 implemented it. Callouts became admonitions and cross-links were
repointed at the new paths, as everywhere else in this branch.

* [Docs] Document the elicitation and roots client examples

Both were missing from the examples guide: the elicitation client predates
this branch, the roots client arrived with #395.

* [Docs] Fold the 2026-07-28 lifecycle into the new structure

Main's stateless-lifecycle.md becomes a docs/lifecycle/ section, and the pages
main touched — deprecations, the middleware split, the client's modern era —
land where the restructure moved them.

* [Docs] Link the Inspector to its documentation, not its repo

* [Docs] Distribute the 2026-07-28 material into the task sections

The Python and TypeScript SDKs file each feature where the task lives and keep
only an era comparison on its own page. Follow them: input-required moves next
to the other handler concerns, caching, subscriptions and era routing to
"Running your server", and one Protocol versions page carries the rest.

* [Docs] Move protocol version negotiation onto the Protocol versions page

The builder page keeps the setProtocolVersion() knob and links out; how a
revision is agreed now sits beside the era it belongs to.

* [Docs] Slim the README to a funnel, turn Examples into an index

* [Docs] Fix the code samples and API listings flagged by the audit

* [Docs] Link the negotiation spec section at latest, not draft
This commit is contained in:
Christopher Hertel 2026-08-20 00:03:54 +02:00 • committed by GitHub
commit 0cd5d56164
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 4245 additions and 4069 deletions

View file

@ -0,0 +1,146 @@
# Talking back to the client
MCP supports various ways a server can communicate back to a client on top of the main
request-response flow.
> **Protocol revision `2026-07-28`.** This page describes the handshake era, where a server
> sends its own JSON-RPC requests to the client. The modern lifecycle removed that: sampling,
> elicitation and roots are carried back inside the *result* instead, and
> `ClientGateway::sample()`, `elicit()` and `listRoots()` raise a `LogicException` there.
> Logging and progress still work as described below — they simply travel on the request's own
> response stream, and the client opts into each. See
> [Asking for input](input-required.md).
## ClientGateway
Every communication back to client is handled using the `Mcp\Server\ClientGateway` and its dedicated methods per
operation. Reach it through method argument injection for `RequestContext`. (A `ClientGateway`-typed parameter is
injected too, but unlike `RequestContext` it is not excluded from the generated input schema, so it would show up as
an argument of your tool.)
Every reference of a MCP element, that translates to an actual method call, can just add an type-hinted argument for the
`RequestContext` and the SDK will take care to include the gateway in the arguments of the method call:
```php
use Mcp\Capability\Attribute\McpTool;
use Mcp\Server\RequestContext;
class MyService
{
#[McpTool(name: 'my_tool', description: 'My Tool Description')]
public function myTool(RequestContext $context): string
{
$context->getClientGateway()->log(...);
```
## Request metadata
`RequestContext` also carries what the current request said about itself, which is useful when a feature is only
available from a certain revision on:
```php
use Mcp\Schema\Enum\ProtocolVersion;
if ($context->getProtocolVersion()->isAtLeast(ProtocolVersion::V2026_07_28)) {
// e.g. a bare list is only valid as `structuredContent` from this revision on
}
```
Two more accessors read what the client declared, and both work in either
[protocol era](../protocol-versions.md) — negotiated once during the handshake, or declared per request from
`2026-07-28` on:
```php
$context->getClientCapabilities(); // what this client declared, or null in the handshake era
$context->getTraceContext(); // traceparent / tracestate / baggage, verbatim
```
`ClientGateway`'s capability probes — `supportsElicitation()`, `supportsSampling()`, `supportsRoots()` and the
sub-capability variants — read the same declaration.
W3C trace context is passed through exactly as it arrived, and echoed onto every notification the request causes,
so a span stays joined across the response stream. Reading it adds no OpenTelemetry dependency — the values are
strings.
## Sampling
> **Deprecated** since protocol revision `2026-07-28` ([SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577)), earliest removal `2027-07-28`. Sampling keeps working until then; new integrations should call an LLM provider's API directly instead.
With [sampling](https://modelcontextprotocol.io/specification/2025-11-25/client/sampling) servers can request clients to
execute "completions" or "generations" with a language model for them:
```php
$result = $clientGateway->sample('Roses are red, violets are', 350, 90, ['temperature' => 0.5]);
```
The `sample` method accepts four arguments:
1. `message`, which is **required** and accepts a string, an instance of `Content` or an array of `Mcp\Schema\Content\SamplingMessage` instances.
2. `maxTokens`, which defaults to `1000`
3. `timeout` in seconds, which defaults to `120`
4. `options` which might include `systemPrompt`, `preferences` for model choice, `includeContext`, `temperature`,
`stopSequences`, `metadata`, `tools`, and `toolChoice`
Both `tools`/`toolChoice` and `includeContext` are gated on what the client advertised, so check before sending:
```php
if ($clientGateway->supportsSamplingTools()) {
$result = $clientGateway->sample($messages, options: ['tools' => $tools]);
}
```
A server **must not** send `tools` or `toolChoice` to a client that did not advertise `sampling.tools`. The
`includeContext` values other than `none` are soft-deprecated and should only be sent when the client advertises
`sampling.context` — `supportsSamplingContext()` reports that one.
### Tool loops
When the model wants to call a tool, the result comes back with `stopReason: 'toolUse'` and one or more
`ToolUseContent` blocks. Execute them, then send a follow-up request with the assistant's message and a user message
carrying a matching `ToolResultContent` for every `ToolUseContent`:
```php
$messages[] = new SamplingMessage(Role::Assistant, $result->content);
$messages[] = new SamplingMessage(Role::User, [new ToolResultContent($toolUse->id, [new TextContent($output)])]);
```
The specification is strict about the shape of that exchange: tool results may not be mixed with other content in a
message, and every tool use must be answered before the conversation continues. `sample()` checks these rules before
sending and throws an `InvalidArgumentException` rather than letting the client reject the request with `-32602`.
Use `$result->getContentBlocks()` to iterate the response regardless of whether it holds one block or a list.
[Find more details to sampling payload in the specification.](https://modelcontextprotocol.io/specification/2025-11-25/client/sampling#protocol-messages)
## Logging
> **Deprecated** since protocol revision `2026-07-28` ([SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577)), earliest removal `2027-07-28`. Logging keeps working until then; new integrations should log to stderr (stdio) or use OpenTelemetry instead.
The [Logging](https://modelcontextprotocol.io/specification/2025-06-18/server/utilities/logging) utility enables servers
to send structured log messages as notification to clients:
```php
use Mcp\Schema\Enum\LoggingLevel;
$clientGateway->log(LoggingLevel::Warning, 'The end is near.');
```
## Progress
With a [Progress](https://modelcontextprotocol.io/specification/2025-06-18/basic/utilities/progress#progress)
notification a server can update a client while an operation is ongoing:
```php
$clientGateway->progress(4.2, 10, 'Downloading needed images.');
```
Progress is opt-in by the client in both eras: it sends a `progressToken` with the request, and without one this
call sends nothing.
## Notification
Lastly, the server can push all kind of notifications, that extend the abstract `Mcp\Schema\JsonRpc\Notification` class
to the client to:
```php
$clientGateway->notify($yourNotification);
```

42
docs/handlers/index.md Normal file
View file

@ -0,0 +1,42 @@
# Inside your handler
The methods you register are ordinary PHP methods, but they are not cut off from the
protocol. Type-hint a `Mcp\Server\RequestContext` argument anywhere in the signature and
the SDK passes it in — that object is the way back to the client mid-request.
```php
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Content\TextContent;
use Mcp\Server\RequestContext;
#[McpTool]
public function summarize(string $text, RequestContext $context): string
{
$context->getClientLogger()->info(\sprintf('Summarizing %d characters', \strlen($text)));
$result = $context->getClientGateway()->sample("Summarize:\n\n".$text, 500);
// `content` is TextContent|ImageContent|AudioContent (or ToolUseContent
// blocks when the client samples with tools)
return $result->content instanceof TextContent ? $result->content->text : '';
}
```
Two caveats on this example: clients drop log messages below `warning` unless they raise
the level first (see [Logging](logging.md)), and `sample()` belongs to the features
[deprecated by revision `2026-07-28`](../protocol-versions.md#deprecations) — on that
revision it throws, and [Asking for input](input-required.md) is the way to write it
instead.
* **[Talking back to the client](client-communication.md)** — the `ClientGateway`:
asking the client's model for a completion (sampling), reporting progress on a long
call, and sending notifications.
* **[Logging](logging.md)** — structured PSR-3 log messages that surface in the client,
not in your server's log file.
* **[Asking for input](input-required.md)** — returning an `InputRequiredResult` when a
handler needs elicitation, sampling or roots. Written that way, one handler serves both
[protocol eras](../protocol-versions.md).
Handlers that need application services (a database connection, an API client) get them
from the container instead; see
[Service dependencies](../run/server-builder.md#service-dependencies).

View file

@ -0,0 +1,111 @@
# Asking for input
Some handlers cannot finish in one go: they need the user to confirm something, fill in a
form, name a directory, or have the client's model draft a paragraph. The way to write that
is to **return** the ask — an `InputRequiredResult` naming what you need — and read the
answer off `RequestContext` when the call comes back.
Write it that way once and it serves both [protocol eras](../protocol-versions.md).
Revision `2026-07-28` has no server-initiated requests at all, so the client retries the
original call carrying the answers; the specification calls that a multi round-trip request
(MRTR). On a handshake-era connection the SDK fulfils the same ask over that connection's own
channel instead. Your handler does not fork on which — see
[What a handler forks on](#what-a-handler-forks-on).
```php
use Mcp\Schema\Result\CallToolResult;
use Mcp\Schema\Result\InputRequiredResult;
static function (RequestContext $context): CallToolResult|InputRequiredResult {
$answer = $context->getInputContext()?->elicitResult('who');
if (null === $answer) {
return new InputRequiredResult(
['who' => new ElicitRequest('Your name?', $schema)],
requestState: $context->mintRequestState(['asked' => 'who']),
);
}
return new CallToolResult([new TextContent("Hello, {$answer->content['name']}!")]);
}
```
`tools/call`, `prompts/get` and `resources/read` may answer this way; nothing else may.
## Reading the answers
`InputContext` hands them back typed — `elicitResult()`, `samplingResult()`,
`rootsResult()` — and returns `null` for an answer that is absent *or* malformed. Both mean
the same thing to a handler: ask again. `response()` is still there for the raw array.
## `requestState`
Whatever the server needs to remember between rounds. It travels through the client, so it
is attacker-controlled on return; `mintRequestState()` seals it with an HMAC and a TTL, and
a state that fails verification never reaches a handler. Configure the key with
`Builder::setRequestState()`:
```php
->setRequestState($_ENV['MCP_REQUEST_STATE_KEY'], ttl: 600)
```
The **same key must reach every process that might serve the retry**. A per-process random
value works only for a single-process deployment. Nothing secret belongs in the payload —
it is signed, not encrypted.
## Capabilities
A server must not ask for input the client cannot provide. The SDK checks each ask against
the request's declared capabilities and answers `-32021` — with the missing set in
`data.requiredCapabilities` — rather than sending an ask that could never be answered.
Url-mode elicitation needs its own `elicitation.url` declaration; a bare `elicitation` means
form mode only.
## What not to call
`ClientGateway::sample()`, `elicit()`, `elicitUrl()` and `listRoots()` belong to the
handshake era. Calling one under this revision raises a `LogicException` naming
`InputRequiredResult` as the replacement.
## What a handler forks on
Nothing. Tools, resources, prompts, structured output, progress and errors do not care
which era called, and neither does the one thing that looks like it should: **asking the
user something**.
Write it the 2026-07-28 way — return an `InputRequiredResult` naming what you need, read the
answer off `RequestContext::getInputContext()` when the call comes back. On a handshake-era
connection the SDK's input-required shim fulfils the same ask over that connection's own
channel: each embedded request goes out as the real `elicitation/create` /
`sampling/createMessage` / `roots/list`, and the handler is re-entered with the answers under
the keys it asked for. It is on by default;
[`examples/server/elicitation`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/elicitation)
and
[`examples/server/client-communication`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/client-communication)
are written this way and name no era anywhere.
Two things to know about it.
**Re-entry is re-execution.** The handler runs again from the top each round, so it has to
re-derive where it is from what came back rather than from anything it kept. That is already
true of the modern era — the client retries the whole call there — so a portable handler is
written that way regardless. It is only new if you were relying on `ClientGateway::elicit()`
suspending mid-body and keeping your locals; that keeps working untouched, since nothing here
runs unless a handler *returns* an ask.
**Each round holds the request open.** The shim waits for the client's answer inside the
originating request, which on a process-per-request runtime means it holds a worker for as
long as the user takes. That is the same cost `ClientGateway::elicit()` already pays on that
leg, but the shim makes it reachable from handlers that never mention it — so size
`setInputRequiredLimits()` against your pool.
```php
$server = Server::builder()
->setServerInfo('My Server', '1.0.0')
// Re-entries per request, and seconds to wait for one answer.
->setInputRequiredLimits(maxRounds: 4, roundTimeout: 120)
->build();
```
`withoutInputRequiredShim()` turns it off, so such a handler fails on a handshake-era
connection instead of being fulfilled behind your back.

39
docs/handlers/logging.md Normal file
View file

@ -0,0 +1,39 @@
# Logging
> **Deprecated** since protocol revision `2026-07-28` ([SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577)), earliest removal `2027-07-28`. Logging keeps working until then; new integrations should log to stderr (stdio) or use OpenTelemetry instead.
The SDK provides support to send log messages to clients. All standard PSR-3 log levels are supported.
Level **warning** is the default level, so anything below it is dropped until the client raises the level with
`logging/setLevel`.
!!! note
Under the [2026-07-28 lifecycle](../run/protocol-eras.md#what-a-modern-request-carries) there is no
`logging/setLevel`: the client names its level in each request's
`_meta["io.modelcontextprotocol/logLevel"]`, and a request naming none receives no log
notifications at all.
!!! note
Only the message is forwarded to the client. A PSR-3 `$context` array is accepted for interface compatibility
but is **not** sent — interpolate anything you need into the message itself.
## Usage
The SDK automatically injects a `RequestContext` instance into handlers. This can be used to create a `ClientLogger`.
```php
use Mcp\Capability\Attribute\McpTool;
use Mcp\Server\RequestContext;
#[McpTool]
public function processData(string $input, RequestContext $context): array {
$logger = $context->getClientLogger();
$logger->info(\sprintf('Processing started for "%s"', $input));
$logger->warning('Deprecated API used');
// ... processing logic ...
$logger->info('Processing completed');
return ['result' => 'processed'];
}
```