[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
46 changed files with 4245 additions and 4069 deletions

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 180 180"><path fill="none" d="M23.5996 85.2532L86.2021 22.6507C94.8457 14.0071 108.86 14.0071 117.503 22.6507C126.147 31.2942 126.147 45.3083 117.503 53.9519L70.2254 101.23" stroke="currentColor" stroke-width="11.0667" stroke-linecap="round"/><path fill="none" d="M70.8789 100.578L117.504 53.952C126.148 45.3083 140.163 45.3083 148.806 53.952L149.132 54.278C157.776 62.9216 157.776 76.9357 149.132 85.5792L92.5139 142.198C89.6327 145.079 89.6327 149.75 92.5139 152.631L104.14 164.257" stroke="currentColor" stroke-width="11.0667" stroke-linecap="round"/><path fill="none" d="M101.853 38.3013L55.553 84.6011C46.9094 93.2447 46.9094 107.258 55.553 115.902C64.1966 124.546 78.2106 124.546 86.8543 115.902L133.154 69.6025" stroke="currentColor" stroke-width="11.0667" stroke-linecap="round"/></svg>

After

Width:  |  Height:  |  Size: 848 B

1
docs/CNAME Normal file
View file

@ -0,0 +1 @@
php.sdk.modelcontextprotocol.io

View file

@ -0,0 +1,98 @@
# Custom Message Handlers
**Low-level escape hatch.** Custom message handlers run before the SDK's built-in handlers and give you total control over
individual JSON-RPC messages. They do not receive the builder's registry, container, or discovery output unless you pass
those dependencies in yourself.
> **Warning**: Custom message handlers bypass discovery, manual capability registration, and container lookups (unless
> you explicitly pass them). Tools, resources, and prompts you register elsewhere will not show up unless your handler
> loads and executes them manually. Reach for this API only when you need that level of control and are comfortable
> taking on the additional plumbing.
## Request Handlers
Handle JSON-RPC requests (messages with an `id` that expect a response). Request handlers **must** return either a
`Response` or an `Error` object.
Attach request handlers with `addRequestHandler()` (single) or `addRequestHandlers()` (multiple). You can call these
methods as many times as needed; handlers are collected in call order, and the whole custom list runs before the
built-in defaults:
```php
$server = Server::builder()
->addRequestHandler(new CustomListToolsHandler())
->addRequestHandlers([
new CustomCallToolHandler(),
new CustomGetPromptHandler(),
])
->build();
```
Request handlers implement `RequestHandlerInterface`:
```php
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Server\Handler\Request\RequestHandlerInterface;
use Mcp\Server\Session\SessionInterface;
interface RequestHandlerInterface
{
public function supports(Request $request): bool;
public function handle(Request $request, SessionInterface $session): Response|Error;
}
```
- `supports()` decides if the handler should process the incoming request
- `handle()` **must** return a `Response` (on success) or an `Error` (on failure)
## Notification Handlers
Handle JSON-RPC notifications (messages without an `id` that don't expect a response). Notification handlers **do not**
return anything - they perform side effects only.
Attach notification handlers with `addNotificationHandler()` (single) or `addNotificationHandlers()` (multiple):
```php
// Handlers are your own classes implementing NotificationHandlerInterface;
// the SDK ships only its internal ones.
$server = Server::builder()
->addNotificationHandler(new AuditNotificationHandler($auditLog))
->addNotificationHandlers([
new MetricsNotificationHandler($metrics),
new CancellationNotificationHandler(),
])
->build();
```
Notification handlers implement `NotificationHandlerInterface`:
```php
use Mcp\Schema\JsonRpc\Notification;
use Mcp\Server\Handler\Notification\NotificationHandlerInterface;
use Mcp\Server\Session\SessionInterface;
interface NotificationHandlerInterface
{
public function supports(Notification $notification): bool;
public function handle(Notification $notification, SessionInterface $session): void;
}
```
- `supports()` decides if the handler should process the incoming notification
- `handle()` performs side effects but **does not** return a value (notifications have no response)
## Key Differences
| Handler Type | Interface | Returns | Use Case |
|-------------|-----------|---------|----------|
| Request Handler | `RequestHandlerInterface` | `Response\|Error` | Handle requests that need responses (e.g., `tools/list`, `tools/call`) |
| Notification Handler | `NotificationHandlerInterface` | `void` | Handle fire-and-forget notifications (e.g., `notifications/initialized`, `notifications/progress`) |
## Example
Check out [`examples/server/custom-method-handlers/server.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/server/custom-method-handlers/server.php) for a complete example showing how to implement
custom `tools/list` and `tools/call` request handlers independently of the registry.

94
docs/advanced/events.md Normal file
View file

@ -0,0 +1,94 @@
# Events
The MCP SDK provides a PSR-14 compatible event system that allows you to hook into the server's lifecycle. Events enable request/response modification, and other user-defined behaviors.
## Setup
Configure an event dispatcher when building your server:
```php
use Mcp\Event\RequestEvent;
use Mcp\Server;
use Symfony\Component\EventDispatcher\EventDispatcher;
$dispatcher = new EventDispatcher();
// Register your listeners
$dispatcher->addListener(RequestEvent::class, function (RequestEvent $event) {
// Handle any incoming request
if ($event->getMethod() === 'tools/call') {
// Handle tool call requests specifically
}
});
$server = Server::builder()
->setEventDispatcher($dispatcher)
->build();
```
## Protocol Events
The SDK dispatches 4 broad event types at the protocol level, allowing you to observe and modify all server operations:
### RequestEvent
**Dispatched**: When any request is received from the client, before it's processed by handlers.
**Properties**:
- `getRequest(): Request` - The incoming request
- `setRequest(Request $request): void` - Modify the request before processing
- `getSession(): SessionInterface` - The current session
- `getMethod(): string` - Convenience method to get the request method
### ResponseEvent
**Dispatched**: When a successful response is ready to be sent to the client, after handler execution.
**Properties**:
- `getResponse(): Response` - The response being sent
- `setResponse(Response $response): void` - Modify the response before sending
- `getRequest(): Request` - The original request
- `getSession(): SessionInterface` - The current session
- `getMethod(): string` - Convenience method to get the request method
### ErrorEvent
**Dispatched**: When an error occurs during request processing.
**Properties**:
- `getError(): Error` - The error being sent
- `setError(Error $error): void` - Modify the error before sending
- `getRequest(): Request` - The original request. Messages that fail to parse are rejected before this event, so a listener never sees them.
- `getThrowable(): ?\Throwable` - The exception that caused the error (if any)
- `getSession(): SessionInterface` - The current session
### NotificationEvent
**Dispatched**: When a notification is received from the client, before it's processed by handlers.
**Properties**:
- `getNotification(): Notification` - The incoming notification
- `setNotification(Notification $notification): void` - Modify the notification before processing
- `getSession(): SessionInterface` - The current session
- `getMethod(): string` - Convenience method to get the notification method
## List Change Events
These events are dispatched when the lists of available capabilities change:
| Event | Description |
|------------------------------------|------------------------------------------------------------------|
| `ToolListChangedEvent` | Dispatched when the list of available tools changes |
| `ResourceListChangedEvent` | Dispatched when the list of available resources changes |
| `ResourceTemplateListChangedEvent` | Dispatched when the list of available resource templates changes |
| `PromptListChangedEvent` | Dispatched when the list of available prompts changes |
These events carry no data and are used to notify clients that they should refresh their capability lists.
```php
use Mcp\Event\ToolListChangedEvent;
$dispatcher->addListener(ToolListChangedEvent::class, function (ToolListChangedEvent $event) {
$logger->info('Tool list has changed, clients should refresh');
});
```

160
docs/advanced/extensions.md Normal file
View file

@ -0,0 +1,160 @@
# Protocol Extensions
MCP protocol extensions advertise additional, optional capabilities alongside the regular ones —
during the `initialize` handshake, or on revision `2026-07-28` (which has no handshake) inside the
capabilities that travel with every request. A server opts in via `Builder::enableExtension()` and
the SDK places the advertisement correctly for whichever era the client speaks:
```php
use Mcp\Schema\Extension\Apps\McpApps;
use Mcp\Server;
$server = Server::builder()
->setServerInfo('My Server', '1.0.0')
->enableExtension(new McpApps())
->build();
```
Pass one or more `ExtensionInterface` instances; multiple extensions can
be enabled in a single call. Enabling the same extension twice throws a
`LogicException`.
Clients (hosts) advertise the extensions they support the same way, via
`Client\Builder::enableExtension()`; the payload lands under
`capabilities.extensions` in the initialize request — or, on a modern revision,
under the client capabilities carried in each request's `_meta` envelope.
> Note: extensions enabled via `enableExtension()` are merged into the
> `extensions` capability even when you supply your own `ServerCapabilities` /
> `ClientCapabilities` via `setCapabilities()`. An enabled extension overrides
> any entry under the same id already present in those capabilities.
## Checking what the client negotiated
An extension is only in effect when both sides advertise it. On the server, a
handler can ask the `ClientGateway` from the injected `RequestContext` whether the
connected client did:
```php
use Mcp\Schema\Extension\Apps\McpApps;
use Mcp\Server\RequestContext;
public function getWeather(string $city, RequestContext $context): string
{
if (!$context->getClientGateway()->supportsExtension(McpApps::EXTENSION_ID)) {
// text-only fallback for hosts without MCP Apps support
}
// ...
}
```
## MCP Apps (`io.modelcontextprotocol/ui`)
The [MCP Apps extension][ext-apps] lets servers expose interactive HTML UIs as
resources. Clients that support it render them in sandboxed iframes and bridge
tool calls between the iframe (the *View*) and the server via the host.
A UI consists of two pieces wired together by `_meta.ui`:
1. **A resource** with URI scheme `ui://` and MIME type
`text/html;profile=mcp-app`, returning the HTML body.
2. **A tool** linked to that resource via `UiToolMeta`, so the client knows to
open the UI when the tool is invoked.
```php
use Mcp\Schema\Content\TextResourceContents;
use Mcp\Schema\Extension\Apps\McpApps;
use Mcp\Schema\Extension\Apps\ToolVisibility;
use Mcp\Schema\Extension\Apps\UiResourceContentMeta;
use Mcp\Schema\Extension\Apps\UiResourceCsp;
use Mcp\Schema\Extension\Apps\UiResourcePermissions;
use Mcp\Schema\Extension\Apps\UiToolMeta;
$server = Server::builder()
->enableExtension(new McpApps())
->addResource(
fn () => new TextResourceContents(
uri: 'ui://my-app',
mimeType: McpApps::MIME_TYPE,
text: file_get_contents(__DIR__.'/app.html'),
meta: ['ui' => new UiResourceContentMeta(
csp: new UiResourceCsp(connectDomains: ['https://api.example.com']),
permissions: new UiResourcePermissions(geolocation: true),
prefersBorder: true,
)],
),
'ui://my-app',
mimeType: McpApps::MIME_TYPE,
meta: ['ui' => McpApps::resourceMarker()],
)
->addTool(
$myToolHandler,
'my_tool',
meta: ['ui' => new UiToolMeta(
resourceUri: 'ui://my-app',
visibility: [ToolVisibility::Model, ToolVisibility::App],
)],
)
->build();
```
Note the two distinct `_meta.ui` shapes: the resource *descriptor* (its
`resources/list` entry) carries only an empty marker — `McpApps::resourceMarker()` —
flagging it as an MCP App, while the resource *content* returned by `resources/read`
carries the structured `UiResourceContentMeta` with the actual CSP and permission
configuration.
### Attribute-based discovery
The same linkage works with `#[McpResource]` / `#[McpTool]`, since both accept a
`meta` array and PHP allows `new` in attribute arguments. The one difference is the
descriptor marker: `McpApps::resourceMarker()` is a method call and cannot appear
in an attribute, so spell it as `new \stdClass()` there.
```php
use Mcp\Capability\Attribute\McpResource;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Schema\Extension\Apps\McpApps;
use Mcp\Schema\Extension\Apps\ToolVisibility;
use Mcp\Schema\Extension\Apps\UiToolMeta;
final class WeatherApp
{
#[McpResource(uri: 'ui://my-app', mimeType: McpApps::MIME_TYPE, meta: ['ui' => new \stdClass()])]
public function view(): TextResourceContents { /* as above */ }
#[McpTool(name: 'my_tool', meta: ['ui' => new UiToolMeta(resourceUri: 'ui://my-app', visibility: [ToolVisibility::Model, ToolVisibility::App])])]
public function myTool(string $city): string { /* ... */ }
}
```
### Server-side DTOs
| Class | Purpose |
| --- | --- |
| `McpApps` | Extension marker; provides `EXTENSION_ID`, `MIME_TYPE`, `URI_SCHEME` constants. |
| `UiToolMeta` | Tool `_meta.ui` payload: `resourceUri` + `visibility`. |
| `ToolVisibility` | Enum: `Model`, `App`. |
| `UiResourceContentMeta` | Resource content `_meta.ui`: `csp`, `permissions`, `domain`, `prefersBorder`. |
| `UiResourceCsp` | CSP allow-lists: `connectDomains`, `resourceDomains`, `frameDomains`, `baseUriDomains`. |
| `UiResourcePermissions` | Sandbox permissions: `camera`, `microphone`, `geolocation`, `clipboardWrite`. |
### Writing the HTML view
The View and host exchange `JSONRPCMessage` **objects** (not JSON strings) via
`window.parent.postMessage`. Before the host forwards `tools/call`,
`tool-input`, or `tool-result`, the View must complete the spec-mandated
handshake:
1. View → Host: `ui/initialize` request
2. Host → View: response with `hostCapabilities`, `hostInfo`, `hostContext`
3. View → Host: `ui/notifications/initialized`
4. View → Host: `ui/notifications/size-changed` whenever the iframe wants to
resize
See the [`ext-apps` repository][ext-apps] for the full protocol, official
TypeScript SDK (`@modelcontextprotocol/ext-apps`), and view-side examples. A
working minimal view is included in
[`examples/server/mcp-apps/weather-app.html`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/server/mcp-apps/weather-app.html).
[ext-apps]: https://github.com/modelcontextprotocol/ext-apps

10
docs/advanced/index.md Normal file
View file

@ -0,0 +1,10 @@
# Advanced
Everything here is optional. A working server needs none of it.
* **[Events](events.md)** — PSR-14 events dispatched around every request, response,
error, and notification. Useful for metrics, audit logs, and debugging.
* **[Protocol extensions](extensions.md)** — opt-in extensions announced during
capability negotiation, including MCP Apps (HTML UI resources).
* **[Custom message handlers](custom-handlers.md)** — taking over a JSON-RPC method the
SDK does not implement, or overriding one it does.

View file

@ -1,879 +0,0 @@
# Client
The MCP Client SDK provides a synchronous, framework-agnostic API for communicating with MCP servers from PHP applications.
It handles connection management, request/response correlation, server-initiated requests (sampling), and real-time notifications.
## Table of Contents
- [Overview](#overview)
- [Client Builder](#client-builder)
- [Transports](#transports)
- [Connecting to Servers](#connecting-to-servers)
- [Server Information](#server-information)
- [Working with Tools](#working-with-tools)
- [Working with Resources](#working-with-resources)
- [Working with Prompts](#working-with-prompts)
- [Server-Initiated Communication](#server-initiated-communication)
- [Error Handling](#error-handling)
- [Complete Example](#complete-example)
## Overview
The client follows a builder pattern for configuration and provides a synchronous API for all operations:
```php
use Mcp\Client;
use Mcp\Client\Transport\StdioTransport;
// Build and configure the client
$client = Client::builder()
->setClientInfo('My Client', '1.0.0')
->setInitTimeout(30)
->setRequestTimeout(120)
->build();
// Create a transport
$transport = new StdioTransport(
command: 'php',
args: ['/path/to/server.php'],
);
// Connect and use the server
$client->connect($transport);
$tools = $client->listTools();
$client->disconnect();
```
## Client Builder
The `Client\Builder` provides fluent configuration of client instances.
### Basic Configuration
```php
use Mcp\Client;
$client = Client::builder()
->setClientInfo('My Application', '1.0.0', 'Description of my client')
->setInitTimeout(30) // Seconds to wait for initialization
->setRequestTimeout(120) // Seconds to wait for request responses
->setMaxRetries(3) // Retries for failed connections
->build();
```
### Connection Retries
`setMaxRetries()` controls how often `connect()` retries a failed connection. It
counts retries rather than attempts, so the default of `3` means one initial
attempt plus up to three retries — four in total — before the `ConnectionException`
of the last attempt is rethrown:
```php
$client = Client::builder()
->setMaxRetries(0) // Fail on the first failed attempt
->build();
```
Between two attempts the transport is closed, so a retry never reuses a
half-established connection: a `StdioTransport` spawns a fresh server process and
an `HttpTransport` discards the session ID of the failed attempt. Each retry is
preceded by a short, linearly growing delay (100ms, 200ms, 300ms, …).
Only the connection handshake is retried. Individual requests such as
`callTool()` are always sent once — retrying them is unsafe as tool calls are not
necessarily idempotent.
### Client Information
Set the client's identity reported to servers during initialization:
```php
$client = Client::builder()
->setClientInfo(
name: 'AI Assistant Client',
version: '2.1.0',
description: 'Client for automated AI workflows'
)
->build();
```
### Protocol Version
Specify the MCP protocol version to offer during the handshake (defaults to the latest):
```php
use Mcp\Schema\Enum\ProtocolVersion;
$client = Client::builder()
->setProtocolVersion(ProtocolVersion::V2025_11_25)
->build();
```
This is an offer, not a demand. A server that does not support the requested revision counter-offers one it does, as
described in the specification's
[protocol version negotiation](https://modelcontextprotocol.io/specification/draft/basic/versioning#protocol-version-negotiation)
section. The client accepts any counter-offer it knows about and continues on that revision; a counter-offer the SDK
cannot speak fails the handshake with a `ConnectionException` rather than continuing on a revision neither side agreed
on. Use `$client->getProtocolVersion()` after connecting to read what was actually negotiated.
Modern revisions such as `2026-07-28` replaced `initialize` with per-request metadata, so they cannot be offered here.
Configuring one still opens the handshake with `ProtocolVersion::latestHandshake()`, and the client logs a warning
saying so.
See [Protocol Version Negotiation](server-builder.md#protocol-version-negotiation) for the server side of the exchange.
### Capabilities
Declare client capabilities to enable server features:
```php
use Mcp\Schema\ClientCapabilities;
$client = Client::builder()
->setCapabilities(new ClientCapabilities(
sampling: true, // Enable LLM sampling requests from server
roots: true, // Enable filesystem root listing
))
->build();
```
### Notification Handlers
Register handlers for server-initiated notifications:
```php
use Mcp\Client\Handler\Notification\LoggingNotificationHandler;
use Mcp\Schema\Notification\LoggingMessageNotification;
$loggingHandler = new LoggingNotificationHandler(
static function (LoggingMessageNotification $notification) {
echo "[{$notification->level->value}] {$notification->data}\n";
}
);
$client = Client::builder()
->addNotificationHandler($loggingHandler)
->build();
```
### Request Handlers
Register handlers for server-initiated requests (e.g., sampling):
```php
use Mcp\Client\Handler\Request\SamplingRequestHandler;
use Mcp\Client\Handler\Request\SamplingCallbackInterface;
use Mcp\Schema\Request\CreateSamplingMessageRequest;
use Mcp\Schema\Result\CreateSamplingMessageResult;
$samplingCallback = new class implements SamplingCallbackInterface {
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
{
// Perform LLM sampling and return result
}
};
$client = Client::builder()
->addRequestHandler(new SamplingRequestHandler($samplingCallback))
->build();
```
### Logger
Configure PSR-3 logging for debugging:
```php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('mcp-client');
$logger->pushHandler(new StreamHandler('client.log', Logger::DEBUG));
$client = Client::builder()
->setLogger($logger)
->build();
```
## Transports
Transports handle the communication layer between client and server.
### STDIO Transport
Spawns a server process and communicates via standard input/output:
```php
use Mcp\Client\Transport\StdioTransport;
$transport = new StdioTransport(
command: 'php',
args: ['/path/to/server.php'],
cwd: '/working/directory', // Optional working directory
env: ['KEY' => 'value'], // Optional environment variables
);
```
**Parameters:**
- `command` (string): The command to execute
- `args` (array): Command arguments
- `cwd` (string|null): Working directory for the process
- `env` (array|null): Environment variables
- `logger` (LoggerInterface|null): Optional PSR-3 logger
### HTTP Transport
Communicates with remote MCP servers over HTTP:
```php
use Mcp\Client\Transport\HttpTransport;
$transport = new HttpTransport(
endpoint: 'http://localhost:8000',
headers: ['Authorization' => 'Bearer token'],
);
```
**Parameters:**
- `endpoint` (string): The MCP server URL
- `headers` (array): Additional HTTP headers
- `httpClient` (ClientInterface|null): PSR-18 HTTP client (auto-discovered)
- `requestFactory` (RequestFactoryInterface|null): PSR-17 request factory (auto-discovered)
- `streamFactory` (StreamFactoryInterface|null): PSR-17 stream factory (auto-discovered)
- `logger` (LoggerInterface|null): Optional PSR-3 logger
**PSR-18 Auto-Discovery:**
The transport automatically discovers PSR-18 HTTP clients from:
- `php-http/guzzle7-adapter`
- `php-http/curl-client`
- `symfony/http-client`
- And other PSR-18 compatible implementations
```bash
# Install any PSR-18 client - discovery works automatically
composer require php-http/guzzle7-adapter
```
## Connecting to Servers
### Establishing Connection
```php
$client->connect($transport);
```
The `connect()` method performs the MCP initialization handshake:
1. Opens the transport connection
2. Sends InitializeRequest with client capabilities
3. Waits for InitializeResult from server
4. Sends InitializedNotification
> [!IMPORTANT]
> Always wrap connection in try/catch to handle `ConnectionException` for failed connections.
### Checking Connection State
```php
if ($client->isConnected()) {
// Client is connected and initialized
}
```
### Disconnecting
```php
$client->disconnect();
```
Always disconnect when finished to clean up resources:
```php
try {
$client->connect($transport);
// ... use the client ...
} finally {
$client->disconnect();
}
```
## Server Information
After successful connection, retrieve server metadata:
```php
// Get server implementation info
$serverInfo = $client->getServerInfo();
echo "Server: {$serverInfo->name} v{$serverInfo->version}\n";
// Get server instructions
$instructions = $client->getInstructions();
if ($instructions) {
echo "Instructions: {$instructions}\n";
}
```
## Working with Tools
### Listing Tools
```php
$toolsResult = $client->listTools();
foreach ($toolsResult->tools as $tool) {
echo "- {$tool->name}: {$tool->description}\n";
}
// Handle pagination
if ($toolsResult->nextCursor) {
$moreTools = $client->listTools($toolsResult->nextCursor);
}
```
### Calling Tools
```php
$result = $client->callTool(
name: 'calculate',
arguments: ['a' => 5, 'b' => 3, 'operation' => 'add'],
);
// Access results
foreach ($result->content as $content) {
if ($content instanceof TextContent) {
echo $content->text;
}
}
```
### Progress Notifications
Hook into tool execution progress (if server supports it):
```php
$result = $client->callTool(
name: 'long_running_task',
arguments: ['data' => 'large_dataset'],
onProgress: static function (float $progress, ?float $total, ?string $message) {
$percent = $total > 0 ? round(($progress / $total) * 100) : 0;
echo "Progress: {$percent}% - {$message}\n";
}
);
```
> [!NOTE]
> Progress notifications are only received if the server sends them. The callback will not be invoked if the server doesn't support or send progress updates.
## Working with Resources
### Listing Resources
```php
$resourcesResult = $client->listResources();
foreach ($resourcesResult->resources as $resource) {
echo "- {$resource->uri}: {$resource->name}\n";
}
```
### Listing Resource Templates
```php
$templatesResult = $client->listResourceTemplates();
foreach ($templatesResult->resourceTemplates as $template) {
echo "- {$template->uriTemplate}: {$template->name}\n";
}
```
### Reading Resources
```php
$resourceResult = $client->readResource('config://app/settings');
foreach ($resourceResult->contents as $content) {
if ($content instanceof TextResourceContents) {
echo "Text: {$content->text}\n";
} elseif ($content instanceof BlobResourceContents) {
echo "Binary data (base64): {$content->blob}\n";
}
}
```
Resources also support progress notifications:
```php
$result = $client->readResource(
uri: 'file://large-file.bin',
onProgress: static function (float $progress, ?float $total, ?string $message) {
echo "Reading: {$progress}/{$total} bytes\n";
}
);
```
## Working with Prompts
### Listing Prompts
```php
$promptsResult = $client->listPrompts();
foreach ($promptsResult->prompts as $prompt) {
echo "- {$prompt->name}: {$prompt->description}\n";
}
```
### Getting Prompts
```php
$promptResult = $client->getPrompt(
name: 'code_review',
arguments: ['language' => 'php', 'code' => '...'],
);
foreach ($promptResult->messages as $message) {
echo "{$message->role->value}: {$message->content->text}\n";
}
```
Prompts also support progress notifications:
```php
$result = $client->getPrompt(
name: 'generate_report',
arguments: ['topic' => 'quarterly_analysis'],
onProgress: static function (float $progress, ?float $total, ?string $message) {
echo "Generating: {$message}\n";
}
);
```
### Requesting Completions
Request auto-completion suggestions for prompt or resource arguments:
```php
use Mcp\Schema\PromptReference;
$completionResult = $client->complete(
ref: new PromptReference('code_review'),
argument: ['name' => 'language', 'value' => 'ph'],
);
foreach ($completionResult->values as $value) {
echo "Suggestion: {$value}\n";
}
```
## Server-Initiated Communication
The client can receive requests and notifications from the server when configured with appropriate handlers.
### 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);
```
### 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.
> [!IMPORTANT]
> **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');
> ```
### 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\Request\ElicitRequest;
use Mcp\Schema\Result\ElicitResult;
class ConsoleElicitationCallback implements ElicitationCallbackInterface
{
public function __invoke(ElicitRequest $request): ElicitResult
{
echo $request->message.\PHP_EOL;
// Present $request->requestedSchema->properties to the user 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.
> [!IMPORTANT]
> **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` for a runnable example against the
elicitation demo server.
### 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` 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.
## Error Handling
The client throws exceptions for various error conditions:
### ConnectionException
Thrown when connection or initialization fails:
```php
use Mcp\Exception\ConnectionException;
try {
$client->connect($transport);
} catch (ConnectionException $e) {
echo "Failed to connect: {$e->getMessage()}\n";
}
```
### RequestException
Thrown when a request returns an error response:
```php
use Mcp\Exception\RequestException;
try {
$result = $client->callTool('unknown_tool', []);
} catch (RequestException $e) {
echo "Request failed: {$e->getMessage()}\n";
echo "Error code: {$e->getCode()}\n";
}
```
## Complete Example
Here's a comprehensive example demonstrating client usage:
```php
<?php
use Mcp\Client;
use Mcp\Client\Handler\Notification\LoggingNotificationHandler;
use Mcp\Client\Handler\Request\SamplingCallbackInterface;
use Mcp\Client\Handler\Request\SamplingRequestHandler;
use Mcp\Client\Transport\StdioTransport;
use Mcp\Exception\SamplingException;
use Mcp\Schema\ClientCapabilities;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\Enum\LoggingLevel;
use Mcp\Schema\Enum\Role;
use Mcp\Schema\Notification\LoggingMessageNotification;
use Mcp\Schema\Request\CreateSamplingMessageRequest;
use Mcp\Schema\Result\CreateSamplingMessageResult;
// Configure logging notification handler
$loggingHandler = new LoggingNotificationHandler(
static function (LoggingMessageNotification $notification) {
echo "[LOG {$notification->level->value}] {$notification->data}\n";
}
);
// Configure sampling callback
$samplingCallback = new class implements SamplingCallbackInterface {
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
{
echo "[SAMPLING] Processing request (max {$request->maxTokens} tokens)\n";
try {
// Integration with your LLM provider
$response = "This is a mock LLM response for: " .
json_encode($request->messages);
return new CreateSamplingMessageResult(
role: Role::Assistant,
content: new TextContent($response),
model: 'mock-llm',
stopReason: 'endTurn',
);
} catch (\Throwable $e) {
throw new SamplingException(
"Sampling failed: {$e->getMessage()}",
0,
$e
);
}
}
};
// Build client
$client = Client::builder()
->setClientInfo('Example Client', '1.0.0')
->setInitTimeout(30)
->setRequestTimeout(120)
->setCapabilities(new ClientCapabilities(sampling: true))
->addNotificationHandler($loggingHandler)
->addRequestHandler(new SamplingRequestHandler($samplingCallback))
->build();
// Create transport
$transport = new StdioTransport(
command: 'php',
args: [__DIR__ . '/server.php'],
);
// Connect and use server
try {
echo "Connecting to server...\n";
$client->connect($transport);
// Get server info
$serverInfo = $client->getServerInfo();
echo "Connected to: {$serverInfo->name} v{$serverInfo->version}\n\n";
// List capabilities
echo "Available tools:\n";
$tools = $client->listTools();
foreach ($tools->tools as $tool) {
echo " - {$tool->name}\n";
}
echo "\nAvailable resources:\n";
$resources = $client->listResources();
foreach ($resources->resources as $resource) {
echo " - {$resource->uri}\n";
}
// Set logging level
$client->setLoggingLevel(LoggingLevel::Debug);
// Call tool with progress
echo "\nCalling tool with progress...\n";
$result = $client->callTool(
name: 'process_data',
arguments: ['dataset' => 'large_file.csv'],
onProgress: static function (float $progress, ?float $total, ?string $message) {
$percent = $total > 0 ? round(($progress / $total) * 100) : 0;
echo " Progress: {$percent}% - {$message}\n";
}
);
echo "\nResult:\n";
foreach ($result->content as $content) {
if ($content instanceof TextContent) {
echo $content->text . "\n";
}
}
} catch (\Throwable $e) {
echo "Error: {$e->getMessage()}\n";
echo $e->getTraceAsString() . "\n";
} finally {
$client->disconnect();
echo "\nDisconnected.\n";
}
```

161
docs/client/capabilities.md Normal file
View file

@ -0,0 +1,161 @@
# Tools, resources & prompts
Once connected, everything the server exposes is reachable through the client: list what
is there, then call it. Each list method returns the server's own descriptions and
schemas, so a generic client can build its UI from them.
## Working with Tools
### Listing Tools
```php
$toolsResult = $client->listTools();
foreach ($toolsResult->tools as $tool) {
echo "- {$tool->name}: {$tool->description}\n";
}
// Handle pagination
if ($toolsResult->nextCursor) {
$moreTools = $client->listTools($toolsResult->nextCursor);
}
```
### Calling Tools
```php
use Mcp\Schema\Content\TextContent;
$result = $client->callTool(
name: 'calculate',
arguments: ['a' => 5, 'b' => 3, 'operation' => 'add'],
);
// Access results
foreach ($result->content as $content) {
if ($content instanceof TextContent) {
echo $content->text;
}
}
```
### Progress Notifications
Hook into tool execution progress (if server supports it):
```php
$result = $client->callTool(
name: 'long_running_task',
arguments: ['data' => 'large_dataset'],
onProgress: static function (float $progress, ?float $total, ?string $message) {
$percent = $total > 0 ? round(($progress / $total) * 100) : 0;
echo "Progress: {$percent}% - {$message}\n";
}
);
```
!!! note
Progress notifications are only received if the server sends them. The callback will not be invoked if the server doesn't support or send progress updates.
## Working with Resources
### Listing Resources
```php
$resourcesResult = $client->listResources();
foreach ($resourcesResult->resources as $resource) {
echo "- {$resource->uri}: {$resource->name}\n";
}
```
### Listing Resource Templates
```php
$templatesResult = $client->listResourceTemplates();
foreach ($templatesResult->resourceTemplates as $template) {
echo "- {$template->uriTemplate}: {$template->name}\n";
}
```
### Reading Resources
```php
use Mcp\Schema\Content\{TextResourceContents, BlobResourceContents};
$resourceResult = $client->readResource('config://app/settings');
foreach ($resourceResult->contents as $content) {
if ($content instanceof TextResourceContents) {
echo "Text: {$content->text}\n";
} elseif ($content instanceof BlobResourceContents) {
echo "Binary data (base64): {$content->blob}\n";
}
}
```
Resources also support progress notifications:
```php
$result = $client->readResource(
uri: 'file://large-file.bin',
onProgress: static function (float $progress, ?float $total, ?string $message) {
echo "Reading: {$progress}/{$total} bytes\n";
}
);
```
## Working with Prompts
### Listing Prompts
```php
$promptsResult = $client->listPrompts();
foreach ($promptsResult->prompts as $prompt) {
echo "- {$prompt->name}: {$prompt->description}\n";
}
```
### Getting Prompts
```php
$promptResult = $client->getPrompt(
name: 'code_review',
arguments: ['language' => 'php', 'code' => '...'],
);
foreach ($promptResult->messages as $message) {
echo "{$message->role->value}: {$message->content->text}\n";
}
```
Prompts also support progress notifications:
```php
$result = $client->getPrompt(
name: 'generate_report',
arguments: ['topic' => 'quarterly_analysis'],
onProgress: static function (float $progress, ?float $total, ?string $message) {
echo "Generating: {$message}\n";
}
);
```
### Requesting Completions
Request auto-completion suggestions for prompt or resource arguments:
```php
use Mcp\Schema\PromptReference;
$completionResult = $client->complete(
ref: new PromptReference('code_review'),
argument: ['name' => 'language', 'value' => 'ph'],
);
foreach ($completionResult->values as $value) {
echo "Suggestion: {$value}\n";
}
```

222
docs/client/connecting.md Normal file
View file

@ -0,0 +1,222 @@
# Connecting to a server
A client is configured once through its builder, then connected to a
[transport](transports.md). Connecting performs the MCP initialization handshake, after
which the server's capabilities are known and its elements can be used. On protocol
revision `2026-07-28` there is no handshake to perform — see
[Clients on this revision](../protocol-versions.md).
## Client Builder
The `Client\Builder` provides fluent configuration of client instances.
### Basic Configuration
```php
use Mcp\Client;
$client = Client::builder()
->setClientInfo('My Application', '1.0.0', 'Description of my client')
->setInitTimeout(30) // Seconds to wait for initialization
->setRequestTimeout(120) // Seconds to wait for request responses
->setMaxRetries(3) // Retries for failed connections
->build();
```
### Connection Retries
`setMaxRetries()` controls how often `connect()` retries a failed connection. It
counts retries rather than attempts, so the default of `3` means one initial
attempt plus up to three retries — four in total — before the `ConnectionException`
of the last attempt is rethrown:
```php
$client = Client::builder()
->setMaxRetries(0) // Fail on the first failed attempt
->build();
```
Between two attempts the transport is closed, so a retry never reuses a
half-established connection: a `StdioTransport` spawns a fresh server process and
an `HttpTransport` discards the session ID of the failed attempt. Each retry is
preceded by a short, linearly growing delay (100ms, 200ms, 300ms, …).
Only the connection handshake is retried. Individual requests such as
`callTool()` are always sent once — retrying them is unsafe as tool calls are not
necessarily idempotent.
### Client Information
Set the client's identity reported to servers during initialization:
```php
$client = Client::builder()
->setClientInfo(
name: 'AI Assistant Client',
version: '2.1.0',
description: 'Client for automated AI workflows'
)
->build();
```
### Protocol Version
Specify the MCP protocol version to offer during the handshake (defaults to `V2025_11_25`, the
latest handshake revision — the modern `2026-07-28` revision must be chosen explicitly):
```php
use Mcp\Schema\Enum\ProtocolVersion;
$client = Client::builder()
->setProtocolVersion(ProtocolVersion::V2025_11_25)
->build();
```
This is an offer, not a demand. A server that does not support the requested revision counter-offers one it does, as
described in the specification's
[protocol version negotiation](https://modelcontextprotocol.io/specification/latest/basic/versioning#protocol-version-negotiation)
section. The client accepts any counter-offer it knows about and continues on that revision; a counter-offer the SDK
cannot speak fails the handshake with a `ConnectionException` rather than continuing on a revision neither side agreed
on. Use `$client->getProtocolVersion()` after connecting to read what was actually negotiated.
Setting a modern revision such as `2026-07-28` selects the other lifecycle rather than making an offer: there is no
`initialize` to negotiate with, so `connect()` sends none and every request carries its own revision instead. Nothing
else about the client API changes. See [Clients on this revision](../protocol-versions.md) for what happens underneath.
See [Protocol versions](../protocol-versions.md#negotiating-in-the-handshake-era) for the server side of the
exchange.
### Capabilities
Declare client capabilities to enable server features:
```php
use Mcp\Schema\ClientCapabilities;
$client = Client::builder()
->setCapabilities(new ClientCapabilities(
sampling: true, // Enable LLM sampling requests from server
roots: true, // Enable filesystem root listing
))
->build();
```
### Notification Handlers
Register handlers for server-initiated notifications:
```php
use Mcp\Client\Handler\Notification\LoggingNotificationHandler;
use Mcp\Schema\Notification\LoggingMessageNotification;
$loggingHandler = new LoggingNotificationHandler(
static function (LoggingMessageNotification $notification) {
echo "[{$notification->level->value}] {$notification->data}\n";
}
);
$client = Client::builder()
->addNotificationHandler($loggingHandler)
->build();
```
### Request Handlers
Register handlers for server-initiated requests (e.g., sampling). The same handlers answer a
[multi round-trip](../handlers/input-required.md) `input_required` result on a modern revision, where the server
returns its ask instead of sending a request:
```php
use Mcp\Client\Handler\Request\SamplingRequestHandler;
use Mcp\Client\Handler\Request\SamplingCallbackInterface;
use Mcp\Schema\Request\CreateSamplingMessageRequest;
use Mcp\Schema\Result\CreateSamplingMessageResult;
$samplingCallback = new class implements SamplingCallbackInterface {
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
{
// Perform LLM sampling and return result
}
};
$client = Client::builder()
->addRequestHandler(new SamplingRequestHandler($samplingCallback))
->build();
```
### Logger
Configure PSR-3 logging for debugging:
```php
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$logger = new Logger('mcp-client');
$logger->pushHandler(new StreamHandler('client.log', Logger::DEBUG));
$client = Client::builder()
->setLogger($logger)
->build();
```
## Connecting to Servers
### Establishing Connection
```php
$client->connect($transport);
```
The `connect()` method performs the MCP initialization handshake:
1. Opens the transport connection
2. Sends InitializeRequest with client capabilities
3. Waits for InitializeResult from server
4. Sends InitializedNotification
On a modern revision it opens the transport and asks `server/discover` for the server's identity instead; a server
that does not answer that optional method still yields a usable connection.
!!! warning
Always wrap connection in try/catch to handle `ConnectionException` for failed connections.
### Checking Connection State
```php
if ($client->isConnected()) {
// Client is connected and initialized
}
```
### Disconnecting
```php
$client->disconnect();
```
Always disconnect when finished to clean up resources:
```php
try {
$client->connect($transport);
// ... use the client ...
} finally {
$client->disconnect();
}
```
## Server Information
After successful connection, retrieve server metadata:
```php
// Get server implementation info
$serverInfo = $client->getServerInfo();
echo "Server: {$serverInfo->name} v{$serverInfo->version}\n";
// Get server instructions
$instructions = $client->getInstructions();
if ($instructions) {
echo "Instructions: {$instructions}\n";
}
```

155
docs/client/errors.md Normal file
View file

@ -0,0 +1,155 @@
# Error Handling
The client throws exceptions for various error conditions:
## ConnectionException
Thrown when connection or initialization fails:
```php
use Mcp\Exception\ConnectionException;
try {
$client->connect($transport);
} catch (ConnectionException $e) {
echo "Failed to connect: {$e->getMessage()}\n";
}
```
## RequestException
Thrown when a request returns an error response:
```php
use Mcp\Exception\RequestException;
try {
$result = $client->callTool('unknown_tool', []);
} catch (RequestException $e) {
echo "Request failed: {$e->getMessage()}\n";
echo "Error code: {$e->getCode()}\n";
}
```
## Complete Example
Here's a comprehensive example demonstrating client usage:
```php-file
<?php
use Mcp\Client;
use Mcp\Client\Handler\Notification\LoggingNotificationHandler;
use Mcp\Client\Handler\Request\SamplingCallbackInterface;
use Mcp\Client\Handler\Request\SamplingRequestHandler;
use Mcp\Client\Transport\StdioTransport;
use Mcp\Exception\SamplingException;
use Mcp\Schema\ClientCapabilities;
use Mcp\Schema\Content\TextContent;
use Mcp\Schema\Enum\LoggingLevel;
use Mcp\Schema\Enum\Role;
use Mcp\Schema\Notification\LoggingMessageNotification;
use Mcp\Schema\Request\CreateSamplingMessageRequest;
use Mcp\Schema\Result\CreateSamplingMessageResult;
// Configure logging notification handler
$loggingHandler = new LoggingNotificationHandler(
static function (LoggingMessageNotification $notification) {
echo "[LOG {$notification->level->value}] {$notification->data}\n";
}
);
// Configure sampling callback
$samplingCallback = new class implements SamplingCallbackInterface {
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
{
echo "[SAMPLING] Processing request (max {$request->maxTokens} tokens)\n";
try {
// Integration with your LLM provider
$response = "This is a mock LLM response for: " .
json_encode($request->messages);
return new CreateSamplingMessageResult(
role: Role::Assistant,
content: new TextContent($response),
model: 'mock-llm',
stopReason: 'endTurn',
);
} catch (\Throwable $e) {
throw new SamplingException(
"Sampling failed: {$e->getMessage()}",
0,
$e
);
}
}
};
// Build client
$client = Client::builder()
->setClientInfo('Example Client', '1.0.0')
->setInitTimeout(30)
->setRequestTimeout(120)
->setCapabilities(new ClientCapabilities(sampling: true))
->addNotificationHandler($loggingHandler)
->addRequestHandler(new SamplingRequestHandler($samplingCallback))
->build();
// Create transport
$transport = new StdioTransport(
command: 'php',
args: [__DIR__ . '/server.php'],
);
// Connect and use server
try {
echo "Connecting to server...\n";
$client->connect($transport);
// Get server info
$serverInfo = $client->getServerInfo();
echo "Connected to: {$serverInfo->name} v{$serverInfo->version}\n\n";
// List capabilities
echo "Available tools:\n";
$tools = $client->listTools();
foreach ($tools->tools as $tool) {
echo " - {$tool->name}\n";
}
echo "\nAvailable resources:\n";
$resources = $client->listResources();
foreach ($resources->resources as $resource) {
echo " - {$resource->uri}\n";
}
// Set logging level
$client->setLoggingLevel(LoggingLevel::Debug);
// Call tool with progress
echo "\nCalling tool with progress...\n";
$result = $client->callTool(
name: 'process_data',
arguments: ['dataset' => 'large_file.csv'],
onProgress: static function (float $progress, ?float $total, ?string $message) {
$percent = $total > 0 ? round(($progress / $total) * 100) : 0;
echo " Progress: {$percent}% - {$message}\n";
}
);
echo "\nResult:\n";
foreach ($result->content as $content) {
if ($content instanceof TextContent) {
echo $content->text . "\n";
}
}
} catch (\Throwable $e) {
echo "Error: {$e->getMessage()}\n";
echo $e->getTraceAsString() . "\n";
} finally {
$client->disconnect();
echo "\nDisconnected.\n";
}
```

41
docs/client/index.md Normal file
View file

@ -0,0 +1,41 @@
# Clients
The client side is for applications that *use* MCP servers: you connect to a server,
discover what it offers, and call it. The API is synchronous — every method returns a
result or throws.
```php
use Mcp\Client;
use Mcp\Client\Transport\StdioTransport;
// Build and configure the client
$client = Client::builder()
->setClientInfo('My Client', '1.0.0')
->setInitTimeout(30)
->setRequestTimeout(120)
->build();
// Create a transport
$transport = new StdioTransport(
command: 'php',
args: ['/path/to/server.php'],
);
// Connect and use the server
$client->connect($transport);
$tools = $client->listTools();
$client->disconnect();
```
* **[Connecting to a server](connecting.md)** — the builder, the connection lifecycle,
and what the server told you about itself during initialization.
* **[Transports](transports.md)** — launching a local server process (STDIO) or talking
to a remote one (HTTP).
* **[Tools, resources & prompts](capabilities.md)** — listing and calling everything a
server exposes, including progress callbacks and completions.
* **[Server-initiated requests](server-requests.md)** — the other direction: log
messages, sampling requests, and elicitations the server sends *you*.
* **[Error handling](errors.md)** — which exception means what, plus a complete
end-to-end example.
* **[Clients on this revision](../protocol-versions.md)** — the one builder line that speaks
protocol revision `2026-07-28`, and what it changes underneath.

View file

@ -0,0 +1,265 @@
# 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.

61
docs/client/transports.md Normal file
View file

@ -0,0 +1,61 @@
# Transports
Transports handle the communication layer between client and server.
## STDIO Transport
Spawns a server process and communicates via standard input/output:
```php
use Mcp\Client\Transport\StdioTransport;
$transport = new StdioTransport(
command: 'php',
args: ['/path/to/server.php'],
cwd: '/working/directory', // Optional working directory
env: ['KEY' => 'value'], // Optional environment variables
);
```
**Parameters:**
- `command` (string): The command to execute
- `args` (array): Command arguments
- `cwd` (string|null): Working directory for the process
- `env` (array|null): Environment variables
- `logger` (LoggerInterface|null): Optional PSR-3 logger
- `maxBufferSize` (int): Maximum buffered bytes per message before the transport gives up
## HTTP Transport
Communicates with remote MCP servers over HTTP:
```php
use Mcp\Client\Transport\HttpTransport;
$transport = new HttpTransport(
endpoint: 'http://localhost:8000',
headers: ['Authorization' => 'Bearer token'],
);
```
**Parameters:**
- `endpoint` (string): The MCP server URL
- `headers` (array): Additional HTTP headers
- `httpClient` (ClientInterface|null): PSR-18 HTTP client (auto-discovered)
- `requestFactory` (RequestFactoryInterface|null): PSR-17 request factory (auto-discovered)
- `streamFactory` (StreamFactoryInterface|null): PSR-17 stream factory (auto-discovered)
- `logger` (LoggerInterface|null): Optional PSR-3 logger
- `maxSseBufferBytes` (int): Maximum buffered bytes for a streamed SSE response
**PSR-18 Auto-Discovery:**
The transport automatically discovers PSR-18 HTTP clients from:
- `php-http/guzzle7-adapter`
- `php-http/curl-client`
- `symfony/http-client`
- And other PSR-18 compatible implementations
```bash
# Install any PSR-18 client - discovery works automatically
composer require php-http/guzzle7-adapter
```

View file

@ -1,520 +1,97 @@
# Examples
The MCP PHP SDK includes comprehensive examples demonstrating different patterns and use cases. Each example showcases
specific features and can be run independently to understand how the SDK works.
## Table of Contents
- [Getting Started](#getting-started)
- [Running Examples](#running-examples)
- [Server Examples](#server-examples)
- [Client Examples](#client-examples)
## Getting Started
All examples are located in the `examples/` directory and use the SDK dependencies from the root project. Most examples
can be run directly without additional setup.
### Prerequisites
Every example lives in [`examples/`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples)
and runs against the dependencies installed in the repository root. Each server example is a
`server.php` whose bootstrap picks the transport from the SAPI it runs under:
```bash
# Install dependencies (in project root)
composer install
# STDIO transport
php examples/server/discovery-calculator/server.php
# Streamable HTTP transport
php -S 127.0.0.1:8000 examples/server/discovery-userprofile/server.php
# Interactive testing with the MCP Inspector
npx @modelcontextprotocol/inspector php examples/server/discovery-calculator/server.php
```
## Running Examples
## Server examples
The bootstrapping of the example will choose the used transport based on the SAPI you use.
| Example | What it shows | Docs |
| --- | --- | --- |
| [`discovery-calculator`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/discovery-calculator) | Attribute discovery of tools, resources and prompts; `ResourceLink` content | [Tools](servers/tools.md) |
| [`discovery-userprofile`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/discovery-userprofile) | Resource templates with completion providers; `FileSessionStore` | [Resource templates](servers/resource-templates.md), [Completions](servers/completions.md) |
| [`explicit-registration`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/explicit-registration) | Manual `addTool()`/`addResource()`/`addResourceTemplate()`/`addPrompt()` without discovery | [Registering elements](servers/registration.md) |
| [`combined-registration`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/combined-registration) | Discovery and manual registration combined, and which wins on conflict | [Registering elements](servers/registration.md) |
| [`cached-discovery`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/cached-discovery) | Caching the discovery scan in a PSR-16 cache | [Server builder](run/server-builder.md#discovery-configuration) |
| [`custom-dependencies`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/custom-dependencies) | Handlers pulling services from a PSR-11 container | [Server builder](run/server-builder.md#service-dependencies) |
| [`complex-tool-schema`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/complex-tool-schema) | Rich input schemas from typed parameters, PHP enums and defaults | [Schema generation](servers/schemas.md) |
| [`schema-showcase`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/schema-showcase) | `#[Schema]` constraint attributes: formats, patterns, ranges | [Schema generation](servers/schemas.md) |
| [`env-variables`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/env-variables) | Configuring a server through environment variables | [Server builder](run/server-builder.md) |
| [`client-communication`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/client-communication) | Sampling, roots, progress and log messages from inside a handler | [Talking back to the client](handlers/client-communication.md) |
| [`client-logging`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/client-logging) | Structured log notifications through the `ClientLogger` | [Logging](handlers/logging.md) |
| [`elicitation`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/elicitation) | Asking the user for input mid-call with `InputRequiredResult` and typed elicitation schemas | [Asking for input](handlers/input-required.md) |
| [`custom-method-handlers`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/custom-method-handlers) | Registering handlers for custom JSON-RPC methods | [Custom message handlers](advanced/custom-handlers.md) |
| [`mcp-apps`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/mcp-apps) | The MCP Apps extension: a tool that ships an interactive HTML view | [Protocol extensions](advanced/extensions.md) |
| [`stateless-lifecycle`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/stateless-lifecycle) | Revision `2026-07-28`: cache policy, request state, notification bus | [Serving both eras](run/protocol-eras.md), [Caching](run/caching.md), [Subscriptions](run/subscriptions.md) |
| [`oauth-keycloak`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/oauth-keycloak) | OAuth authorization against a Keycloak instance (own README) | [Authorization](run/authorization.md) |
| [`oauth-microsoft`](https://github.com/modelcontextprotocol/php-sdk/tree/main/examples/server/oauth-microsoft) | OAuth authorization against Microsoft Entra ID (own README) | [Authorization](run/authorization.md) |
### STDIO Transport
## Client examples
The STDIO transport will use standard input/output for communication:
| Example | What it shows | Docs |
| --- | --- | --- |
| [`stdio_discovery_calculator.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/client/stdio_discovery_calculator.php) | Connecting over STDIO, listing and calling tools, reading resources | [Connecting to a server](client/connecting.md) |
| [`http_discovery_calculator.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/client/http_discovery_calculator.php) | The same conversation over the Streamable HTTP transport | [Transports](client/transports.md) |
| [`stdio_client_communication.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/client/stdio_client_communication.php) | Answering server-initiated sampling, log and progress messages | [Server-initiated requests](client/server-requests.md) |
| [`http_client_communication.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/client/http_client_communication.php) | The same handlers over HTTP — see the note on PHP's built-in server below | [Server-initiated requests](client/server-requests.md) |
| [`stdio_elicitation.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/client/stdio_elicitation.php) | Answering elicitation requests from an interactive prompt | [Server-initiated requests](client/server-requests.md) |
| [`stdio_roots.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/client/stdio_roots.php) | Exposing workspace roots and signalling `roots/list_changed` | [Server-initiated requests](client/server-requests.md) |
| [`stateless_lifecycle_client.php`](https://github.com/modelcontextprotocol/php-sdk/blob/main/examples/client/stateless_lifecycle_client.php) | A client pinned to revision `2026-07-28` — see [Modern-era client](#modern-era-client) | [Connecting to a server](client/connecting.md) |
Client examples run directly:
```bash
# Interactive testing with MCP Inspector
npx @modelcontextprotocol/inspector php examples/discovery-calculator/server.php
# Run with debugging enabled
npx @modelcontextprotocol/inspector -e DEBUG=1 -e FILE_LOG=1 php examples/discovery-calculator/server.php
# Or configure the script path in your MCP client
# Path: php examples/discovery-calculator/server.php
```
### HTTP Transport
The Streamable HTTP transport will be chosen if running examples with a web servers:
```bash
# Start the server
php -S localhost:8000 examples/discovery-userprofile/server.php
# Test with MCP Inspector
npx @modelcontextprotocol/inspector http://localhost:8000
# Test with curl
curl -X POST http://localhost:8000 \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","clientInfo":{"name":"test","version":"1.0.0"},"capabilities":{}}}'
```
## Server Examples
### Discovery Calculator
**File**: `examples/discovery-calculator/`
**What it demonstrates:**
- Attribute-based discovery using `#[McpTool]` and `#[McpResource]`
- Basic arithmetic operations
- Configuration management through resources
- State management between tool calls
**Key Features:**
```php
#[McpTool(name: 'calculate')]
public function calculate(float $a, float $b, string $operation): float|string
#[McpResource(
uri: 'config://calculator/settings',
name: 'calculator_config',
mimeType: 'application/json'
)]
public function getConfiguration(): array
```
**Usage:**
```bash
# Interactive testing
npx @modelcontextprotocol/inspector php examples/discovery-calculator/server.php
# Or configure in MCP client: php examples/discovery-calculator/server.php
```
### Explicit Registration
**File**: `examples/explicit-registration/`
**What it demonstrates:**
- Manual registration of tools, resources, and prompts
- Alternative to attribute-based discovery
- Simple handler functions
**Key Features:**
```php
$server = Server::builder()
->addTool([SimpleHandlers::class, 'echoText'], 'echo_text')
->addResource([SimpleHandlers::class, 'getAppVersion'], 'app://version')
->addPrompt([SimpleHandlers::class, 'greetingPrompt'], 'personalized_greeting')
```
### Environment Variables
**File**: `examples/env-variables/`
**What it demonstrates:**
- Environment variable integration
- Server configuration from environment
- Environment-based tool behavior
**Key Features:**
- Reading environment variables within tools
- Conditional behavior based on environment
- Environment validation and defaults
### Custom Dependencies
**File**: `examples/custom-dependencies/`
**What it demonstrates:**
- Dependency injection with PSR-11 containers
- Service layer architecture
- Repository pattern implementation
- Complex business logic integration
**Key Features:**
```php
$container->set(TaskRepositoryInterface::class, $taskRepo);
$container->set(StatsServiceInterface::class, $statsService);
$server = Server::builder()
->setContainer($container)
->setDiscovery(__DIR__, ['.'])
```
### Cached Discovery
**File**: `examples/cached-discovery/`
**What it demonstrates:**
- Discovery caching for improved performance
- PSR-16 cache integration
- Cache invalidation strategies
**Key Features:**
```php
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Psr16Cache;
$cache = new Psr16Cache(new FilesystemAdapter('mcp-discovery'));
$server = Server::builder()
->setDiscovery(__DIR__, ['.'], [], $cache)
```
### Client Communication
**File**: `examples/client-communication/`
**What it demonstrates:**
- Server initiated communication back to the client
- Logging, sampling, progress and notifications
- Using `ClientGateway` in tool method via method argument injection of `RequestContext`
### Discovery User Profile
**File**: `examples/discovery-userprofile/`
**What it demonstrates:**
- HTTP transport with StreamableHttpTransport
- Resource templates with URI parameters
- Completion providers for parameter hints
- User profile management system
- Session persistence with FileSessionStore
**Key Features:**
```php
#[McpResourceTemplate(
uriTemplate: 'user://{userId}/profile',
name: 'user_profile',
mimeType: 'application/json'
)]
public function getUserProfile(
#[CompletionProvider(values: ['101', '102', '103'])]
string $userId
): array
#[McpPrompt(name: 'generate_bio_prompt')]
public function generateBio(string $userId, string $tone = 'professional'): array
```
**Usage:**
```bash
# Start the HTTP server
php -S localhost:8000 examples/discovery-userprofile/server.php
# Test with MCP Inspector
npx @modelcontextprotocol/inspector http://localhost:8000
# Or configure in MCP client: http://localhost:8000
```
### Combined Registration
**File**: `examples/combined-registration/`
**What it demonstrates:**
- Mixing attribute discovery with manual registration
- HTTP server with both discovered and manual capabilities
- All three handler styles: discovered, `[Class::class, 'method']`, and a pre-built `[$instance, 'method']`
- Pre-built instance handlers for classes the container cannot auto-wire (e.g. constructor scalars)
**Key Features:**
```php
// Built here so its constructor dependencies are injected before registration;
// the SDK invokes this very instance instead of constructing one itself.
$preconfiguredGreeter = new PreconfiguredGreeter('Willkommen', logger());
$server = Server::builder()
->setDiscovery(__DIR__, ['.']) // Automatic discovery
->addTool([ManualHandlers::class, 'manualGreeter']) // Manual class-string handler
->addTool([$preconfiguredGreeter, 'greet'], 'instance_greeter') // Pre-built instance handler
->addResource([ManualHandlers::class, 'getPriorityConfigManual'], 'config://priority')
```
### Complex Tool Schema
**File**: `examples/complex-tool-schema/`
**What it demonstrates:**
- Advanced JSON schema definitions
- Complex data structures and validation
- Event scheduling and management
- Enum types and nested objects
**Key Features:**
```php
#[Schema(definition: [
'type' => 'object',
'properties' => [
'title' => ['type' => 'string', 'minLength' => 1, 'maxLength' => 100],
'eventType' => ['type' => 'string', 'enum' => ['meeting', 'deadline', 'reminder']],
'priority' => ['type' => 'string', 'enum' => ['low', 'medium', 'high', 'urgent']]
]
])]
public function scheduleEvent(array $eventData): array
```
### Schema Showcase
**File**: `examples/schema-showcase/`
**What it demonstrates:**
- Comprehensive JSON schema features
- Parameter-level schema validation
- String constraints (minLength, maxLength, pattern)
- Numeric constraints (minimum, maximum, multipleOf)
- Array and object validation
**Key Features:**
```php
#[McpTool]
public function formatText(
#[Schema(
type: 'string',
minLength: 5,
maxLength: 100,
pattern: '^[a-zA-Z0-9\s\.,!?\-]+$'
)]
string $text,
#[Schema(enum: ['uppercase', 'lowercase', 'title', 'sentence'])]
string $format = 'sentence'
): array
```
### Elicitation
**File**: `examples/server/elicitation/`
**What it demonstrates:**
- Server-to-client elicitation requests
- Interactive user input during tool execution
- Multi-field form schemas with validation
- Boolean confirmation dialogs
- Enum fields with human-readable labels
- Handling accept/decline/cancel responses
- Session persistence requirement for server-initiated requests
**Key Features:**
```php
// Check client support before eliciting
if (!$context->getClientGateway()->supportsElicitation()) {
return ['status' => 'error', 'message' => 'Client does not support elicitation'];
}
// Build schema with multiple field types
$schema = new ElicitationSchema(
properties: [
'party_size' => new NumberSchemaDefinition(
title: 'Party Size',
integerOnly: true,
minimum: 1,
maximum: 20
),
'date' => new StringSchemaDefinition(
title: 'Reservation Date',
format: 'date'
),
'dietary' => new EnumSchemaDefinition(
title: 'Dietary Restrictions',
enum: ['none', 'vegetarian', 'vegan'],
enumNames: ['None', 'Vegetarian', 'Vegan']
),
],
required: ['party_size', 'date']
);
// Send elicitation request
$result = $client->elicit(
message: 'Please provide your reservation details',
requestedSchema: $schema
);
// Handle response
if ($result->isAccepted()) {
$data = $result->content; // User-provided data
} elseif ($result->isDeclined() || $result->isCancelled()) {
// User declined or cancelled
}
```
**Important Notes:**
- Elicitation requires a session store (e.g., `FileSessionStore`)
- Check client capabilities with `supportsElicitation()` before sending requests
- Schema supports primitive types: string, number/integer, boolean, enum
- String fields support format validation: date, date-time, email, uri
- Users can accept (providing data), decline, or cancel requests
**Usage:**
```bash
# Interactive testing with MCP client that supports elicitation
npx @modelcontextprotocol/inspector php examples/server/elicitation/server.php
# Test with Goose (confirmed working by reviewer)
# Or configure in Claude Desktop or other MCP clients
```
**Example Tools:**
1. **book_restaurant** - Multi-field reservation form with number, date, and enum fields
2. **confirm_action** - Simple boolean confirmation dialog
3. **collect_feedback** - Rating and comments form with optional fields
### MCP Apps
**File**: `examples/server/mcp-apps/`
A weather app demonstrating the [MCP Apps extension](extensions.md): a `ui://`
HTML resource is opened by an MCP App-aware client (e.g. Goose) and bridged to
the `get_weather` tool. The bundled `weather-app.html` performs the
`ui/initialize` handshake, reports its size via `ui/notifications/size-changed`,
and calls back into the server. See the
[ext-apps repo](https://github.com/modelcontextprotocol/ext-apps) for the
TypeScript SDK and richer view-side patterns.
## Client Examples
### STDIO Discovery Calculator (Client)
**File**: `examples/client/stdio_discovery_calculator.php`
**What it demonstrates:**
- Basic MCP client usage with STDIO transport
- Connecting to a local MCP server process
- Listing and calling tools
- Reading resources
**Key Features:**
```php
$client = Client::builder()
->setClientInfo('STDIO Example Client', '1.0.0')
->setInitTimeout(30)
->setRequestTimeout(60)
->build();
$transport = new StdioTransport(
command: 'php',
args: [__DIR__.'/../server/discovery-calculator/server.php'],
);
$client->connect($transport);
$tools = $client->listTools();
$result = $client->callTool('calculate', ['a' => 5, 'b' => 3, 'operation' => 'add']);
$resourceContent = $client->readResource('config://calculator/settings');
```
**Usage:**
```bash
# Run the client (automatically starts the server)
php examples/client/stdio_discovery_calculator.php
```
### HTTP Discovery Calculator (Client)
> **Note**: PHP's built-in development server handles one request at a time, so the sampling
> round-trip in `http_client_communication.php` will not complete under a plain `php -S`.
> Start it with worker processes instead: `PHP_CLI_SERVER_WORKERS=2 php -S 127.0.0.1:8000 …`.
**File**: `examples/client/http_discovery_calculator.php`
## The 2026-07-28 lifecycle
**What it demonstrates:**
- MCP client with HTTP transport
- Connecting to remote MCP servers
- Listing tools, resources, and prompts
`stateless-lifecycle/server.php` answers both eras on the same URL. On revision `2026-07-28`
every request carries its own protocol version and client capabilities, so a call is a single
POST with no handshake before it:
**Key Features:**
```php
$transport = new HttpTransport('http://localhost:8000');
$client->connect($transport);
$tools = $client->listTools();
$resources = $client->listResources();
$prompts = $client->listPrompts();
```
**Usage:**
```bash
# Start the server first
php -S localhost:8000 examples/server/http-discovery-calculator/server.php
# Then run the client
php examples/client/http_discovery_calculator.php
php -S 127.0.0.1:8000 examples/server/stateless-lifecycle/server.php
```
### STDIO Client Communication
**File**: `examples/client/stdio_client_communication.php`
**What it demonstrates:**
- Server-to-client communication (logging, progress, sampling)
- Handling logging notifications from server
- Implementing sampling callbacks for LLM requests
- Progress tracking during tool execution
**Key Features:**
```php
use Mcp\Client\Handler\Notification\LoggingNotificationHandler;
use Mcp\Client\Handler\Request\SamplingRequestHandler;
use Mcp\Client\Handler\Request\SamplingCallbackInterface;
use Mcp\Schema\ClientCapabilities;
$loggingHandler = new LoggingNotificationHandler(
static function (LoggingMessageNotification $n) {
echo "[LOG {$n->level->value}] {$n->data}\n";
}
);
$samplingHandler = new SamplingRequestHandler(new class implements SamplingCallbackInterface {
public function __invoke(CreateSamplingMessageRequest $request): CreateSamplingMessageResult
{
// Perform LLM sampling and return result
}
});
$client = Client::builder()
->setCapabilities(new ClientCapabilities(sampling: true))
->addNotificationHandler($loggingHandler)
->addRequestHandler($samplingHandler)
->build();
// Call tool with progress tracking
$result = $client->callTool(
name: 'run_dataset_quality_checks',
arguments: ['dataset' => 'customer_orders_2024'],
onProgress: static function (float $progress, ?float $total, ?string $message) {
$percent = $total > 0 ? round(($progress / $total) * 100) : '?';
echo "[PROGRESS {$percent}%] {$message}\n";
}
);
```
**Usage:**
```bash
# Run the client (automatically starts the communication server)
php examples/client/stdio_client_communication.php
curl -sS http://127.0.0.1:8000/ \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-H 'MCP-Protocol-Version: 2026-07-28' \
-H 'Mcp-Method: server/discover' \
-d '{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{"_meta":{
"io.modelcontextprotocol/protocolVersion":"2026-07-28",
"io.modelcontextprotocol/clientCapabilities":{}}}}'
```
### HTTP Client Communication
The example's header comments document the equivalent handshake-era conversation against the
same endpoint. [Serving both eras](run/protocol-eras.md) explains how the routing works.
**File**: `examples/client/http_client_communication.php`
## Modern-era client
**What it demonstrates:**
- Server-to-client communication over HTTP
- Receiving logging and progress notifications via SSE streaming
- Implementing sampling for HTTP-based servers
- Progress tracking with long-running operations
`stateless_lifecycle_client.php` drives the server above from PHP: it pins
`ProtocolVersion::V2026_07_28`, skips the handshake, discovers the server through
`server/discover` and calls a tool — one process, no session:
**Key Features:**
- Same client-side code as STDIO version
- Uses HttpTransport instead of StdioTransport
- Demonstrates SSE-based real-time notifications
- Shows HTTP session management
**Usage:**
```bash
# Start the server
php -S 127.0.0.1:8000 examples/server/client-communication/server.php
# Run the client
php examples/client/http_client_communication.php
php -S 127.0.0.1:8000 examples/server/stateless-lifecycle/server.php &
php examples/client/stateless_lifecycle_client.php
```
> [!NOTE]
> For sampling with HTTP transport, the server must support concurrent request processing (e.g., using Symfony CLI, PHP-FPM, or a production web server). PHP's built-in development server cannot handle the concurrent requests required for sampling.
See [Clients on the modern revision](client/connecting.md) for the API it uses.

11
docs/favicon.svg Normal file
View file

@ -0,0 +1,11 @@
<svg width="180" height="180" viewBox="0 0 180 180" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="180" height="180" rx="24" fill="black"/>
<mask id="mask0_246_1229" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="7" y="7" width="166" height="166">
<path d="M173 7H7V173H173V7Z" fill="white"/>
</mask>
<g mask="url(#mask0_246_1229)">
<path d="M23.5996 85.2532L86.2021 22.6507C94.8457 14.0071 108.86 14.0071 117.503 22.6507C126.147 31.2942 126.147 45.3083 117.503 53.9519L70.2254 101.23" stroke="white" stroke-width="11.0667" stroke-linecap="round"/>
<path d="M70.8789 100.578L117.504 53.952C126.148 45.3083 140.163 45.3083 148.806 53.952L149.132 54.278C157.776 62.9216 157.776 76.9357 149.132 85.5792L92.5139 142.198C89.6327 145.079 89.6327 149.75 92.5139 152.631L104.14 164.257" stroke="white" stroke-width="11.0667" stroke-linecap="round"/>
<path d="M101.853 38.3013L55.553 84.6011C46.9094 93.2447 46.9094 107.258 55.553 115.902C64.1966 124.546 78.2106 124.546 86.8543 115.902L133.154 69.6025" stroke="white" stroke-width="11.0667" stroke-linecap="round"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

View file

@ -0,0 +1,84 @@
# First server
A server is a plain PHP class plus three lines of wiring. Create `server.php` next to
your `vendor/` directory:
```php-file title="server.php"
#!/usr/bin/env php
<?php
require __DIR__.'/vendor/autoload.php';
use Mcp\Capability\Attribute\McpResource;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Server;
use Mcp\Server\Transport\StdioTransport;
class Calculator
{
/**
* Adds two numbers.
*/
#[McpTool]
public function add(int $a, int $b): int
{
return $a + $b;
}
#[McpResource(uri: 'config://calculator/settings')]
public function settings(): array
{
return ['precision' => 2];
}
}
exit(Server::builder()
->setServerInfo('Calculator', '1.0.0')
->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor'])
->build()
->run(new StdioTransport()));
```
Discovery needs `symfony/finder`:
```bash
composer require symfony/finder
```
## What each piece does
`#[McpTool]` marks a method as an action the *model* can call. Its name defaults to the
method name, its description comes from the docblock (the summary, plus the longer
description if you write one), and its input schema is
generated from the parameter types — `int $a, int $b` becomes a JSON Schema with two
required integers. See [Tools](../servers/tools.md).
`#[McpResource]` marks a method as read-only data the *application* can read, addressed
by URI. See [Resources](../servers/resources.md).
`setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor'])` scans those directories for
attributed classes. Scanning is lazy: it happens on the first request that needs the
registry, not when `build()` returns — call `setLazyLoading(false)` if you would rather
pay for it up front. Excluding `vendor` matters because the scan is recursive and would
otherwise read and autoload every file your dependencies ship. If you would rather
register elements explicitly — or mix both — see
[Registering elements](../servers/registration.md).
`run(new StdioTransport())` speaks JSON-RPC over stdin/stdout and returns an exit code.
That is the transport local MCP hosts launch as a subprocess; for a web-facing server
use the [HTTP transport](../run/http.md) instead.
!!! warning "Never write to STDOUT"
With the STDIO transport, `STDOUT` carries the protocol. `echo`, `print_r()`, or a
stray `var_dump()` in a handler corrupts the stream. Write to `STDERR`, or use the
[logger](../handlers/logging.md).
## Run it
```bash
php server.php
```
Nothing happens — the server is waiting for JSON-RPC on stdin, which is exactly right.
Stop it with `Ctrl+C`, and let a real client drive it instead:
[Try it with the Inspector](inspector.md).

27
docs/get-started/index.md Normal file
View file

@ -0,0 +1,27 @@
# Get started
New to MCP, or new to this SDK? Start here. These pages take you from nothing to a
server a real MCP host can talk to: [install the SDK](installation.md), build your
[first server](first-server.md), and [open it in the Inspector](inspector.md).
## Run the code
Every code block on these pages is a complete, working file — copy it into
`server.php` next to your `vendor/` directory and run it.
It is worth actually typing (or pasting) and running them: what the SDK does for you
only really shows up in your own editor, where the type hints you write turn into the
schema a model sees.
## Where to go next
Once you have a server running, the rest of these docs are a reference, not a course.
Every page stands on its own, so jump straight to what you need:
* What a server exposes (tools, resources, prompts) is **[Servers](../servers/index.md)**.
* Getting it in front of clients (STDIO, HTTP, an existing framework app) is
**[Running your server](../run/index.md)**.
* What is available inside the functions you register is
**[Inside your handler](../handlers/index.md)**.
* Building the other side, an application that *uses* MCP servers, is
**[Clients](../client/index.md)**.

View file

@ -0,0 +1,88 @@
# Try it with the Inspector
The [MCP Inspector](https://modelcontextprotocol.io/docs/latest/tools/inspector) is an interactive
UI for poking at a server: it lists what the server exposes and lets you call it by
hand. It is the fastest way to see whether your server does what you think it does.
It is a Node.js application, so this needs `npx` on your `PATH`.
## STDIO
Point the Inspector at the command that starts your server — it launches the process
itself:
```bash
npx @modelcontextprotocol/inspector php server.php
```
Open the URL it prints. Under **Tools**, call `add` with `a=1` and `b=2`; you get `3`
back. The form the Inspector built for you — a required integer field for each argument
— came from the type hints on the method. So will the schema every other MCP host sees.
Under **Resources**, read `config://calculator/settings` to get the array back as JSON.
## HTTP
A server behind a web server speaks the [HTTP transport](../run/http.md) instead, so the
last lines of `server.php` change — `StdioTransport` reads stdin and would just block
under `php -S`:
```php title="server.php (HTTP variant)"
use Http\Discovery\Psr17Factory;
use Mcp\Server\Session\FileSessionStore;
use Mcp\Server\Transport\StreamableHttpTransport;
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
$request = (new Psr17Factory())->createServerRequestFromGlobals();
$response = Server::builder()
->setServerInfo('Calculator', '1.0.0')
->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor'])
->setSession(new FileSessionStore(__DIR__.'/sessions'))
->build()
->run(new StreamableHttpTransport($request));
(new SapiEmitter())->emit($response);
```
That needs a PSR-17 implementation and an emitter
(`composer require nyholm/psr7 laminas/laminas-httphandlerrunner`). Start it, then give
the Inspector its URL:
```bash
php -S localhost:8000 server.php
npx @modelcontextprotocol/inspector http://localhost:8000
```
`curl` works too, if you would rather see the wire format:
```bash
curl -X POST http://localhost:8000 \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-11-25","clientInfo":{"name":"test","version":"1.0.0"},"capabilities":{}}}'
```
## Connect a real host
Hosts that launch local servers take the same command the Inspector did. For Claude
Desktop, that is an entry in its configuration file:
```json
{
"mcpServers": {
"calculator": {
"command": "php",
"args": ["/absolute/path/to/server.php"]
}
}
}
```
Use an absolute path: the host does not run the command from your project directory.
## Next
* Add more of what a server can expose: **[Servers](../servers/index.md)**.
* Put it on the web instead of stdin/stdout: **[HTTP transport](../run/http.md)**.
* Drive a server from PHP instead of a UI: **[Clients](../client/index.md)**.

View file

@ -0,0 +1,44 @@
# Installation
The SDK ships as a single Composer package:
```bash
composer require mcp/sdk
```
It requires **PHP 8.1+** and the `fileinfo` extension. Most of what it pulls in is PSR
interface packages (`psr/container`, `psr/log`, `psr/http-message`, …); the rest is
`opis/json-schema` for schema validation, `symfony/uid` for session identifiers,
`phpdocumentor/reflection-docblock` for reading descriptions out of your docblocks, and
`php-http/discovery` for finding PSR-17/PSR-18 implementations.
That is enough for a complete [STDIO server](../run/stdio.md) and for the
[STDIO client](../client/transports.md).
## Optional packages
Which extras you need depends on what you build:
| You want to… | Also install |
| --- | --- |
| discover `#[McpTool]` & friends from a directory | `symfony/finder` |
| serve over [HTTP](../run/http.md) | any PSR-17 implementation, e.g. `nyholm/psr7` |
| emit the response from a standalone HTTP entry point | `laminas/laminas-httphandlerrunner` |
| [connect a client over HTTP](../client/transports.md) | any PSR-18 client, e.g. `symfony/http-client` |
| [validate JWT access tokens](../run/authorization.md) | `firebase/php-jwt` |
| store sessions in a PSR-16 cache | `psr/simple-cache` implementation, e.g. `symfony/cache` |
PSR-17 and PSR-18 implementations are found through
[`php-http/discovery`](https://docs.php-http.org/en/latest/discovery.html), so
installing the package is all that is needed — no wiring:
```bash
composer require nyholm/psr7
```
If discovery picks the wrong one, or you want to be explicit, pass the factories to the
transport yourself; see [HTTP transport](../run/http.md).
## Next
Write your [first server](first-server.md).

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);
```

Some files were not shown because too many files have changed in this diff Show more