Compare commits

...
Author SHA1 Message Date
dependabot[bot]
16836d4e9a
chore(deps): bump astral-sh/setup-uv from 10.0.1 to 10.1.0 (#512)
Some checks failed
Documentation / build (push) Has been cancelled
Documentation / deploy (push) Has been cancelled
Bumps [astral-sh/setup-uv](https://github.com/astral-sh/setup-uv) from 10.0.1 to 10.1.0.
- [Release notes](https://github.com/astral-sh/setup-uv/releases)
- [Commits](https://github.com/astral-sh/setup-uv/compare/v10.0.1...v10.1.0)

---
updated-dependencies:
- dependency-name: astral-sh/setup-uv
  dependency-version: 10.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-09-15 15:57:24 +02:00
Дмитрий Воротынцев
ef6bee5531
[Server] fix OIDC discovery for issuers with trailing slash (#506)
* fix OIDC discovery for issuers with trailing slash

* add trailing-slash issuer tests and changelog entry

---------

Co-authored-by: Dmitry Vorotyntsev <d.vorotyntsev@dats.team>
Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
2026-09-15 00:14:48 +02:00
Christopher Hertel
5a64bab1c7
[CI] Open conformance issue on manual runs too (#502) 2026-09-08 01:15:25 +02:00
Christopher Hertel
e7aa2d77de
[Docs] Add blank line before lists so they render (#503) 2026-09-08 01:14:59 +02:00
Christopher Hertel
7047019030
[README] Show conformance badges in a table (#501) 2026-09-08 00:49:47 +02:00
Christopher Hertel
f39625b257
[Capability] Remove CompletionProvider's dead providerClass argument (#499)
* [Capability] Remove CompletionProvider's dead providerClass argument

It always threw on construction, so it never worked in any release. `provider:`
takes the same class-string and is now the first positional argument.

* Reword Changelog
2026-09-07 23:27:53 +02:00
Christopher Hertel
749c0353ef
[Server] Keep inbound request intact when queueing an outbound one (#486) 2026-09-05 01:36:39 +02:00
Christopher Hertel
1bd7895b5f
[Schema] Fix _meta guard key in Request and Notification jsonSerialize() (#485) 2026-09-05 01:18:54 +02:00
Christopher Hertel
b458008f07
[Server] Fix StreamableHttpTransport mutable state and clock (#487) 2026-09-05 01:13:09 +02:00
Christopher Hertel
ebe067f6b3
[Server] Log filesystem failures in FileSessionStore (#488)
* [Server] Log filesystem failures in FileSessionStore

* [Server] Warn on failed unlink during session garbage collection
2026-09-05 01:11:20 +02:00
Christopher Hertel
4630d7424e
[Server] Stop Session::forget() from creating missing segments (#484) 2026-09-04 23:55:48 +02:00
Rob Loach
418034f2b0
[Client] Expose session ID from HttpTransport (#497)
* Expose session ID from HttpTransport

* [Client] State what getSessionId() returns on 2026-07-28

That revision removed protocol-level sessions (SEP-2567), so the getter is always null there. Adds the changelog entry.

---------

Co-authored-by: Christopher Hertel <mail@christopher-hertel.de>
2026-09-04 23:55:20 +02:00
39 changed files with 829 additions and 60 deletions

View file

@ -125,10 +125,11 @@ jobs:
name: Open issue on failure
runs-on: ubuntu-latest
needs: [server, client]
if: failure() && github.event_name == 'schedule'
if: failure()
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
EVENT_NAME: ${{ github.event_name }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
steps:
- name: File or comment tracking issue
@ -140,12 +141,13 @@ jobs:
gh issue create \
--title '[conformance] Weekly conformance run failed' \
--label conformance-weekly \
--body "Weekly conformance against \`@modelcontextprotocol/conformance@latest\` failed.
--body "Conformance against the newest published \`@modelcontextprotocol/conformance\` failed.
- Run: $RUN_URL
- Triggered: $(date -u +%FT%TZ)
- Trigger: $EVENT_NAME
- Date: $(date -u +%FT%TZ)
Upstream likely published a release whose scenarios the SDK does not satisfy. Either fix the SDK, update the conformance fixtures, or add the new failure to \`tests/Conformance/conformance-baseline-2025-11-25.yml\`."
Upstream likely published a release whose scenarios the SDK does not satisfy. Either fix the SDK, update the conformance fixtures, or add the new failure to the matching \`tests/Conformance/conformance-baseline-<spec-version>.yml\`."
fi
publish:

View file

@ -35,7 +35,7 @@ jobs:
uses: "ramsey/composer-install@v4"
- name: Install uv
uses: astral-sh/setup-uv@v10.0.1
uses: astral-sh/setup-uv@v10.1.0
with:
enable-cache: true

View file

@ -2,6 +2,13 @@
All notable changes to `mcp/sdk` will be documented in this file.
0.9.0
-----
* [BC Break] Remove the `providerClass` argument of `#[CompletionProvider]`. Use `provider:`, which takes the same class-string and is now the first positional argument.
* Add `HttpTransport::getSessionId()` to read the server-minted `Mcp-Session-Id`: a request-scoped caller can persist it and pass it back through the constructor's `$headers` on a later transport. Always `null` on `2026-07-28`, which removed protocol-level sessions.
* Fix OIDC discovery rejecting issuers with a trailing slash (e.g. Authentik, Auth0).
0.8.0
-----

View file

@ -1,19 +1,10 @@
# MCP PHP SDK
<div align="center">
[![Latest Version](https://img.shields.io/packagist/v/mcp/sdk.svg)](https://packagist.org/packages/mcp/sdk)
[![CI](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/pipeline.yaml/badge.svg)](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/pipeline.yaml)
[![PHP Version](https://img.shields.io/packagist/php-v/mcp/sdk.svg)](https://packagist.org/packages/mcp/sdk)
[![License](https://img.shields.io/packagist/l/mcp/sdk.svg)](LICENSE)
[![Server Conformance 2025-11-25](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/modelcontextprotocol/php-sdk/badges/server-conformance-2025-11-25.json)](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml)
[![Client Conformance 2025-11-25](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/modelcontextprotocol/php-sdk/badges/client-conformance-2025-11-25.json)](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml)
[![Server Conformance 2026-07-28](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/modelcontextprotocol/php-sdk/badges/server-conformance-2026-07-28.json)](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml)
[![Client Conformance 2026-07-28](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/modelcontextprotocol/php-sdk/badges/client-conformance-2026-07-28.json)](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml)
</div>
The official PHP SDK for the Model Context Protocol (MCP). It provides a framework-agnostic API for implementing MCP
servers and clients in PHP — tools, resources, prompts, STDIO and HTTP transports, sessions, authorization, and both
protocol eras (the `initialize` handshake and the stateless `2026-07-28` revision).
@ -25,6 +16,17 @@ development practices and standards from the Symfony project, including [Coding
Until the first major release, this SDK is considered [experimental](https://symfony.com/doc/current/contributing/code/experimental.html), please see the [roadmap](./ROADMAP.md) for
planned next steps and features.
## Protocol Conformance
Measured weekly against the [MCP Conformance Test Framework](https://github.com/modelcontextprotocol/conformance),
as passing checks out of total. The `2026-07-28` scores run against the framework's `alpha` releases, so they move as
upstream publishes new scenarios.
| Revision | Server | Client |
|:--------:|:------:|:------:|
| `2026-07-28` | [![Server conformance 2026-07-28](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/modelcontextprotocol/php-sdk/badges/server-conformance-2026-07-28.json)](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml) | [![Client conformance 2026-07-28](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/modelcontextprotocol/php-sdk/badges/client-conformance-2026-07-28.json)](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml) |
| `2025-11-25` | [![Server conformance 2025-11-25](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/modelcontextprotocol/php-sdk/badges/server-conformance-2025-11-25.json)](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml) | [![Client conformance 2025-11-25](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/modelcontextprotocol/php-sdk/badges/client-conformance-2025-11-25.json)](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml) |
## Installation
```bash

View file

@ -35,6 +35,7 @@ The SDK dispatches 4 broad event types at the protocol level, allowing you to ob
**Dispatched**: When any request is received from the client, before it's processed by handlers.
**Properties**:
- `getRequest(): Request` - The incoming request
- `setRequest(Request $request): void` - Modify the request before processing
- `getSession(): SessionInterface` - The current session
@ -45,6 +46,7 @@ The SDK dispatches 4 broad event types at the protocol level, allowing you to ob
**Dispatched**: When a successful response is ready to be sent to the client, after handler execution.
**Properties**:
- `getResponse(): Response` - The response being sent
- `setResponse(Response $response): void` - Modify the response before sending
- `getRequest(): Request` - The original request
@ -56,6 +58,7 @@ The SDK dispatches 4 broad event types at the protocol level, allowing you to ob
**Dispatched**: When an error occurs during request processing.
**Properties**:
- `getError(): Error` - The error being sent
- `setError(Error $error): void` - Modify the error before sending
- `getRequest(): Request` - The original request. Messages that fail to parse are rejected before this event, so a listener never sees them.
@ -67,6 +70,7 @@ The SDK dispatches 4 broad event types at the protocol level, allowing you to ob
**Dispatched**: When a notification is received from the client, before it's processed by handlers.
**Properties**:
- `getNotification(): Notification` - The incoming notification
- `setNotification(Notification $notification): void` - Modify the notification before processing
- `getSession(): SessionInterface` - The current session

View file

@ -169,6 +169,7 @@ $client->connect($transport);
```
The `connect()` method performs the MCP initialization handshake:
1. Opens the transport connection
2. Sends InitializeRequest with client capabilities
3. Waits for InitializeResult from server

View file

@ -18,6 +18,7 @@ $transport = new StdioTransport(
```
**Parameters:**
- `command` (string): The command to execute
- `args` (array): Command arguments
- `cwd` (string|null): Working directory for the process
@ -39,6 +40,7 @@ $transport = new HttpTransport(
```
**Parameters:**
- `endpoint` (string): The MCP server URL
- `headers` (array): Additional HTTP headers
- `httpClient` (ClientInterface|null): PSR-18 HTTP client (auto-discovered)
@ -50,6 +52,7 @@ $transport = new HttpTransport(
**PSR-18 Auto-Discovery:**
The transport automatically discovers PSR-18 HTTP clients from:
- `php-http/guzzle7-adapter`
- `php-http/curl-client`
- `symfony/http-client`

View file

@ -54,6 +54,7 @@ $server = Server::builder()
```
**Parameters:**
- `$name` (string): The server name
- `$version` (string): Version string (semantic versioning recommended)
- `$description` (string|null): Optional description
@ -152,6 +153,7 @@ $server = Server::builder()
```
**Parameters:**
- `$basePath` (string): Base directory for discovery (typically `__DIR__`)
- `$scanDirs` (array): Directories to recursively scan for `#[McpTool]`, `#[McpResource]`, etc. All subdirectories are included. (default: `['.', 'src']`)
- `$excludeDirs` (array): Directory names to exclude **within** the scanned directories during recursive scanning
@ -189,6 +191,7 @@ $server = Server::builder()
```
**How `excludeDirs` works:**
- If scanning `src/` and there's `src/vendor/`, it will be excluded
- If scanning `lib/` and there's `lib/tests/`, it will be excluded
- But if `vendor/` and `tests/` are at the same level as `src/`, they're not scanned anyway (not in `scanDirs`)
@ -217,6 +220,7 @@ $server = Server::builder()
```
**Basic Container Features:**
- Supports constructor auto-wiring for classes with parameterless constructors
- Resolves dependencies where all parameters are type-hinted classes/interfaces known to the container
- Supports parameters with default values

View file

@ -74,6 +74,7 @@ $server = Server::builder()
```
**Parameters:**
- `$gcProbability` (int): The numerator of the GC probability fraction (default: `1`). Set to `0` to disable GC.
- `$gcDivisor` (int): The denominator of the GC probability fraction (default: `100`). Must be >= 1.
@ -81,6 +82,7 @@ $server = Server::builder()
> the `gcProbability` and `gcDivisor` settings are ignored — you control GC behavior in your own implementation.
**Available Session Stores:**
- `InMemorySessionStore`: Fast in-memory storage (default)
- `FileSessionStore`: Persistent file-based storage
- `Psr16SessionStore`: PSR-16 compliant cache-based storage

View file

@ -87,6 +87,7 @@ public function getUserProfile(
```
**Provider Resolution:**
- **Class strings** (`Provider::class`) → Resolved from PSR-11 container
- **Instances** (`new Provider()`) → Used directly
- **Values** (`['a', 'b']`) → Wrapped in `ListCompletionProvider`

View file

@ -100,6 +100,7 @@ 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

View file

@ -6,6 +6,7 @@ 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
@ -25,6 +26,7 @@ Register MCP elements programmatically without using attributes. The handler is
any PHP callable.
**Advantages:**
- Fine-grained control
- Runtime configuration
- Conditional registration

View file

@ -24,9 +24,9 @@ class CompletionProvider
* @param class-string<ProviderInterface>|ProviderInterface|null $provider if a class-string, it will be resolved
* from the container at the point of use
* @param ?array<int, int|float|string> $values a list of values to use for completion
* @param class-string|null $enum an enum whose cases are the completions
*/
public function __construct(
public ?string $providerClass = null,
public string|ProviderInterface|null $provider = null,
public ?array $values = null,
public ?string $enum = null,

View file

@ -325,8 +325,6 @@ final class Discoverer implements DiscovererInterface
if ($attributeInstance->provider) {
$completionProviders[$param->getName()] = $attributeInstance->provider;
} elseif ($attributeInstance->providerClass) {
$completionProviders[$param->getName()] = $attributeInstance->provider;
} elseif ($attributeInstance->values) {
$completionProviders[$param->getName()] = new ListCompletionProvider($attributeInstance->values);
} elseif ($attributeInstance->enum) {

View file

@ -287,7 +287,7 @@ final class ReflectedElementLoader implements LoaderInterface
}
/**
* @return array<string, ProviderInterface>
* @return array<string, class-string<ProviderInterface>|ProviderInterface>
*/
private function getCompletionProviders(\ReflectionMethod|\ReflectionFunction $reflection): array
{
@ -307,8 +307,6 @@ final class ReflectedElementLoader implements LoaderInterface
if ($attributeInstance->provider) {
$completionProviders[$param->getName()] = $attributeInstance->provider;
} elseif ($attributeInstance->providerClass) {
$completionProviders[$param->getName()] = $attributeInstance->providerClass;
} elseif ($attributeInstance->values) {
$completionProviders[$param->getName()] = new ListCompletionProvider($attributeInstance->values);
} elseif ($attributeInstance->enum) {

View file

@ -121,6 +121,22 @@ class HttpTransport extends BaseTransport implements HeaderAwareTransportInterfa
$this->headerCallback = $callback;
}
/**
* The session ID minted by the server for this connection, if any.
*
* Captured from the Mcp-Session-Id response header of a handshake-era
* server; always null on 2026-07-28, which removed protocol-level sessions
* (SEP-2567). A caller that cannot keep the transport alive between
* interactions can persist it and pass it back through the constructor's
* $headers on a later transport, where it wins over the tracked value.
*
* @return string|null null until the server mints a session, and again after close()
*/
public function getSessionId(): ?string
{
return $this->sessionId;
}
public function send(string $data): void
{
$request = $this->requestFactory->createRequest('POST', $this->endpoint)

View file

@ -74,7 +74,7 @@ abstract class Notification implements HasMethodInterface, MessageInterface
$array['params'] = $params;
}
if (null !== $this->meta && !isset($params['meta'])) {
if (null !== $this->meta && !isset($params['_meta'])) {
$array['params']['_meta'] = $this->meta;
}

View file

@ -122,7 +122,7 @@ abstract class Request implements HasMethodInterface, MessageInterface
$array['params'] = $params;
}
if (null !== $this->meta && !isset($params['meta'])) {
if (null !== $this->meta && !isset($params['_meta'])) {
$array['params']['_meta'] = $this->meta;
}

View file

@ -303,9 +303,11 @@ class Protocol
$notification = $result['notification'];
$this->sendNotification($notification, $session);
} elseif ('request' === $result['type']) {
$request = $result['request'];
// Keep $request untouched: it is the inbound request the catch
// blocks below answer under, not this outbound one.
$outboundRequest = $result['request'];
$timeout = $result['timeout'] ?? 120;
$this->sendRequest($request, $timeout, $session);
$this->sendRequest($outboundRequest, $timeout, $session);
}
}

View file

@ -14,6 +14,8 @@ namespace Mcp\Server\Session;
use Mcp\Exception\RuntimeException;
use Mcp\Server\NativeClock;
use Psr\Clock\ClockInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Symfony\Component\Uid\Uuid;
/**
@ -26,9 +28,13 @@ class FileSessionStore implements SessionStoreInterface
private readonly string $directory,
private readonly int $ttl = 3600,
private readonly ClockInterface $clock = new NativeClock(),
private readonly LoggerInterface $logger = new NullLogger(),
) {
if (!is_dir($this->directory)) {
@mkdir($this->directory, 0775, true);
if (!is_dir($this->directory) && !@mkdir($this->directory, 0775, true) && !is_dir($this->directory)) {
$this->logger->warning('Failed to create session directory.', [
'directory' => $this->directory,
'error' => error_get_last()['message'] ?? 'unknown',
]);
}
if (!is_dir($this->directory) || !is_writable($this->directory)) {
@ -59,13 +65,23 @@ class FileSessionStore implements SessionStoreInterface
$mtime = @filemtime($path) ?: 0;
if (($this->clock->now()->getTimestamp() - $mtime) > $this->ttl) {
@unlink($path);
if (!@unlink($path) && is_file($path)) {
$this->logger->warning('Failed to delete expired session file.', [
'path' => $path,
'error' => error_get_last()['message'] ?? 'unknown',
]);
}
return false;
}
$data = @file_get_contents($path);
if (false === $data) {
$this->logger->warning('Failed to read session file.', [
'path' => $path,
'error' => error_get_last()['message'] ?? 'unknown',
]);
return false;
}
@ -78,6 +94,11 @@ class FileSessionStore implements SessionStoreInterface
$tmp = $path.'.tmp';
if (false === @file_put_contents($tmp, $data, \LOCK_EX)) {
$this->logger->warning('Failed to write session file.', [
'path' => $tmp,
'error' => error_get_last()['message'] ?? 'unknown',
]);
return false;
}
@ -85,6 +106,10 @@ class FileSessionStore implements SessionStoreInterface
if (!@rename($tmp, $path)) {
// Fallback if rename fails cross-device
if (false === @copy($tmp, $path)) {
$this->logger->warning('Failed to move session file into place.', [
'path' => $path,
'error' => error_get_last()['message'] ?? 'unknown',
]);
@unlink($tmp);
return false;
@ -101,8 +126,11 @@ class FileSessionStore implements SessionStoreInterface
{
$path = $this->pathFor($id);
if (is_file($path)) {
@unlink($path);
if (is_file($path) && !@unlink($path) && is_file($path)) {
$this->logger->warning('Failed to delete session file.', [
'path' => $path,
'error' => error_get_last()['message'] ?? 'unknown',
]);
}
return true;
@ -119,6 +147,11 @@ class FileSessionStore implements SessionStoreInterface
$dir = @opendir($this->directory);
if (false === $dir) {
$this->logger->warning('Failed to open session directory for garbage collection.', [
'directory' => $this->directory,
'error' => error_get_last()['message'] ?? 'unknown',
]);
return $deleted;
}
@ -140,7 +173,15 @@ class FileSessionStore implements SessionStoreInterface
$mtime = @filemtime($path) ?: 0;
if (($now - $mtime) > $this->ttl) {
@unlink($path);
if (!@unlink($path) && is_file($path)) {
$this->logger->warning('Failed to delete expired session file.', [
'path' => $path,
'error' => error_get_last()['message'] ?? 'unknown',
]);
continue;
}
$deleted[] = Uuid::fromString($entry);
}
}

Some files were not shown because too many files have changed in this diff Show more