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