Drivers
MCP Driver
Serve Model Context Protocol tools, resources and prompts from a Kipchak API, so that an AI assistant can use its operations. Built on the official PHP SDK, safe in worker mode.
Introduction
The MCP driver lets a Kipchak API serve Model Context Protocol tools, resources and prompts, so that an AI assistant can use the API's operations. It is built on the official PHP SDK, mcp/sdk.
- Attributes on ordinary classes. Mark a public method with
#[McpTool],#[McpResource],#[McpResourceTemplate]or#[McpPrompt]. Input schemas come from the parameter types and descriptions from the doc block. - Services from the Kipchak container. Tool classes are built by the container, so a constructor can ask for an entity manager, a cache or any other service.
- Both protocol eras on one endpoint. Clients on the handshake revisions, up to 2025-11-25, and on 2026-07-28, which needs no session, are served by the same route.
- No sessions by default. Each request stands alone, so the API needs no shared store however many copies of it run.
- Authentication stays where it is. The endpoint sits behind your route's authentication middleware, and the driver passes the caller's identity to the SDK.
- Worker mode. The server is built once per FrankenPHP worker, and each request runs with a transport of its own, so nothing about one caller reaches the next request.
- Checked at boot. A configuration error stops the API when it starts, with a message naming the server and the setting.
Installation
composer require kipchak/driver-mcp
Or, with the CLI, kipchak add mcp, which also copies the configuration and initialises the driver. The driver needs kipchak/cli 1.6 or later in a project that has the CLI installed, and Composer says so if an older CLI is present.
The SDK requires php-http/discovery, which is a Composer plugin. Kipchak already provides the PSR-17 factories the SDK needs, from slim/psr7, and the driver passes them to the SDK, so the plugin has nothing to install. Allow it explicitly, so that a non-interactive install neither stops to ask nor installs packages you did not choose:
"config": {
"allow-plugins": {
"php-http/discovery": false
}
}
Initialise the driver in drivers/drivers.php, after the Config and Logger drivers, and after any cache driver whose cache keeps the sessions:
\Kipchak\Driver\Mcp\Mcp::initialise($container);
Copy sample.config.php from the package to config/kipchak.mcp.php.
A first tool
<?php
namespace Api\Mcp;
use Mcp\Schema\ToolAnnotations;
use Mcp\Server\Capability\Attribute\McpTool;
final class StatusTools
{
/**
* Reports whether the API is running.
*/
#[McpTool(name: 'status', annotations: new ToolAnnotations(readOnlyHint: true))]
public function status(): array
{
return ['status' => 'alive'];
}
}
List the class under 'tools' in config/kipchak.mcp.php, and route the endpoint in a file under routes/:
$app->any('/mcp', \Kipchak\Driver\Mcp\Mcp::endpoint('default'));
Route every method with any, not only POST: the endpoint answers POST, DELETE and OPTIONS itself and refuses the others.
The starter project ships this route without sign-in, like /status, because its one tool only reports that the API is running. Any tool that reads or changes data must sit behind authentication, as the next section shows.
Behind authentication
Put the route behind your authentication middleware, and tell the driver which request attribute that middleware sets. The driver then binds each session, and each signed request state, to the caller.
This is the route behind kipchak/middleware-auth-jwks:
<?php
/**
* routes/mcp.php: the MCP endpoint behind kipchak/middleware-auth-jwks. Every request needs a valid access token
* carrying the mcp scope, and each session belongs to the token's issuer and subject.
*
* In config/kipchak.mcp.php, set:
*
* 'principal_attribute' => \Kipchak\Middleware\Auth\JWKS\Handlers\AuthJWKS::ATTRIBUTE_TOKEN,
* 'principal_claim' => 'sub',
*
* @var \Kipchak\Core\Components\App $app
*/
use Kipchak\Driver\Mcp\Mcp;
use Kipchak\Middleware\Auth\JWKS\Handlers\AuthJWKS;
$app->any('/mcp', Mcp::endpoint('default'))
->add(new AuthJWKS($app->getContainer(), ['mcp']));
How the caller is identified:
- When the attribute holds a verified token, as auth-jwks and auth-jwt set it, the caller is the token's issuer and the claim named by
principal_claim,subby default. A subject is unique only within its issuer, so the samesubfrom two issuers is two callers. - When the attribute holds a plain string, that string is the caller. It is then only as unique as that string is within your deployment, so prefer a token where several identity providers are in use.
- A request without a caller cannot use a session.
- The SDK sees the caller's issuer, client and subject, and nothing else from the token. A tool that reads the caller with
RequestContext::getAccessToken()sees only those three claims.
Tool dispatcher
Authentication decides who the caller is. When different tools need different callers, for example a public tool beside tools that read one customer's data, put that decision in one place: a tool dispatcher. Name a class implementing Kipchak\Driver\Mcp\ToolDispatcher in tool_dispatcher. The Kipchak container builds it. The setting is available from version 1.1.
accept(ToolDefinition $tool)is called for every tool when the API starts, including tools found by discovery. It reads the attributes on$tool->function. If it throws, the API does not start, so a tool the dispatcher cannot govern is never served.dispatch(ToolCall $call, \Closure $next)runs every tool call.$call->calleris the caller's issuer, client and subject, ornullfor an anonymous call;$call->argumentsare the caller's arguments. Call$next()to run the tool, or$next($grant)to hand the tool what you authorised. The tool runs at most once.- To refuse a call with a message, throw
Mcp\Server\Exception\ToolCallException. The assistant receives the message as a tool error and the tool does not run. Any other exception closes the call with a generic error and no data, so a fault in the dispatcher never lets a call through. - A tool reads the grant with
Grant::from($context), declaring aRequestContext $contextparameter. The SDK supplies that parameter and keeps it out of the tool's input schema. The grant exists only while the tool runs, and a caller cannot set it.
Resources and prompts do not pass through the dispatcher.
This dispatcher requires each tool to declare who may call it:
<?php
/**
* api/Mcp/Dispatcher.php: every tool declares #[SignIn] or #[Anyone], and this dispatcher enforces it. A tool with
* neither stops the API at boot. Name the class in config/kipchak.mcp.php:
*
* 'tool_dispatcher' => \Api\Mcp\Dispatcher::class,
*/
namespace Api\Mcp;
use Kipchak\Driver\Mcp\ToolCall;
use Kipchak\Driver\Mcp\ToolDefinition;
use Kipchak\Driver\Mcp\ToolDispatcher;
use Mcp\Server\Exception\ToolCallException;
#[\Attribute(\Attribute::TARGET_METHOD)]
final class Anyone
{
}
#[\Attribute(\Attribute::TARGET_METHOD)]
final class SignIn
{
}
final class Dispatcher implements ToolDispatcher
{
public function accept(ToolDefinition $tool): void
{
if (self::needsSignIn($tool) === null) {
throw new \LogicException("MCP tool '{$tool->name}' declares neither #[SignIn] nor #[Anyone].");
}
}
public function dispatch(ToolCall $call, \Closure $next): mixed
{
if (self::needsSignIn($call->tool) && $call->caller === null) {
throw new ToolCallException('Sign in to use this tool.');
}
// The tool reads this with Grant::from($context).
return $next(['subject' => $call->caller['sub'] ?? null]);
}
private static function needsSignIn(ToolDefinition $tool): ?bool
{
$signIn = $tool->function?->getAttributes(SignIn::class) ?? [];
$anyone = $tool->function?->getAttributes(Anyone::class) ?? [];
return match (true) {
$signIn !== [] && $anyone === [] => true,
$anyone !== [] && $signIn === [] => false,
default => null,
};
}
}
A tool then declares it beside its MCP attribute:
#[McpTool(name: 'my_account')]
#[SignIn]
public function myAccount(RequestContext $context): string
{
return 'account of ' . Grant::from($context)['subject'];
}
Configuration
| Setting | Default | What it does |
|---|---|---|
name, version | How the server introduces itself to the assistant. Required. | |
instructions | null | Optional text for the assistant. |
tools | [] | Classes whose public methods carry MCP attributes. Built by the Kipchak container. |
discovery | [] | Directories, relative to the project root, to scan for those attributes. |
allowed_hosts | MCP_HOST, or localhost | Host names clients use, without the port. Other hosts are refused with 403. |
allowed_origins | [] | Origins of browser-based clients. Clients outside a browser need nothing here. |
sessions | null | null for no sessions, or the container key of a PSR-16 cache, such as drivers.cache.valkey.cache. |
session_ttl | 3600 | Seconds a session lives. |
principal_attribute | null | The request attribute your authentication middleware sets. Required when sessions is set. |
principal_claim | sub | The claim that identifies the caller when that attribute is a token. |
tool_dispatcher | null | A class implementing ToolDispatcher that decides every tool call. See Tool dispatcher above. Version 1.1 and later. |
max_body_bytes | 4194304 | The largest request body accepted. Larger bodies are refused with 413. |
request_state | no keys | Signing keys and lifetime for tools that ask the user for input. See below. |
A server that lists no tools and no discovery directories boots, and logs a warning on its first request that it offers an assistant nothing.
Sessions and protocol versions
Sessions are off unless sessions is set. Without them, every request stands alone: an API with several replicas needs no shared store, and the 2026-07-28 revision never needs one.
Clients on the handshake revisions, up to 2025-11-25, may keep a session, which some of their features need, such as asking the user for input. To keep sessions, name a PSR-16 cache from another Kipchak driver, and set principal_attribute as well: the driver refuses to boot with sessions that no caller owns.
Signed request state
On the 2026-07-28 revision, a tool that asks the user for input in the middle of a call, by elicitation, sampling or a roots request, hands the client a signed state and reads it back on the next call. The SDK signs that state with keys you give it. With no keys, tools that ask for input are unavailable on 2026-07-28.
Generate a key of at least 32 bytes:
openssl rand -base64 48
Give the keys to every replica in MCP_REQUEST_STATE_KEYS, separated by commas. They are one secret per deployment, shared by every replica, so keep them where you keep your other secrets.
To rotate a key across replicas, first add the new key after the current one everywhere, so every replica accepts it before any signs with it. Then move it to the front: the first key signs, and every key verifies. Remove the old key once the state lifetime has passed since the last replica signed with it. The lifetime is request_state.ttl, 600 seconds by default.
What the state is, and is not:
- The state is signed, not encrypted. The client can read it, so a tool puts nothing secret in it.
- Each state is bound to the request it was issued for, its tool and arguments, and to the caller. A state issued to one caller does not verify for another.
- When the call resumes, a tool authorises the current caller again. It never trusts identity or organisation values read from the state.
Input schemas
A tool's input schema is generated from its parameters: their types, PHP enums, defaults, and the SDK's #[Schema] attribute for constraints such as patterns, ranges and formats.
In version 1.0, a tool registered by attributes cannot declare a hand-written JSON Schema 2020-12 input schema. If a tool needs a schema that types, enums and #[Schema] constraints cannot express, model the input as a typed object or enum, or validate the input inside the tool and return a tool error.
In production
Enterprise middlewares that an API serving MCP often uses:
- Audit keeps signed records of who did what, in Kafka, OpenSearch or NATS.
- Policy authorises a route from roles, permissions, attributes or OPA.
- Quotas sets per-plan limits on requests and credits, per customer.
- Redaction masks, hashes or removes personal data in responses and in every log line.
- Idempotency makes retries safe with an Idempotency-Key header: a repeated request gets the stored response and is not run twice.
These middlewares act on the HTTP request. MCP carries the tool name inside the request body, so at /mcp they apply to the endpoint as a whole, as "POST /mcp", not to each tool. They are part of Kipchak Enterprise.
The SDK version
The driver requires mcp/sdk at exactly 0.10.0. The SDK is before version 1.0, and each of its minor releases from 0.5 to 0.10 changed its interfaces, so each SDK release reaches you in a driver release that has passed the driver's tests and the protocol's conformance suite. When the SDK publishes a security release, a driver release taking it follows within five working days.
A project that also requires mcp/sdk directly must require the same version as the driver.
Troubleshooting
403 with the body "Forbidden: Invalid Host header." The request's host is not in allowed_hosts. Set MCP_HOST to the host name clients use, or list it in config/kipchak.mcp.php. The log has a warning naming the host received, such as:
MCP server 'default' refused a request for Host 'api.example.com' with 403: that host is not in 'allowed_hosts' in kipchak.mcp. Add it there, or set MCP_HOST.
A tool that asks for input fails with "Error while executing tool" on 2026-07-28. No signing keys are configured. The log shows:
Unhandled error during tool execution ... No requestState signing key is configured; call Builder::setRequestState() before returning state from a handler.
Set MCP_REQUEST_STATE_KEYS, as described under Signed request state.
The API does not start, naming a key. A key in MCP_REQUEST_STATE_KEYS is shorter than 32 bytes. The message gives its position and length, never its value:
MCP server 'default' in kipchak.mcp: 'request_state.keys' has key 1 of 9 bytes; each key must be a string of at least 32 bytes.
Generate a new key with openssl rand -base64 48.
The API does not start: "'principal_attribute' must be set when 'sessions' is set". Sessions need an owner. Set principal_attribute to the attribute your authentication middleware sets, or set sessions to null.
Composer refuses to install the driver, naming kipchak/cli. The project has a CLI older than 1.6, whose OpenAPI validator would report the /mcp route as an error. Upgrade it with composer require --dev kipchak/cli:^1.6.
Git Repository
The source is at 1x.ax/mamluk/kipchak/drivers/mcp. The package is kipchak/driver-mcp on Packagist, under the MIT licence. mcp/sdk is licensed under the Apache License 2.0; it is a dependency and is not copied into the package.