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

2
.gitattributes vendored
View file

@ -5,6 +5,8 @@
/tests export-ignore /tests export-ignore
/.php-cs-fixer.dist.php export-ignore /.php-cs-fixer.dist.php export-ignore
/Makefile export-ignore /Makefile export-ignore
/mkdocs.yml export-ignore
/requirements-docs.txt export-ignore
/phpdoc.dist.xml /phpdoc.dist.xml
/phpstan* export-ignore /phpstan* export-ignore
/phpunit.xml.dist export-ignore /phpunit.xml.dist export-ignore

View file

@ -1,15 +1,25 @@
name: Deploy Documentation name: Documentation
# The site is built by `make docs`: Zensical renders the guides under docs/
# (see mkdocs.yml) and phpDocumentor renders the API reference into /api/.
# Pull requests build only — the build is strict, so a broken internal link
# fails CI instead of shipping a dead link to the site.
on: on:
release: push:
types: [published] branches: [main]
pull_request:
workflow_dispatch: workflow_dispatch:
permissions: permissions:
contents: write contents: read
concurrency:
group: docs-${{ github.ref }}
cancel-in-progress: true
jobs: jobs:
deploy: build:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout - name: Checkout
@ -21,16 +31,33 @@ jobs:
php-version: '8.4' php-version: '8.4'
coverage: "none" coverage: "none"
- name: Install Composer - name: Install Composer dependencies
uses: "ramsey/composer-install@v4" uses: "ramsey/composer-install@v4"
- name: Generate Documentation - name: Install uv
uses: astral-sh/setup-uv@v9.0.0
with:
enable-cache: true
- name: Build documentation
run: make docs run: make docs
- name: Deploy to gh-pages branch - name: Upload Pages artifact
uses: peaceiris/actions-gh-pages@v4 uses: actions/upload-pages-artifact@v5
with: with:
github_token: ${{ secrets.GITHUB_TOKEN }} path: ./site
publish_dir: ./.phpdoc/build
enable_jekyll: false deploy:
cname: php.sdk.modelcontextprotocol.io needs: build
if: github.event_name != 'pull_request'
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v5

View file

@ -244,5 +244,7 @@ jobs:
- name: PHPStan - name: PHPStan
run: vendor/bin/phpstan analyse run: vendor/bin/phpstan analyse
# Only the phpDocumentor half: this job is PHP-only, and the Zensical
# guides are built (strictly) by the Documentation workflow.
- name: Documentation - name: Documentation
run: make docs run: make docs-api

4
.gitignore vendored
View file

@ -15,3 +15,7 @@ tests/Conformance/logs/*.log
# phpDocumentor # phpDocumentor
.phpdoc/build/ .phpdoc/build/
.phpdoc/cache/ .phpdoc/cache/
# Documentation site (make docs)
/site/
/.cache/

View file

@ -2,7 +2,7 @@
{% set topMenu = { {% set topMenu = {
"menu": [ "menu": [
{ "name": "Guides", "url": "docs/index.html"}, { "name": "Guides", "url": "/"},
{ "name": "Specification", "url": "https://modelcontextprotocol.io/" } { "name": "Specification", "url": "https://modelcontextprotocol.io/" }
], ],
"social": [ "social": [

View file

@ -1,5 +1,5 @@
<h1 class="phpdocumentor-title"> <h1 class="phpdocumentor-title">
<a href="{{ path('/docs/index.html') }}" class="phpdocumentor-title__link"> <a href="/" class="phpdocumentor-title__link">
<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 195 195" fill="none"> <svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="0 0 195 195" fill="none">
<path d="M25 97.8528L92.8823 29.9706C102.255 20.598 117.451 20.598 126.823 29.9706V29.9706C136.196 39.3431 136.196 54.5391 126.823 63.9117L75.5581 115.177" stroke="black" stroke-width="12" stroke-linecap="round"/> <path d="M25 97.8528L92.8823 29.9706C102.255 20.598 117.451 20.598 126.823 29.9706V29.9706C136.196 39.3431 136.196 54.5391 126.823 63.9117L75.5581 115.177" stroke="black" stroke-width="12" stroke-linecap="round"/>
<path d="M76.2653 114.47L126.823 63.9117C136.196 54.5391 151.392 54.5391 160.765 63.9117L161.118 64.2652C170.491 73.6378 170.491 88.8338 161.118 98.2063L99.7248 159.6C96.6006 162.724 96.6006 167.789 99.7248 170.913L112.331 183.52" stroke="black" stroke-width="12" stroke-linecap="round"/> <path d="M76.2653 114.47L126.823 63.9117C136.196 54.5391 151.392 54.5391 160.765 63.9117L161.118 64.2652C170.491 73.6378 170.491 88.8338 161.118 98.2063L99.7248 159.6C96.6006 162.724 96.6006 167.789 99.7248 170.913L112.331 183.52" stroke="black" stroke-width="12" stroke-linecap="round"/>

View file

@ -14,7 +14,7 @@ All notable changes to `mcp/sdk` will be documented in this file.
* Answer a request over a response stream under the 2026-07-28 lifecycle: `StatelessProtocol` runs handlers in a fiber, so `$gateway->progress()` and `$gateway->log()` work there as they do in the handshake era. The stream opens only if the handler actually emits something *and* the client's `Accept` admits `text/event-stream`, and the choice is made after the handler's first suspension, so a request that turns out to need `-32021` or `-32602` is still answered with the status the spec fixes for it. * Answer a request over a response stream under the 2026-07-28 lifecycle: `StatelessProtocol` runs handlers in a fiber, so `$gateway->progress()` and `$gateway->log()` work there as they do in the handshake era. The stream opens only if the handler actually emits something *and* the client's `Accept` admits `text/event-stream`, and the choice is made after the handler's first suspension, so a request that turns out to need `-32021` or `-32602` is still answered with the status the spec fixes for it.
* Honour `io.modelcontextprotocol/logLevel` (SEP-2575), which replaced the `logging/setLevel` RPC: a request naming no level receives no `notifications/message` at all, one naming a level receives the messages at or above it. Adds `LoggingLevel::severity()` and `LoggingLevel::isAtLeast()`. * Honour `io.modelcontextprotocol/logLevel` (SEP-2575), which replaced the `logging/setLevel` RPC: a request naming no level receives no `notifications/message` at all, one naming a level receives the messages at or above it. Adds `LoggingLevel::severity()` and `LoggingLevel::isAtLeast()`.
* [BC Break] Answer a not-found subject with `-32602` (Invalid params) instead of `-32002`, which the 2026-07-28 revision reserves and forbids emitting (SEP-2164). `resources/read` picks the code from the revision serving the request — `-32602` with the uri in `error.data` from `2026-07-28` on, `-32002` below. `prompts/get` for an unknown prompt, `completion/complete` for an unknown reference and `tools/call` for an unknown tool switch to `-32602` in *every* revision: `-32002` was never the code for those. Adds `ProtocolVersion::usesInvalidParamsForResourceNotFound()`. * [BC Break] Answer a not-found subject with `-32602` (Invalid params) instead of `-32002`, which the 2026-07-28 revision reserves and forbids emitting (SEP-2164). `resources/read` picks the code from the revision serving the request — `-32602` with the uri in `error.data` from `2026-07-28` on, `-32002` below. `prompts/get` for an unknown prompt, `completion/complete` for an unknown reference and `tools/call` for an unknown tool switch to `-32602` in *every* revision: `-32002` was never the code for those. Adds `ProtocolVersion::usesInvalidParamsForResourceNotFound()`.
* Add the multi round-trip requests pattern for the 2026-07-28 lifecycle (SEP-2322): a `tools/call` or `prompts/get` handler returning `Mcp\Schema\Result\InputRequiredResult` comes back as `resultType: "input_required"` carrying the `inputRequests` it needs answered and an opaque `requestState`; the client retries the same request with `inputResponses`, which the handler reads through `RequestContext::getInputContext()`. `Mcp\Server\Stateless\RequestStateCodec` signs and time-bounds the state — set the key with `Builder::setRequestStateKey()`. * Add the multi round-trip requests pattern for the 2026-07-28 lifecycle (SEP-2322): a `tools/call` or `prompts/get` handler returning `Mcp\Schema\Result\InputRequiredResult` comes back as `resultType: "input_required"` carrying the `inputRequests` it needs answered and an opaque `requestState`; the client retries the same request with `inputResponses`, which the handler reads through `RequestContext::getInputContext()`. `Mcp\Server\Stateless\RequestStateCodec` signs and time-bounds the state — set the key with `Builder::setRequestState()`.
* Validate the standard MCP request headers under the 2026-07-28 lifecycle (SEP-2243): `Mcp\Server\Stateless\StandardHeaderValidator`, set with `Builder::setHeaderValidator()`, checks that `Mcp-Method` and `Mcp-Name` agree with the body they travel with and that a `Mcp-Param-*` mirrors the argument its tool marked `x-mcp-header`, answering `-32020` when they disagree. Intermediaries route on these headers, so a value contradicting the body has to be refused rather than ignored. * Validate the standard MCP request headers under the 2026-07-28 lifecycle (SEP-2243): `Mcp\Server\Stateless\StandardHeaderValidator`, set with `Builder::setHeaderValidator()`, checks that `Mcp-Method` and `Mcp-Name` agree with the body they travel with and that a `Mcp-Param-*` mirrors the argument its tool marked `x-mcp-header`, answering `-32020` when they disagree. Intermediaries route on these headers, so a value contradicting the body has to be refused rather than ignored.
* [BC Break] `Mcp\Schema\JsonRpc\Error` accepts `null` as its `$id`, and `getId()` may return it. An error response whose id could not be read now omits the member instead of sending `"id": ""` — which claimed the peer had issued a request with an empty-string id. All the `for*()` factories default to `null`, `fromArray()` accepts a missing or explicitly-null id, and `MessageFactory` decodes both as an id-less error rather than rejecting them. * [BC Break] `Mcp\Schema\JsonRpc\Error` accepts `null` as its `$id`, and `getId()` may return it. An error response whose id could not be read now omits the member instead of sending `"id": ""` — which claimed the peer had issued a request with an empty-string id. All the `for*()` factories default to `null`, `fromArray()` accepts a missing or explicitly-null id, and `MessageFactory` decodes both as an id-less error rather than rejecting them.
* Preserve the original request `id` on an invalid-but-parseable message (`-32600`) instead of answering it id-less: `InvalidInputMessageException` now carries the recoverable id via `getRequestId()`/`setRequestId()`, threaded from `MessageFactory` through to the error response. * Preserve the original request `id` on an invalid-but-parseable message (`-32600`) instead of answering it id-less: `InvalidInputMessageException` now carries the recoverable id via `getRequestId()`/`setRequestId()`, threaded from `MessageFactory` through to the error response.

View file

@ -1,4 +1,4 @@
.PHONY: deps-stable deps-low cs phpstan tests unit-tests integration-tests inspector-tests coverage ci ci-stable ci-lowest conformance-tests conformance-server conformance-client conformance-draft conformance-draft-server conformance-draft-client docs .PHONY: deps-stable deps-low cs phpstan tests unit-tests integration-tests inspector-tests coverage ci ci-stable ci-lowest conformance-tests conformance-server conformance-client conformance-draft conformance-draft-server conformance-draft-client docs docs-guides docs-api docs-serve
# The 2026-07-28 scenarios ship on the `alpha` dist-tag; `latest` (0.1.x) has # The 2026-07-28 scenarios ship on the `alpha` dist-tag; `latest` (0.1.x) has
# none of them. Pinned to the same version CI runs (see # none of them. Pinned to the same version CI runs (see
@ -6,6 +6,11 @@
CONFORMANCE_VERSION ?= 0.2.0-alpha.11 CONFORMANCE_VERSION ?= 0.2.0-alpha.11
CONFORMANCE = npx --yes @modelcontextprotocol/conformance@$(CONFORMANCE_VERSION) CONFORMANCE = npx --yes @modelcontextprotocol/conformance@$(CONFORMANCE_VERSION)
# The documentation toolchain is Python (Zensical, see requirements-docs.txt),
# run through uv so no virtualenv has to be managed by hand:
# https://docs.astral.sh/uv/getting-started/installation/
DOCS_RUN = uv run --no-project --with-requirements requirements-docs.txt --
deps-stable: deps-stable:
composer update --prefer-stable composer update --prefer-stable
@ -73,7 +78,19 @@ ci-stable: deps-stable cs phpstan tests
ci-lowest: deps-low cs phpstan tests ci-lowest: deps-low cs phpstan tests
docs: # The published site is the guides (Zensical) with the phpDocumentor API
vendor/bin/phpdoc # reference mounted at /api/. `zensical build` wipes site/, so it runs first.
@grep -q 'No errors have been found' .phpdoc/build/reports/errors.html || \ docs: docs-guides docs-api
(echo "Documentation errors found. See build/docs/reports/errors.html" && exit 1) rm -rf site/api
cp -a .phpdoc/build/api site/api
docs-guides:
$(DOCS_RUN) zensical build --strict
docs-api:
vendor/bin/phpdoc --no-interaction
@grep -q 'No errors have been found' .phpdoc/build/api/reports/errors.html || \
(echo "Documentation errors found. See .phpdoc/build/api/reports/errors.html" && exit 1)
docs-serve:
$(DOCS_RUN) zensical serve

272
README.md
View file

@ -14,8 +14,9 @@
</div> </div>
The official PHP SDK for Model Context Protocol (MCP). It provides a framework-agnostic API for implementing MCP servers The official PHP SDK for the Model Context Protocol (MCP). It provides a framework-agnostic API for implementing MCP
and clients in PHP. servers and clients in PHP — tools, resources, prompts, STDIO and HTTP transports, sessions, authorization, and both
protocol eras (the `initialize` handshake and the stateless `2026-07-28` revision).
This project represents a collaboration between [the PHP Foundation](https://thephp.foundation/) and the [Symfony project](https://symfony.com/). It adopts This project represents a collaboration between [the PHP Foundation](https://thephp.foundation/) and the [Symfony project](https://symfony.com/). It adopts
development practices and standards from the Symfony project, including [Coding Standards](https://symfony.com/doc/current/contributing/code/standards.html) and the development practices and standards from the Symfony project, including [Coding Standards](https://symfony.com/doc/current/contributing/code/standards.html) and the
@ -24,47 +25,27 @@ development practices and standards from the Symfony project, including [Coding
Until the first major release, this SDK is considered [experimental](https://symfony.com/doc/current/contributing/code/experimental.html), please see the [roadmap](./ROADMAP.md) for Until the first major release, this SDK is considered [experimental](https://symfony.com/doc/current/contributing/code/experimental.html), please see the [roadmap](./ROADMAP.md) for
planned next steps and features. planned next steps and features.
## Table of Contents
- [Installation](#installation)
- [Overview](#overview)
- [Server SDK](#server-sdk)
- [Client SDK](#client-sdk)
- [Documentation](#documentation)
- [External Resources](#external-resources)
- [PHP Libraries Using the MCP SDK](#php-libraries-using-the-mcp-sdk)
- [Contributing](#contributing)
- [Credits](#credits)
- [License](#license)
## Installation ## Installation
```bash ```bash
composer require mcp/sdk composer require mcp/sdk
``` ```
## Overview ## Build a server
The MCP PHP SDK provides both **server** and **client** implementations for the Model Context Protocol, enabling you to: A server is a plain PHP class plus three lines of wiring:
- **Build MCP Servers**: Expose your PHP application's functionality (tools, resources, prompts) to AI agents
- **Build MCP Clients**: Connect to and interact with MCP servers from your PHP applications
## Server SDK
Build MCP servers to expose your PHP application's capabilities to AI agents like Claude, Codex, and others.
### Quick Start
```php ```php
use Mcp\Capability\Attribute\McpResource;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Server; use Mcp\Server;
use Mcp\Server\Transport\StdioTransport; use Mcp\Server\Transport\StdioTransport;
use Mcp\Capability\Attribute\McpTool;
use Mcp\Capability\Attribute\McpResource;
// Define capabilities using PHP attributes class Calculator
class CalculatorCapabilities
{ {
/**
* Adds two numbers.
*/
#[McpTool] #[McpTool]
public function add(int $a, int $b): int public function add(int $a, int $b): int
{ {
@ -72,237 +53,56 @@ class CalculatorCapabilities
} }
#[McpResource(uri: 'config://calculator/settings')] #[McpResource(uri: 'config://calculator/settings')]
public function getSettings(): array public function settings(): array
{ {
return ['precision' => 2]; return ['precision' => 2];
} }
} }
// Build and run the server exit(Server::builder()
$server = Server::builder() ->setServerInfo('Calculator', '1.0.0')
->setServerInfo('Calculator Server', '1.0.0') ->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor'])
->setDiscovery(__DIR__, ['.']) // Auto-discover attributes ->build()
->build(); ->run(new StdioTransport()));
$transport = new StdioTransport();
$server->run($transport);
``` ```
### Server Capabilities The walkthrough in [First server](docs/get-started/first-server.md) explains each piece, and
[Try it with the Inspector](docs/get-started/inspector.md) shows it running.
- **Tools**: Executable functions that AI agents can call ## Build a client
- **Resources**: Data sources that can be read (files, configs, databases)
- **Resource Templates**: Dynamic resources with URI parameters
- **Prompts**: Pre-defined templates for AI interactions
- **Server-Initiated Communication**: Elicitations, sampling, logging, progress notifications
### Registration Methods
There are multiple ways to register your MCP capabilities—choose the approach that best fits your application's architecture:
**1. Attribute-Based Discovery** — Define capabilities using PHP attributes for automatic discovery:
```php
#[McpTool]
public function generateReport(): string { /* ... */ }
#[McpResource(uri: 'config://app/settings')]
public function getConfig(): array { /* ... */ }
```
**2. Manual Registration** — Register capabilities programmatically without attributes:
```php
$server = Server::builder()
->addTool([Calculator::class, 'add'], 'add_numbers')
->addResource([Config::class, 'get'], 'config://app')
->build();
```
**3. Hybrid Approach** — Combine both methods for maximum flexibility:
```php
$server = Server::builder()
->setDiscovery(__DIR__, ['.'])
->addTool([ExternalService::class, 'process'], 'external')
->build();
```
### Transports
Choose the transport that matches your deployment environment:
**1. STDIO Transport** — For command-line integration and local processes:
```php
$transport = new StdioTransport();
$server->run($transport);
```
**2. HTTP Transport** — For web-based servers and distributed systems:
```php
$transport = new StreamableHttpTransport($request, $responseFactory, $streamFactory);
$response = $server->run($transport);
```
### Session Management
Configure session storage to maintain state between requests. Choose the backend that fits your infrastructure:
**In-Memory** (default, suitable for STDIO):
```php
$server = Server::builder()
->setSession(ttl: 7200) // 2 hours
->build();
```
**File-Based** (suitable for single-server HTTP deployments):
```php
$server = Server::builder()
->setSession(new FileSessionStore(__DIR__ . '/sessions'))
->build();
```
**PSR-16 Cache** (for example with Redis for scaled deployments):
```php
$server = Server::builder()
->setSession(new Psr16SessionStore(
cache: new Psr16Cache($redisAdapter),
prefix: 'mcp-',
ttl: 3600
))
->build();
```
[→ Server Documentation](docs/server-builder.md)
## Client SDK
Connect to MCP servers from your PHP applications to access their tools, resources, and prompts.
### Quick Start
```php ```php
use Mcp\Client; use Mcp\Client;
use Mcp\Client\Transport\StdioTransport; use Mcp\Client\Transport\StdioTransport;
// Build the client
$client = Client::builder() $client = Client::builder()
->setClientInfo('My Application', '1.0.0') ->setClientInfo('My Application', '1.0.0')
->setInitTimeout(30)
->setRequestTimeout(120)
->build(); ->build();
// Connect to a server $client->connect(new StdioTransport(command: 'php', args: ['/path/to/server.php']));
$transport = new StdioTransport(
command: 'php',
args: ['/path/to/server.php'],
);
$client->connect($transport);
// Discover and use capabilities
$tools = $client->listTools(); $tools = $client->listTools();
$result = $client->callTool('add', ['a' => 5, 'b' => 3]); $result = $client->callTool('add', ['a' => 5, 'b' => 3]);
$resources = $client->listResources();
$content = $client->readResource('config://calculator/settings');
$client->disconnect(); $client->disconnect();
``` ```
### Client Capabilities See [Connecting to a server](docs/client/connecting.md) for transports, timeouts, and the
handlers that answer server-initiated requests.
- **Tool Calling**: List and execute tools from any MCP server
- **Resource Access**: Read static and dynamic resources
- **Prompt Management**: List and retrieve prompt templates
- **Completion Support**: Request argument completion suggestions
- **Sampling & Elicitation**: Respond to server-initiated LLM sampling and user-input requests
### Advanced Features
- **Progress Tracking**: Real-time progress during long operations
```php
$result = $client->callTool(
name: 'process_data',
arguments: ['dataset' => 'large_file.csv'],
onProgress: function (float $progress, ?float $total, ?string $message) {
echo "Progress: {$progress}/{$total} - {$message}\n";
}
);
```
- **Sampling Support**: Handle server LLM sampling requests
```php
$samplingHandler = new SamplingRequestHandler($myCallback);
$client = Client::builder()
->setCapabilities(new ClientCapabilities(sampling: true))
->addRequestHandler($samplingHandler)
->build();
```
- **Elicitation Support**: Respond to server requests for user input
```php
$elicitationHandler = new ElicitationRequestHandler($myCallback);
$client = Client::builder()
->setCapabilities(new ClientCapabilities(elicitation: true))
->addRequestHandler($elicitationHandler)
->build();
```
- **Roots Support**: Expose `file://` workspace folders to the server
```php
$rootsHandler = new ListRootsRequestHandler($myCallback);
$client = Client::builder()
->setCapabilities(new ClientCapabilities(roots: true, rootsListChanged: true))
->addRequestHandler($rootsHandler)
->build();
```
- **Logging Notifications**: Receive server log messages
```php
$loggingHandler = new LoggingNotificationHandler($myCallback);
$client = Client::builder()
->addNotificationHandler($loggingHandler)
->build();
```
### Transports
Connect to MCP servers using the transport that matches your setup:
**1. STDIO Transport** — Connect to local server processes:
```php
$transport = new StdioTransport(
command: 'php',
args: ['/path/to/server.php'],
);
$client->connect($transport);
```
**2. HTTP Transport** — Connect to remote or web-based servers:
```php
$transport = new HttpTransport('http://localhost:8000');
$client->connect($transport);
```
[→ Client Documentation](docs/client.md)
## Documentation ## Documentation
### Core Concepts The full documentation is published at **[php.sdk.modelcontextprotocol.io](https://php.sdk.modelcontextprotocol.io/)**.
- **[Server Builder](docs/server-builder.md)** — Complete ServerBuilder reference and configuration - **[Get started](docs/get-started/index.md)** — Install the SDK and build your first server
- **[Client](docs/client.md)** — Client SDK for connecting to and communicating with MCP servers - **[Servers](docs/servers/index.md)** — Tools, resources, resource templates, prompts, and how to register them
- **[Transports](docs/transports.md)** — STDIO and HTTP transport setup and usage - **[Inside your handler](docs/handlers/index.md)** — Talking back to the client, logging, and asking for input
- **[MCP Elements](docs/mcp-elements.md)** — Creating tools, resources, prompts, and templates - **[Running your server](docs/run/index.md)** — Server builder, STDIO and HTTP transports, framework integration, sessions, authorization
- **[Server-Client Communication](docs/server-client-communication.md)** — Sampling, logging, progress, and notifications - **[Clients](docs/client/index.md)** — Client SDK for connecting to and communicating with MCP servers
- **[Protocol Extensions](docs/extensions.md)** — Opt-in protocol extensions announced during capability negotiation, including MCP Apps (HTML UI resources) - **[Protocol versions](docs/protocol-versions.md)** — The two protocol eras, and what revision `2026-07-28` changed
- **[Authorization](docs/authorization.md)** — OAuth and authorization setup for HTTP transport - **[Advanced](docs/advanced/index.md)** — Events, protocol extensions (including MCP Apps), and custom message handlers
- **[Events](docs/events.md)** — Hooking into server lifecycle with events - **[Examples](docs/examples.md)** — Runnable server and client examples
- **[API Reference](https://php.sdk.modelcontextprotocol.io/api/)** — Generated class reference
### Learning & Examples
- **[Examples](docs/examples.md)** — Comprehensive example walkthroughs for servers and clients
- **[ROADMAP.md](ROADMAP.md)** — Planned features and development roadmap
## External Resources ## External Resources
@ -324,9 +124,9 @@ Building something on top of the SDK? Open a pull request to add it to this list
## Contributing ## Contributing
We are passionate about supporting contributors of all levels of experience and would love to see you get involved in the project. We are passionate about supporting contributors of all levels of experience and would love to see you get involved in
the project. Start by [reporting issues](https://github.com/modelcontextprotocol/php-sdk/issues) or
See the [Contributing Guide](CONTRIBUTING.md) to get started before you [report issues](https://github.com/modelcontextprotocol/php-sdk/issues) and [send pull requests](https://github.com/modelcontextprotocol/php-sdk/pulls). [sending pull requests](https://github.com/modelcontextprotocol/php-sdk/pulls).
## Credits ## Credits

View file

@ -93,5 +93,5 @@ If you need an authorization server (token issuance, client registration, login,
validator seams. The MCP server validates the tokens it issues; it does not issue them validator seams. The MCP server validates the tokens it issues; it does not issue them
itself. itself.
See [`../docs/authorization.md`](../docs/authorization.md) for the supported Resource Server See [`../docs/run/authorization.md`](../docs/run/authorization.md) for the supported Resource Server
and delegation setup. and delegation setup.

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";
}
```

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