Skip to content

Capabilities ​

Yii3 params

'rasuvaeff/yii3-mcp' => [...] snippets are Yii3 configuration. Elsewhere pass the same value as a constructor argument; see Getting started.

Every capability method is a public method on an ordinary service, annotated with one of the SDK's own attributes — this package invents no protocol structures on top of mcp/sdk.

Tools ​

php
use Mcp\Server\Capability\Attribute\McpTool;

final readonly class OrderTools
{
    public function __construct(private OrderRepository $orders) {}

    /** Returns the current status of an order. */
    #[McpTool(name: 'order.status')]
    public function status(string $orderId): string
    {
        return $this->orders->get($orderId)->status->value;
    }
}

The input schema is generated by the SDK from the method signature and DocBlock — no separate schema to keep in sync.

Structured output ​

Declare an outputSchema and return an array: the SDK serves the schema in tools/list and mirrors the return value into the result's structuredContent, alongside the human-readable text content.

php
/** @return array{status: string, total: int} */
#[McpTool(
    name: 'order.status',
    outputSchema: [
        'type' => 'object',
        'properties' => [
            'status' => ['type' => 'string'],
            'total' => ['type' => 'integer'],
        ],
        'required' => ['status', 'total'],
    ],
)]
public function status(string $orderId): array
{
    $order = $this->orders->get($orderId);

    return ['status' => $order->status->value, 'total' => $order->total];
}

An associative array (or an object encoding to a JSON object) produces structuredContent even without an outputSchema (a list does so only on the stateless 2026-07-28 revision) — declaring the schema is what lets the agent know the shape up front. Testing\SchemaSnapshot covers output schemas the same way it covers input schemas, so accidental drift fails the build (see Cookbook: your first MCP server).

Behavior hints ​

Use the SDK's ToolAnnotations directly — no package-specific attribute is needed:

php
use Mcp\Schema\ToolAnnotations;

#[McpTool(
    name: 'order.cancel',
    annotations: new ToolAnnotations(
        readOnlyHint: false,
        destructiveHint: true,
        idempotentHint: true,
        openWorldHint: false,
    ),
)]
public function cancel(string $orderId): string { /* … */ }
HintMeaning
readOnlyHinttrue when the tool does not modify its environment.
destructiveHintFor a mutating tool, distinguishes destructive changes from additive-only ones.
idempotentHintFor a mutating tool, says repeated calls with the same arguments add no further effect.
openWorldHinttrue when the tool may interact with external entities outside a closed domain.

Annotations are advisory metadata a client may ignore — never substitute them for authorization, validation, safe_methods_only (OpenAPI bridge), visibility, or server-side confirmation. idempotentHint alone does not license automatic retries — see Interceptors: retrying transient failures.

Server-initiated communication ​

An attribute tool may accept the SDK's request-scoped RequestContext as a parameter. The SDK creates it for the current MCP request and omits it from the generated input schema, so the client supplies only real domain arguments. Obtain its ClientGateway to send progress/log notifications or to initiate sampling and elicitation:

php
use Mcp\Schema\Elicitation\BooleanSchemaDefinition;
use Mcp\Schema\Elicitation\ElicitationSchema;
use Mcp\Server\RequestContext;

#[McpTool(
    name: 'release.deploy',
    annotations: new ToolAnnotations(
        readOnlyHint: false,
        destructiveHint: true,
        idempotentHint: false,
        openWorldHint: false,
    ),
)]
public function deploy(string $version, RequestContext $context): string
{
    $client = $context->getClientGateway();
    $client->progress(progress: 1, total: 2, message: 'Validation complete');

    if (!$client->supportsElicitation()) {
        throw new RuntimeException('Client does not support required deployment confirmation');
    }

    $confirmation = $client->elicit(
        message: sprintf('Deploy version %s?', $version),
        requestedSchema: new ElicitationSchema(
            properties: [
                'confirmed' => new BooleanSchemaDefinition(
                    title: 'Confirm deployment',
                    description: 'Allow this deployment to proceed',
                ),
            ],
            required: ['confirmed'],
        ),
    );

    if (!$confirmation->isAccepted() || ($confirmation->content['confirmed'] ?? false) !== true) {
        throw new RuntimeException('Deployment was not confirmed');
    }

    return sprintf('Deployment %s queued', $version);
}

progress() is a no-op when the caller did not provide a progress token. log() emits client-visible log notifications; sample() and elicit() are round trips that suspend the tool Fiber until the client responds or the SDK timeout expires. Check supportsElicitation() before requiring elicitation, choose a fail-closed fallback for destructive operations, and assume that not every MCP client supports every server-initiated capability. Keep RequestContext as a method parameter rather than a constructor dependency: it belongs to one request/session.

On the stateless 2026-07-28 era there is nobody to ask while the request is open, so an ask works differently — and the same handler serves both eras unchanged:

  • elicit()/elicitUrl() end the request with resultType: input_required; the client re-sends the call with the answer and the SDK runs the handler again from the top, where the ask now returns it. Anything a handler does before its last ask happens once per round — keep side effects after it.
  • More than one ask per call carries earlier answers between rounds in a signed requestState: set request_state.key (at least 32 bytes, from the environment). Without it the first ask works and a second fails the call.
  • The state is bound (request_state.bind, on by default) to the request it was minted for — method, tool, a digest of the arguments, the OAuth principal — and to the resolved client id: a state replayed by another client, or for other arguments, does not verify. States minted before the binding was switched on stop verifying once.
  • Rotation: move the old key to request_state.previous_keys when setting a new key — previous keys still verify a state but never sign one, so calls in flight survive the switch; drop the old key after ttl.
  • Every round is a tools/call: interceptors run each round and the tool-call budget counts each one (one ask costs two). The answers are not signed, so a budget skipping "retries" could be bypassed by any client.
  • The result cache never stores an ask or serves a later round.
  • sample()/listRoots() throw on 2026-07-28, which removed them (Sampling, Roots and Logging are deprecated by SEP-2577).
  • progress()/log() stream over SSE when the client accepts text/event-stream.
php
'rasuvaeff/yii3-mcp' => [
    'request_state' => [
        'key' => $_ENV['MCP_REQUEST_STATE_KEY'] ?? '',
        'ttl' => 600,
        'previous_keys' => [],   // old keys during a rotation
        'bind' => true,          // tie a state to its request and client
    ],
],

To gate a capability class (feature flag, environment check), implement ConditionalToolInterface — the instance is resolved through the container at build time and skipped when shouldRegister() returns false:

php
final readonly class BetaTools implements ConditionalToolInterface
{
    public function __construct(private FeatureFlags $flags) {}

    public function shouldRegister(): bool
    {
        return $this->flags->isEnabled('mcp-beta-tools');
    }

    #[McpTool(name: 'beta.op')]
    public function betaOp(): string { ... }
}

Conditional registration ​

php
final readonly class BetaTools implements ConditionalToolInterface
{
    public function __construct(private FeatureFlags $flags) {}

    public function shouldRegister(): bool
    {
        return $this->flags->isEnabled('mcp-beta-tools');
    }

    #[McpTool(name: 'beta.op')]
    public function betaOp(): string { /* … */ }
}

The instance is resolved through the container at build time; a false skips registration entirely — no tools/resources/prompts from that class reach tools/list.

Resources and resource templates ​

#[McpResource] (a fixed URI) and #[McpResourceTemplate] (an RFC 6570 template, e.g. app://reports/{region}) work the same way as tools — public methods on a DI-resolved service, returning resource contents.

Subscriptions ​

Subscribers are reached differently on the two protocol eras, and Resource\ResourceUpdateNotifier covers both from one call:

php
public function __construct(private ResourceUpdateNotifier $notifier) {}

#[McpTool(name: 'order.cancel')]
public function cancel(string $orderId, RequestContext $context): string
{
    $this->orders->cancel($orderId);
    $this->notifier->notify('app://orders/' . $orderId, $context);

    return 'cancelled';
}
EraSubscriptionWho is reached
stateless 2026-07-28a subscriptions/listen stream, fed from the notification busevery listener whose filter names the URI, from any process sharing the bus — $context is optional, so a queue worker or console command can notify too
handshakeresources/subscribe, recorded in the caller's sessiononly the calling session, from inside the request that changed the resource — no process holds the other sessions' connections
php
'rasuvaeff/yii3-mcp' => [
    'notifications' => [
        // '' = none (listen streams carry nothing), 'psr16' / 'psr6' =
        // through the container's PSR-16 cache / PSR-6 pool (PHP-FPM:
        // publisher and listener are different workers), 'memory' = one
        // process (stdio, persistent runtimes)
        'bus' => 'psr16',
        // seconds a listen stream is held open; under PHP-FPM it holds a worker
        // that long — keep it below max_execution_time
        'subscription_lifetime' => 30,
    ],
],

An unsolicited notification never reaches the wire: the session path checks the subscription first, and a listen stream carries only the URIs its own filter asked for. Bind a custom Mcp\Server\Resource\SubscriptionManagerInterface and both the subscribe handler and the notifier follow it; the bus is bound once, so McpServerFactory and the notifier always share it.

Argument autocompletion (completion/complete) ​

Declare the source with the SDK's #[CompletionProvider] — no package API is involved:

php
use Mcp\Server\Capability\Attribute\CompletionProvider;

#[McpPrompt(name: 'review')]
public function review(
    #[CompletionProvider(values: ['security', 'performance'])] string $focus,
    #[CompletionProvider(enum: Environment::class)] string $environment,
): string { /* … */ }

#[McpResourceTemplate(uriTemplate: 'app://reports/{region}', name: 'report')]
public function report(
    #[CompletionProvider(provider: RegionCompletionProvider::class)] string $region,
): string { /* … */ }
FormSource
values: [...]A fixed list, prefix-matched.
enum: BackedEnum::classThe enum's cases.
provider: Foo::classA Mcp\Server\Capability\Completion\ProviderInterface, resolved through the DI container — it may query a repository or a feature-flag service.

Exactly one of the three per argument. Completions obey prompt_visibility / resource_visibility — see Visibility: completions. Interceptors do not wrap completion/complete — it is a metadata lookup, not a capability call, so authorization for it belongs in the visibility filter, never in an interceptor.

Server-wide knobs ​

php
'rasuvaeff/yii3-mcp' => [
    'instructions' => 'Prefer order.status over reading app://orders/{id}.',
    'pagination_limit' => 50,
    'protocol_version' => '',
],

instructions is free-form "how to use this server" text served in the initialize result — the agent reads it before its first call. pagination_limit applies to every list method (tools/resources/templates/ prompts), both the SDK's own handlers and this package's filtering ones — so paging can never differ depending on whether visibility is configured. See Protocol for protocol_version.

Server configurators ​

Beyond the built-in OpenAPI bridge, register your own ServerConfiguratorInterface implementations (or a companion package's) to contribute capabilities to the SDK server builder before it is built. The core resolves the FQCNs through the container (after its own configurators) and applies them in order:

php
'rasuvaeff/yii3-mcp' => [
    'configurators' => [MyServerConfigurator::class],   // DI-resolved
],
php
final readonly class MyServerConfigurator implements ServerConfiguratorInterface
{
    #[\Override]
    public function configure(Builder $builder): void
    {
        // $builder->addTool(...) / addResource(...) / addPrompt(...) …
    }
}