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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* [Docs] Document the elicitation and roots client examples

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

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

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

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

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

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

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

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

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

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

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

View file

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