* [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
265 lines
10 KiB
Markdown
265 lines
10 KiB
Markdown
# Server-Initiated Communication
|
|
|
|
The client can receive requests and notifications from the server when configured with appropriate handlers.
|
|
|
|
## Elicitation (User Input Requests)
|
|
|
|
Handle server requests to elicit additional information from the user during tool
|
|
execution. The server sends an `elicitation/create` request describing the fields it
|
|
needs; your callback presents them to the user and returns an `ElicitResult` with one of
|
|
three actions — accept (with the collected content), decline, or cancel:
|
|
|
|
```php
|
|
use Mcp\Client\Handler\Request\ElicitationRequestHandler;
|
|
use Mcp\Client\Handler\Request\ElicitationCallbackInterface;
|
|
use Mcp\Exception\ElicitationException;
|
|
use Mcp\Schema\ClientCapabilities;
|
|
use Mcp\Schema\Enum\ElicitAction;
|
|
use Mcp\Schema\Enum\ElicitationMode;
|
|
use Mcp\Schema\Request\ElicitRequest;
|
|
use Mcp\Schema\Result\ElicitResult;
|
|
|
|
class ConsoleElicitationCallback implements ElicitationCallbackInterface
|
|
{
|
|
public function __invoke(ElicitRequest $request): ElicitResult
|
|
{
|
|
echo $request->message.\PHP_EOL;
|
|
|
|
// In url mode there is no schema to fill in — the user completes the
|
|
// interaction in the browser instead.
|
|
if (ElicitationMode::Url === $request->mode) {
|
|
echo 'Continue in your browser: '.$request->url.\PHP_EOL;
|
|
|
|
return new ElicitResult(ElicitAction::Accept);
|
|
}
|
|
|
|
// Form mode: present $request->requestedSchema->properties and collect input.
|
|
$content = [];
|
|
foreach ($request->requestedSchema->properties as $name => $definition) {
|
|
$answer = readline($definition->title.': ');
|
|
|
|
if (false === $answer) {
|
|
// No input available — let the server know the user cancelled.
|
|
return new ElicitResult(ElicitAction::Cancel);
|
|
}
|
|
|
|
$content[$name] = $answer;
|
|
}
|
|
|
|
return new ElicitResult(ElicitAction::Accept, $content);
|
|
}
|
|
}
|
|
|
|
$client = Client::builder()
|
|
->setCapabilities(new ClientCapabilities(elicitation: true))
|
|
->addRequestHandler(new ElicitationRequestHandler(new ConsoleElicitationCallback))
|
|
->build();
|
|
```
|
|
|
|
Return `new ElicitResult(ElicitAction::Decline)` when the user refuses to provide the
|
|
information, and `new ElicitResult(ElicitAction::Cancel)` when they dismiss the request.
|
|
Only the `Accept` action carries content.
|
|
|
|
!!! warning
|
|
**Error Handling in Elicitation Callbacks:**
|
|
|
|
- **Throw `ElicitationException`** to forward a specific error message to the server
|
|
- **Any other exception** is logged but returns a generic error to the server
|
|
|
|
```php
|
|
// Good: Server receives "No interactive console available" message
|
|
throw new ElicitationException('No interactive console available');
|
|
|
|
// Bad: Server receives generic "Error while processing elicitation" message
|
|
throw new \RuntimeException('No interactive console available');
|
|
```
|
|
|
|
See [`examples/client/stdio_elicitation.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/client/stdio_elicitation.php) for a runnable example against the
|
|
elicitation demo server.
|
|
|
|
## Sampling (LLM Requests)
|
|
|
|
> **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.
|
|
|
|
Handle server requests for LLM completions:
|
|
|
|
```php
|
|
use Mcp\Client\Handler\Request\SamplingRequestHandler;
|
|
use Mcp\Client\Handler\Request\SamplingCallbackInterface;
|
|
use Mcp\Exception\SamplingException;
|
|
use Mcp\Schema\ClientCapabilities;
|
|
use Mcp\Schema\Request\CreateSamplingMessageRequest;
|
|
use Mcp\Schema\Result\CreateSamplingMessageResult;
|
|
use Mcp\Schema\Content\TextContent;
|
|
use Mcp\Schema\Enum\Role;
|
|
|
|
class LlmSamplingCallback implements SamplingCallbackInterface
|
|
{
|
|
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
|
|
{
|
|
try {
|
|
// Call your LLM provider
|
|
$response = $this->llmClient->complete(
|
|
messages: $request->messages,
|
|
maxTokens: $request->maxTokens,
|
|
temperature: $request->temperature ?? 0.7,
|
|
);
|
|
|
|
return new CreateSamplingMessageResult(
|
|
role: Role::Assistant,
|
|
content: new TextContent($response->text),
|
|
model: $response->model,
|
|
stopReason: $response->stopReason,
|
|
);
|
|
} catch (\Throwable $e) {
|
|
// Throw SamplingException to surface error to server
|
|
throw new SamplingException(
|
|
"LLM sampling failed: {$e->getMessage()}",
|
|
(int) $e->getCode(),
|
|
$e
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
$client = Client::builder()
|
|
->setCapabilities(new ClientCapabilities(sampling: true))
|
|
->addRequestHandler(new SamplingRequestHandler(new LlmSamplingCallback))
|
|
->build();
|
|
```
|
|
|
|
### Sampling with Tools
|
|
|
|
Clients that support tool-enabled sampling should advertise that capability and forward the request's `tools` and
|
|
`toolChoice` fields to their LLM provider. A provider response that requests tools can be returned as one or more
|
|
`ToolUseContent` blocks:
|
|
|
|
```php
|
|
use Mcp\Schema\ClientCapabilities;
|
|
use Mcp\Schema\Content\ToolUseContent;
|
|
use Mcp\Schema\Enum\Role;
|
|
use Mcp\Schema\Result\CreateSamplingMessageResult;
|
|
|
|
$client = Client::builder()
|
|
->setCapabilities(new ClientCapabilities(
|
|
sampling: true,
|
|
samplingContext: true,
|
|
samplingTools: true,
|
|
))
|
|
->addRequestHandler(new SamplingRequestHandler($samplingCallback))
|
|
->build();
|
|
|
|
// Inside the sampling callback, after invoking the LLM provider:
|
|
return new CreateSamplingMessageResult(
|
|
role: Role::Assistant,
|
|
content: array_map(
|
|
static fn ($call) => new ToolUseContent($call->id, $call->name, $call->input),
|
|
$providerResponse->toolCalls,
|
|
),
|
|
model: $providerResponse->model,
|
|
stopReason: 'toolUse',
|
|
);
|
|
```
|
|
|
|
The server executes the requested tools and sends their results in a later sampling request as `ToolResultContent`
|
|
blocks in a user message. The client should pass those blocks back to the LLM provider to continue the sampling loop.
|
|
|
|
!!! warning
|
|
**Error Handling in Sampling Callbacks:**
|
|
|
|
When implementing sampling callbacks, error handling is critical:
|
|
|
|
- **Throw `SamplingException`** to forward specific error messages to the server
|
|
- **Any other exception** will be logged but return a generic error to the server
|
|
|
|
This distinction allows you to control what error information the server receives:
|
|
|
|
```php
|
|
// Good: Server receives "Rate limit exceeded" message
|
|
throw new SamplingException('Rate limit exceeded. Retry after 60 seconds.');
|
|
|
|
// Bad: Server receives generic "Error while sampling LLM" message
|
|
throw new \RuntimeException('Rate limit exceeded');
|
|
```
|
|
|
|
## Logging Notifications
|
|
|
|
> **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.
|
|
|
|
Receive structured log messages from the server:
|
|
|
|
```php
|
|
use Mcp\Client\Handler\Notification\LoggingNotificationHandler;
|
|
use Mcp\Schema\Notification\LoggingMessageNotification;
|
|
use Mcp\Schema\Enum\LoggingLevel;
|
|
|
|
$loggingHandler = new LoggingNotificationHandler(
|
|
static function (LoggingMessageNotification $notification) {
|
|
// Route to your application's logging system
|
|
$level = $notification->level;
|
|
$message = $notification->data;
|
|
|
|
match ($level) {
|
|
LoggingLevel::Debug => logger()->debug($message),
|
|
LoggingLevel::Info => logger()->info($message),
|
|
LoggingLevel::Warning => logger()->warning($message),
|
|
LoggingLevel::Error => logger()->error($message),
|
|
default => logger()->info($message),
|
|
};
|
|
}
|
|
);
|
|
|
|
$client = Client::builder()
|
|
->addNotificationHandler($loggingHandler)
|
|
->build();
|
|
|
|
// Set minimum log level (optional)
|
|
$client->setLoggingLevel(LoggingLevel::Info);
|
|
```
|
|
|
|
## Roots
|
|
|
|
> **Deprecated** since protocol revision `2026-07-28` ([SEP-2577](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/2577)), earliest removal `2027-07-28`. Roots keep working until then; new integrations should pass directories or files through tool arguments, resource URIs or server configuration instead.
|
|
|
|
Roots let the client expose a list of `file://` "workspace folders" that the server
|
|
is allowed to operate on. Advertise the `roots` capability and register a handler
|
|
that answers server `roots/list` requests:
|
|
|
|
```php
|
|
use Mcp\Client\Handler\Request\ListRootsRequestHandler;
|
|
use Mcp\Client\Handler\Request\RootsCallbackInterface;
|
|
use Mcp\Schema\ClientCapabilities;
|
|
use Mcp\Schema\Request\ListRootsRequest;
|
|
use Mcp\Schema\Result\ListRootsResult;
|
|
use Mcp\Schema\Root;
|
|
|
|
class WorkspaceRootsCallback implements RootsCallbackInterface
|
|
{
|
|
public function __invoke(ListRootsRequest $request): ListRootsResult
|
|
{
|
|
return new ListRootsResult([
|
|
new Root('file:///home/user/projects/app', 'Application'),
|
|
new Root('file:///home/user/projects/library', 'Library'),
|
|
]);
|
|
}
|
|
}
|
|
|
|
$client = Client::builder()
|
|
->setCapabilities(new ClientCapabilities(roots: true, rootsListChanged: true))
|
|
->addRequestHandler(new ListRootsRequestHandler(new WorkspaceRootsCallback))
|
|
->build();
|
|
```
|
|
|
|
When the client's roots change, notify the server so it can request the updated
|
|
list via `roots/list`. This requires advertising the `roots.listChanged`
|
|
capability (`rootsListChanged: true` above); otherwise `sendRootsListChanged()`
|
|
throws a `RuntimeException`. On a client that is not connected it throws a
|
|
`ConnectionException`:
|
|
|
|
```php
|
|
$client->sendRootsListChanged();
|
|
```
|
|
|
|
See [`examples/client/stdio_roots.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/client/stdio_roots.php) for a runnable example: it calls the
|
|
`inspect_workspace_roots` tool of the client-communication demo server, which
|
|
answers by issuing the `roots/list` request back to the client.
|