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

View file

@ -0,0 +1,98 @@
# Completion Providers
Completion providers help MCP clients offer auto-completion suggestions for Resource Templates and Prompts. Unlike Tools and static Resources (which can be listed via `tools/list` and `resources/list`), Resource Templates and Prompts have dynamic parameters that benefit from completion hints.
## Completion Provider Types
### 1. Value Lists
Provide a static list of possible values:
```php
use Mcp\Capability\Attribute\CompletionProvider;
#[McpPrompt]
public function generateContent(
#[CompletionProvider(values: ['blog', 'article', 'tutorial', 'guide'])]
string $contentType,
#[CompletionProvider(values: ['beginner', 'intermediate', 'advanced'])]
string $difficulty
): array
{
return [
['role' => 'user', 'content' => "Create a {$difficulty} level {$contentType}"]
];
}
```
### 2. Enum Classes
Use enum values for completion:
```php
enum Priority: string
{
case LOW = 'low';
case MEDIUM = 'medium';
case HIGH = 'high';
}
enum Status // Unit enum
{
case DRAFT;
case PUBLISHED;
case ARCHIVED;
}
#[McpResourceTemplate(uriTemplate: 'tasks://{priority}/{status}')]
public function getTask(
#[CompletionProvider(enum: Priority::class)] // Uses backing values
string $priority,
#[CompletionProvider(enum: Status::class)] // Uses case names
string $status
): array
{
// Implementation
}
```
### 3. Custom Provider Classes
For dynamic completion logic:
```php
use Mcp\Capability\Completion\ProviderInterface;
class UserIdCompletionProvider implements ProviderInterface
{
public function __construct(private DatabaseService $db) {}
public function getCompletions(string $currentValue): array
{
// Return dynamic completions based on current input
return $this->db->searchUserIds($currentValue);
}
}
#[McpResourceTemplate(uriTemplate: 'user://{userId}/profile')]
public function getUserProfile(
#[CompletionProvider(provider: UserIdCompletionProvider::class)]
string $userId
): array
{
// Implementation
}
```
**Provider Resolution:**
- **Class strings** (`Provider::class`) → Resolved from PSR-11 container
- **Instances** (`new Provider()`) → Used directly
- **Values** (`['a', 'b']`) → Wrapped in `ListCompletionProvider`
- **Enums** (`MyEnum::class`) → Wrapped in `EnumCompletionProvider`
> **Important**
>
> Completion providers only offer **suggestions** to users. Users can still input any value, so **always validate
> parameters** in your handlers. Providers don't enforce validation - they're purely for UX improvement.

30
docs/servers/index.md Normal file
View file

@ -0,0 +1,30 @@
# Servers
An MCP server exposes four kinds of elements to a connected client. They differ by who
decides to use them:
* A **[tool](tools.md)** is an action the *model* picks and calls. This is the page most
people want first.
* A **[resource](resources.md)** is read-only data the *application* chooses to read,
addressed by a fixed URI. **[Resource templates](resource-templates.md)** are the same
thing with variables in the URI, for data that is generated per request.
* A **[prompt](prompts.md)** is a message template a *person* invokes by name, from a
menu or a slash command.
Around those, the rest of what a server declares:
* **[Completions](completions.md)** is server-side autocomplete for prompt and
resource-template arguments.
* **[Schema generation](schemas.md)** explains how your PHP types and docblocks become
the JSON Schema a model sees, and how to override it where the types are not enough.
* **[Registering elements](registration.md)** covers the three ways an element reaches
the registry: attribute discovery, explicit registration, or both at once.
Every page here stands on its own; jump straight to the one you need. If you have not
built a server yet, start with **[First server](../get-started/first-server.md)**
instead.
What happens *inside* the functions you register — logging, progress, asking the client
for an LLM completion — is the next section,
**[Inside your handler](../handlers/index.md)**. Getting the server in front of a client
is **[Running your server](../run/index.md)**.

126
docs/servers/prompts.md Normal file
View file

@ -0,0 +1,126 @@
# Prompts
Prompts generate templates for AI interactions.
```php
use Mcp\Capability\Attribute\McpPrompt;
class PromptGenerator
{
/**
* Generates a code review request prompt.
*/
#[McpPrompt(name: 'code_review')]
public function reviewCode(string $language, string $code, string $focus = 'general'): array
{
return [
['role' => 'assistant', 'content' => 'You are an expert code reviewer.'],
['role' => 'user', 'content' => "Review this {$language} code focusing on {$focus}:\n\n```{$language}\n{$code}\n```"]
];
}
}
```
## Parameters
- **`name`** (optional): Prompt identifier. Defaults to method name if not provided.
- **`title`** (optional): Human-readable display title shown in client UI. Distinct from `name`.
- **`description`** (optional): Prompt description. Falls back to the docblock (summary plus long description).
- **`icons`** (optional): Array of `Icon` objects for visual representation.
- **`meta`** (optional): Arbitrary key-value pairs for custom metadata.
## Prompt Return Values
Prompt handlers must return an array of message structures that are automatically formatted into MCP prompt messages.
### Supported Return Formats
```php
// Array of message objects with role and content
public function basicPrompt(): array
{
return [
['role' => 'assistant', 'content' => 'You are a helpful assistant'],
['role' => 'user', 'content' => 'Hello, how are you?']
];
}
// Single message (automatically wrapped in array)
public function singleMessage(): array
{
return [
['role' => 'user', 'content' => 'Write a poem about PHP']
];
}
// Associative array with user/assistant keys
public function userAssistantFormat(): array
{
return [
'user' => 'Explain how arrays work in PHP',
'assistant' => 'Arrays in PHP are ordered maps...'
];
}
// Non-text content — each message carries exactly one content block,
// so an image goes into its own message
use Mcp\Schema\Content\{TextContent, ImageContent};
public function mixedContent(): array
{
return [
['role' => 'user', 'content' => new TextContent('Analyze this image:')],
['role' => 'user', 'content' => new ImageContent(data: $imageData, mimeType: 'image/png')]
];
}
// Using explicit PromptMessage objects
use Mcp\Schema\Content\PromptMessage;
use Mcp\Schema\Enum\Role;
public function explicitMessages(): array
{
return [
new PromptMessage(Role::Assistant, new TextContent('System instructions')),
new PromptMessage(Role::User, new TextContent('User question'))
];
}
```
The SDK automatically validates that all messages have valid roles and converts the result into the appropriate MCP prompt message format.
### Valid Message Roles
- **`user`**: User input or questions
- **`assistant`**: Assistant responses, including system-style instructions
Those two are the only valid roles — MCP has no `system` role, and any other value
makes the prompt handler throw.
### Error Handling
Prompt handlers can throw any exception, but the type determines how it's handled:
- **`PromptGetException`**: Converted to JSON-RPC error response with the actual exception message
- **Any other exception**: Converted to JSON-RPC error response, but with a generic error message
```php
use Mcp\Exception\PromptGetException;
#[McpPrompt]
public function generatePrompt(string $topic, string $style): array
{
$validStyles = ['casual', 'formal', 'technical'];
if (!in_array($style, $validStyles)) {
throw new PromptGetException(
"Invalid style '{$style}'. Must be one of: " . implode(', ', $validStyles)
);
}
return [
['role' => 'user', 'content' => "Write about {$topic} in a {$style} style"]
];
}
```
**Recommendation**: Use `PromptGetException` when you want to communicate specific errors to clients. Any other exception will still be converted to JSON-RPC compliant errors but with generic error messages.

View file

@ -0,0 +1,247 @@
# Registering elements
Every tool, resource, resource template, and prompt has to reach the server's
registry somehow. There are three ways to get it there, and they mix freely.
## Attribute-Based Discovery
**Advantages:**
- Declarative and readable
- Automatic parameter inference
- DocBlock integration
- Type-safe by default
- Caching support
**Example:**
```php
$server = Server::builder()
->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor']) // Automatic discovery
->build();
```
## Manual Registration
Register MCP elements programmatically without using attributes. The handler is the most important parameter and can be
any PHP callable.
**Advantages:**
- Fine-grained control
- Runtime configuration
- Conditional registration
- External handler support
**Example:**
```php
$server = Server::builder()
->addTool([Calculator::class, 'add'], 'add_numbers')
->addResource([Config::class, 'get'], 'config://app')
->addPrompt([Prompts::class, 'email'], 'write_email')
->build();
```
### Handler Types
**Handler** can be any PHP callable:
1. **Closure**: `function(int $a, int $b): int { return $a + $b; }`
2. **Class and method name pair**: `[ClassName::class, 'methodName']` - the class is instantiated lazily on first call, so it must be constructable through the container (or have a no-arg constructor)
3. **Class instance and method name**: `[$instance, 'methodName']` - the given, already-constructed object is invoked as-is. Use this for handlers the container cannot build, e.g. those with scalar constructor arguments or dependencies wired at runtime
4. **Invokable class name**: `InvokableClass::class` - class must be constructable through the container and have `__invoke` method
### Manual Tool Registration
```php
$server = Server::builder()
// Using closure
->addTool(
handler: function(int $a, int $b): int { return $a + $b; },
name: 'add_numbers',
description: 'Adds two numbers together'
)
// Using class method pair
->addTool(
handler: [Calculator::class, 'multiply'],
name: 'multiply_numbers'
// name and description are optional - derived from method name and docblock
)
// Using instance method
->addTool(
handler: [$calculatorInstance, 'divide']
)
// Using invokable class
->addTool(
handler: InvokableCalculator::class
);
```
#### Parameters
- `handler` (callable|string): The tool handler
- `name` (string|null): Optional tool name
- `title` (string|null): Optional human-readable title for display in UI
- `description` (string|null): Optional tool description
- `annotations` (ToolAnnotations|null): Optional annotations for the tool
- `inputSchema` (array|null): Optional input schema for the tool
- `icons` (Icon[]|null): Optional array of icons for the tool
- `meta` (array|null): Optional metadata for the tool
- `outputSchema` (array|null): Optional JSON schema describing the tool's `structuredContent`
### Manual Resource Registration
Register static resources:
```php
$server = Server::builder()
->addResource(
handler: [Config::class, 'getSettings'],
uri: 'config://app/settings',
name: 'app_config',
description: 'Application configuration',
mimeType: 'application/json'
);
```
#### Parameters
- `handler` (callable|string): The resource handler
- `uri` (string): The resource URI
- `name` (string|null): Optional resource name
- `title` (string|null): Optional human-readable title for display in UI
- `description` (string|null): Optional resource description
- `mimeType` (string|null): Optional MIME type of the resource
- `size` (int|null): Optional size of the resource in bytes
- `annotations` (Annotations|null): Optional annotations for the resource
- `icons` (Icon[]|null): Optional array of icons for the resource
- `meta` (array|null): Optional metadata for the resource
### Manual Resource Template Registration
Register dynamic resources with URI templates:
```php
$server = Server::builder()
->addResourceTemplate(
handler: [UserService::class, 'getUserProfile'],
uriTemplate: 'user://{userId}/profile',
name: 'user_profile',
description: 'User profile by ID',
mimeType: 'application/json'
);
```
#### Parameters
- `handler` (callable|string): The resource template handler
- `uriTemplate` (string): The resource URI template
- `name` (string|null): Optional resource template name
- `title` (string|null): Optional human-readable title for display in UI
- `description` (string|null): Optional resource template description
- `mimeType` (string|null): Optional MIME type of the resource
- `annotations` (Annotations|null): Optional annotations for the resource template
- `meta` (array|null): Optional metadata for the resource template
### Manual Prompt Registration
Register prompt generators:
```php
$server = Server::builder()
->addPrompt(
handler: [PromptService::class, 'generatePrompt'],
name: 'custom_prompt',
description: 'A custom prompt generator'
);
```
#### Parameters
- `handler` (callable|string): The prompt handler
- `name` (string|null): Optional prompt name
- `title` (string|null): Optional human-readable title for display in UI
- `description` (string|null): Optional prompt description
- `icons` (Icon[]|null): Optional array of icons for the prompt
- `meta` (array|null): Optional metadata for the prompt
**Note:** `name` and `description` are optional when the handler is a method or an invokable class — they are then
derived from the method name and its docblock. A **closure** handler has neither, so it gets a generated name
(`closure_tool_<id>`) and no description; name your closures explicitly.
For more details on the elements themselves, see [Tools](tools.md), [Resources](resources.md), [Resource templates](resource-templates.md), and [Prompts](prompts.md).
### Explicit element registration
When an element's name, schema, or description is only known at runtime, pair an `Mcp\Schema\*` value object with one of
the four handler interfaces below and register it through `Builder::add()`.
| Element kind | Handler interface |
|-------------------|-------------------------------------------------------|
| Tool | `Mcp\Server\Handler\ToolHandlerInterface` |
| Resource | `Mcp\Server\Handler\ResourceHandlerInterface` |
| Resource template | `Mcp\Server\Handler\ResourceTemplateHandlerInterface` |
| Prompt | `Mcp\Server\Handler\PromptHandlerInterface` |
Each handler interface declares a single execution method. Tool and prompt handlers receive an arguments map and a
`ClientGateway`. Resource handlers receive the requested URI; resource template handlers additionally receive the parsed
template variables.
```php
use Mcp\Schema\Tool;
use Mcp\Server;
use Mcp\Server\ClientGateway;
use Mcp\Server\Handler\ToolHandlerInterface;
final class WeatherHandler implements ToolHandlerInterface
{
public function execute(array $arguments, ClientGateway $gateway): mixed
{
return ['temperature' => 21, 'unit' => 'C'];
}
}
$tool = new Tool(
name: 'get_weather',
title: null,
inputSchema: [
'type' => 'object',
'properties' => ['city' => ['type' => 'string']],
'required' => ['city'],
],
description: 'Returns the current weather for a city.',
annotations: null,
);
$server = Server::builder()
->add($tool, new WeatherHandler())
->build();
```
`Builder::add()` validates the pairing at registration time. Pairing a `Tool` definition with, for example, a
`PromptHandlerInterface` raises `Mcp\Exception\InvalidArgumentException`. The schema value objects validate some of
their own input as well — `Tool` requires an object-typed input schema, `ResourceDefinition` and `ResourceTemplate`
check the name pattern and URI — but an invalid tool or prompt *name* is not rejected, it is only logged as a warning
when the element is registered.
Use `add()` when the metadata cannot be inferred from a handler class via reflection. For statically-known elements,
prefer `addTool/addResource/addResourceTemplate/addPrompt`, which can derive metadata from the handler's signature and
docblock.
## Hybrid Approach
Combine both methods for maximum flexibility:
```php
$server = Server::builder()
->setDiscovery(__DIR__, ['.'], excludeDirs: ['vendor']) // Discover most capabilities
->addTool([ExternalService::class, 'process'], 'external') // Add specific ones
->build();
```
Manual registrations always take precedence over discovered elements with the same identifier — same `name` for tools
and prompts, same `uri` for resources, same `uriTemplate` for resource templates.
For runtime, config-driven elements whose shape is not known at compile time, see
[Explicit element registration](#explicit-element-registration).

View file

@ -0,0 +1,49 @@
# Resource Templates
Resource templates are **dynamic resources** that use parameterized URIs with variables. They follow all the same rules
as static resources (URI schemas, return values, MIME types, etc.) but accept `{variable}` placeholders in the URI.
Only simple [RFC 6570](https://datatracker.ietf.org/doc/html/rfc6570) variable expansion
is supported — `{var}`, one path segment each. Operators such as `{+var}`, `{#var}`,
`{/path}`, `{?query}` and explode (`{list*}`) are not parsed, and a variable's value
cannot contain `/`.
```php
use Mcp\Capability\Attribute\McpResourceTemplate;
class UserProvider
{
/**
* Retrieves user profile information by ID.
*/
#[McpResourceTemplate(
uriTemplate: 'user://{userId}/profile/{section}',
name: 'user_profile',
description: 'User profile data by section',
mimeType: 'application/json'
)]
public function getUserProfile(string $userId, string $section): array
{
return $this->users[$userId][$section] ?? throw new \InvalidArgumentException("Profile section not found");
}
}
```
## Parameters
- **`uriTemplate`** (required): URI with `{variables}`. Must start with a scheme (`file://`, `user://`, …) and contain at least one variable.
- **`name`** (optional): Short resource template identifier. Defaults to method name if not provided.
- **`title`** (optional): Human-readable display title shown in client UI. Distinct from `name`.
- **`description`** (optional): Template description. Falls back to the docblock (summary plus long description).
- **`mimeType`** (optional): MIME type of the resource content.
- **`annotations`** (optional): Additional metadata.
- **`meta`** (optional): Arbitrary key-value pairs for custom metadata.
## Variable Rules
1. **Variable names must match exactly** between URI template and method parameters —
they are bound by name, so the parameter order is free
2. **All variables are required** - no optional parameters supported
3. **Type hints work normally** - parameters can be typed (string, int, etc.)
**Example mapping**: `user://123/profile/settings` → `getUserProfile("123", "settings")`

152
docs/servers/resources.md Normal file
View file

@ -0,0 +1,152 @@
# Resources
Resources provide access to static data that clients can read.
```php
use Mcp\Capability\Attribute\McpResource;
class ConfigProvider
{
/**
* Provides the current application configuration.
*/
#[McpResource(uri: 'config://app/settings', name: 'app_settings')]
public function getSettings(): array
{
return [
'version' => '1.0.0',
'debug' => false,
'features' => ['auth', 'logging']
];
}
}
```
## Parameters
- **`uri`** (required): Unique resource identifier. Must comply with [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986).
- **`name`** (optional): Short resource identifier. Defaults to method name if not provided.
- **`title`** (optional): Human-readable display title shown in client UI. Distinct from `name`.
- **`description`** (optional): Resource description. Falls back to the docblock (summary plus long description).
- **`mimeType`** (optional): MIME type of the resource content.
- **`size`** (optional): Size in bytes if known.
- **`annotations`** (optional): Additional metadata.
- **`icons`** (optional): Array of `Icon` objects for visual representation.
- **`meta`** (optional): Arbitrary key-value pairs for custom metadata.
**Standard Protocol URI Schemes**: `https://` (web resources), `file://` (filesystem), `git://` (version control).
**Custom schemes**: `config://`, `data://`, `db://`, `api://` or any RFC 3986 compliant scheme.
## Resource Return Values
Resource handlers can return various data types that are automatically formatted into appropriate MCP resource content types.
### Supported Return Types
```php
// String content - converted to text resource
public function getTextFile(): string
{
return "File content here";
}
// Array content - converted to JSON
public function getConfig(): array
{
return ['debug' => true, 'version' => '1.0'];
}
// Stream resource - read and converted to blob.
// `resource` is not a PHP type declaration, so the return type is left off.
/** @return resource */
public function getImageStream()
{
return fopen('image.png', 'r');
}
// SplFileInfo - file content with MIME type detection
public function getFileInfo(): \SplFileInfo
{
return new \SplFileInfo('document.pdf');
}
```
**Explicit resource content types**
```php
use Mcp\Schema\Content\{TextResourceContents, BlobResourceContents};
public function getExplicitText(): TextResourceContents
{
return new TextResourceContents(
uri: 'config://app/settings',
mimeType: 'application/json',
text: json_encode(['setting' => 'value'])
);
}
public function getExplicitBlob(): BlobResourceContents
{
return new BlobResourceContents(
uri: 'file://image.png',
mimeType: 'image/png',
blob: base64_encode(file_get_contents('image.png'))
);
}
```
**Special Array Formats**
```php
// Array with 'text' key - used as text content
public function getTextArray(): array
{
return ['text' => 'Content here', 'mimeType' => 'text/plain'];
}
// Array with 'blob' key - used as blob content
public function getBlobArray(): array
{
return ['blob' => base64_encode($data), 'mimeType' => 'image/png'];
}
// Multiple resource contents
public function getMultipleResources(): array
{
return [
new TextResourceContents('file://readme.txt', 'text/plain', 'README content'),
new TextResourceContents('file://config.json', 'application/json', '{"key": "value"}')
];
}
```
### Error Handling
Resource handlers can throw any exception, but the type determines how it's handled:
- **`ResourceReadException`**: Converted to JSON-RPC error response with the actual exception message
- **Any other exception**: Converted to JSON-RPC error response, but with a generic error message
```php
use Mcp\Capability\Attribute\McpResourceTemplate;
use Mcp\Exception\ResourceReadException;
// A URI with variables is a resource *template*; `#[McpResource]` registers a
// fixed URI and would never receive `$path`. Note a variable matches a single
// segment, so `$path` here cannot contain `/`.
#[McpResourceTemplate(uriTemplate: 'file://{path}')]
public function getFile(string $path): string
{
if (!file_exists($path)) {
throw new ResourceReadException("File not found: {$path}");
}
if (!is_readable($path)) {
throw new ResourceReadException("File not readable: {$path}");
}
return file_get_contents($path);
}
```
**Recommendation**: Use `ResourceReadException` when you want to communicate specific errors to clients. Any other exception will still be converted to JSON-RPC compliant errors but with generic error messages.

111
docs/servers/schemas.md Normal file
View file

@ -0,0 +1,111 @@
# Schema Generation and Validation
The SDK automatically generates JSON schemas for **tool parameters** using a sophisticated priority system. Schema
generation applies to both attribute-discovered and manually registered tools.
## Schema Generation Priority
The server follows this order of precedence:
1. **`#[Schema]` attribute with `definition`** - Complete schema override (highest priority)
2. **Parameter-level `#[Schema]` attribute** - Parameter-specific enhancements
3. **Method-level `#[Schema]` attribute** - Method-wide configuration
4. **PHP type hints + docblocks** - Automatic inference (lowest priority)
## Automatic Schema from PHP Types
```php
#[McpTool]
public function processUser(
string $email, // Required string
int $age, // Required integer
?string $name = null, // Optional string
bool $active = true // Boolean with default
): array
{
// Schema auto-generated from method signature
}
```
## Parameter-Level Schema Enhancement
Add validation rules to specific parameters:
```php
use Mcp\Capability\Attribute\Schema;
#[McpTool]
public function validateUser(
#[Schema(format: 'email')]
string $email,
#[Schema(minimum: 18, maximum: 120)]
int $age,
#[Schema(
pattern: '^[A-Z][a-z]+$',
description: 'Capitalized first name'
)]
string $firstName
): bool
{
// PHP types provide base validation
// Schema attributes add constraints
}
```
## Method-Level Schema
Add validation for complex object structures:
```php
#[McpTool]
#[Schema(
properties: [
'userData' => [
'type' => 'object',
'properties' => [
'name' => ['type' => 'string', 'minLength' => 2],
'email' => ['type' => 'string', 'format' => 'email'],
'age' => ['type' => 'integer', 'minimum' => 18]
],
'required' => ['name', 'email']
]
],
required: ['userData']
)]
public function createUser(array $userData): array
{
// Method-level schema adds object structure validation
// PHP array type provides base type
}
```
## Complete Schema Override
**Use sparingly** - bypasses all automatic inference:
```php
#[McpTool]
#[Schema(definition: [
'type' => 'object',
'properties' => [
'endpoint' => ['type' => 'string', 'format' => 'uri'],
'method' => ['type' => 'string', 'enum' => ['GET', 'POST', 'PUT', 'DELETE']],
'headers' => [
'type' => 'object',
'patternProperties' => [
'^[A-Za-z0-9-]+$' => ['type' => 'string']
]
]
],
'required' => ['endpoint', 'method']
])]
public function makeApiRequest(string $endpoint, string $method, array $headers): array
{
// Complete definition override - PHP types ignored
}
```
**Warning:** Only use complete schema override if you're well-versed with JSON Schema specification and have complex
validation requirements that cannot be achieved through the priority system.

236
docs/servers/tools.md Normal file
View file

@ -0,0 +1,236 @@
# Tools
Tools are callable functions that perform actions and return results.
```php
use Mcp\Capability\Attribute\McpTool;
class Calculator
{
/**
* Performs arithmetic operations with validation.
*/
#[McpTool(name: 'calculate')]
public function performCalculation(float $a, float $b, string $operation): float
{
return match($operation) {
'add' => $a + $b,
'subtract' => $a - $b,
'multiply' => $a * $b,
'divide' => $b != 0 ? $a / $b : throw new \InvalidArgumentException('Division by zero'),
default => throw new \InvalidArgumentException('Invalid operation')
};
}
}
```
## Parameters
- **`name`** (optional): Tool identifier. Defaults to method name if not provided.
- **`title`** (optional): Human-readable display title shown in client UI. Distinct from `name`.
- **`description`** (optional): Tool description. Falls back to the docblock (summary plus long description); stays unset if there is no docblock.
- **`annotations`** (optional): `ToolAnnotations` object for additional metadata.
- **`outputSchema`** (optional): JSON schema describing `structuredContent`; see [Structured Output](#structured-output).
- **`icons`** (optional): Array of `Icon` objects for visual representation.
- **`meta`** (optional): Arbitrary key-value pairs for custom metadata.
**Priority**: `name` is the attribute parameter, else the method name. `description` is the attribute parameter, else the docblock — the method name is never used as a description.
For tool parameter validation and JSON schema generation, see [Schema generation](schemas.md).
## Tool Return Values
Tools can return any data type and the SDK will automatically wrap them in appropriate MCP content types.
### Automatic Content Wrapping
```php
// Primitive types → TextContent
public function getString(): string { return "Hello"; } // TextContent
public function getNumber(): int { return 42; } // TextContent
public function getBool(): bool { return true; } // TextContent
public function getArray(): array { return ['key' => 'value']; } // TextContent (JSON)
// Special cases
public function getNull(): ?string { return null; } // TextContent("(null)")
public function returnVoid(): void { /* no return */ } // TextContent("(null)")
```
### Explicit Content Types
For fine control over output formatting:
```php
use Mcp\Schema\Content\{TextContent, ImageContent, AudioContent, ResourceLink, EmbeddedResource};
public function getFormattedCode(): TextContent
{
return TextContent::code('<?php echo "Hello";', 'php');
}
public function getMarkdown(): TextContent
{
return new TextContent('# Title\n\nMarkdown content');
}
public function getImage(): ImageContent
{
return new ImageContent(
data: base64_encode(file_get_contents('image.png')),
mimeType: 'image/png'
);
}
public function getAudio(): AudioContent
{
return new AudioContent(
data: base64_encode(file_get_contents('audio.mp3')),
mimeType: 'audio/mpeg'
);
}
public function getEmbeddedResource(): EmbeddedResource
{
return EmbeddedResource::fromText('file://data.json', 'File content');
// …or build the resource contents yourself:
// return new EmbeddedResource(
// new TextResourceContents('file://data.json', 'application/json', '{}')
// );
}
public function getResourceLink(): ResourceLink
{
// Reference a resource by URI without embedding its contents, e.g. when
// a tool result would otherwise need to inline many or large resources.
return new ResourceLink(
uri: 'file://data.json',
name: 'data.json',
mimeType: 'application/json'
);
}
```
### Multiple Content Items
Return an array of content items:
```php
public function getMultipleContent(): array
{
return [
new TextContent('Here is the analysis:'),
TextContent::code($code, 'php'),
new TextContent('And here is the summary.')
];
}
```
### Structured Output
Besides the human-readable `content`, a tool result can carry a machine-readable `structuredContent` value. Declare its
shape with `outputSchema`, a JSON Schema of type `object`:
```php
#[McpTool(
name: 'get_weather',
outputSchema: [
'type' => 'object',
'properties' => [
'temperature' => ['type' => 'number'],
'conditions' => ['type' => 'string'],
],
'required' => ['temperature', 'conditions'],
]
)]
public function getWeather(string $city): array
{
// Sent as `structuredContent`, and JSON-encoded into `content` for clients that ignore it
return ['temperature' => 22.5, 'conditions' => 'sunny'];
}
```
The same schema can be passed to manual registration:
```php
$builder->addTool([WeatherHandler::class, 'getWeather'], outputSchema: [/* ... */]);
```
The SDK fills `structuredContent` whenever the return value qualifies — `outputSchema` is what tells clients to expect it
and lets them validate it. What qualifies depends on the protocol revision the call is served under:
| Return value | `structuredContent` |
|---|---|
| Associative array (`['temperature' => 22.5]`) | The array |
| Object (`stdClass`, DTO, `JsonSerializable`) that serializes to a JSON object | Its JSON representation |
| List (`[1, 2, 3]`, `[['id' => 1], ['id' => 2]]`), or an object serializing to one | Omitted before `2026-07-28`, kept from it on |
| Array holding `Content` instances | Omitted (already carried in `content`) |
| Scalars, `null`, `Content` instances | Omitted |
Up to revision `2025-11-25`, `structuredContent` had to be a JSON object, so a PHP list — which serializes to a JSON
array — was not emittable and strict clients rejected the whole tool call over one. [SEP-2106][sep-2106], part of
revision `2026-07-28`, widened `outputSchema` to any JSON Schema 2020-12 and `structuredContent` to any JSON value
conforming to it. The SDK picks the rule from the revision negotiated for the call, so a tool serving both eras needs the
object shape to produce structured output everywhere. Wrap the list in a key for that:
```php
// Structured content only from 2026-07-28 on: a bare list is not a JSON object
public function listUsersFlat(): array
{
return [['id' => 1], ['id' => 2]];
}
#[McpTool(outputSchema: [
'type' => 'object',
'properties' => [
'items' => ['type' => 'array', 'items' => ['type' => 'object']],
],
'required' => ['items']
])]
public function listUsers(): array
{
return ['items' => [['id' => 1], ['id' => 2]]];
}
```
Either way the data reaches the client: a return value with no structured representation is still JSON-encoded into
`content` as a `TextContent`. When a tool declares an `outputSchema` but returns something that cannot be sent as
`structuredContent`, the SDK logs a warning — the value is not silently dropped.
A tool that wants to branch on the revision itself can read it from the injected `RequestContext`, see
[Talking back to the client](../handlers/client-communication.md#clientgateway).
[sep-2106]: https://modelcontextprotocol.io/specification/2026-07-28/server/tools#structured-content
### Error Handling
Tool handlers can throw any exception, but the type determines how it's handled:
- **`ToolCallException`**: Converted to JSON-RPC response with `CallToolResult` where `isError: true`, allowing the LLM to see the error message and self-correct
- **Any other exception**: Converted to JSON-RPC error response, but with a generic error message
```php
use Mcp\Exception\ToolCallException;
#[McpTool]
public function divideNumbers(float $a, float $b): float
{
if ($b === 0.0) {
throw new ToolCallException('Division by zero is not allowed');
}
return $a / $b;
}
#[McpTool]
public function processFile(string $filename): string
{
if (!file_exists($filename)) {
throw new ToolCallException("File not found: {$filename}");
}
return file_get_contents($filename);
}
```
**Recommendation**: Use `ToolCallException` when you want to communicate specific errors to clients. Any other exception will still be converted to JSON-RPC compliant errors but with generic error messages.