Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16836d4e9a |
||
|
|
ef6bee5531 |
||
|
|
5a64bab1c7 |
||
|
|
e7aa2d77de |
||
|
|
7047019030 |
||
|
|
f39625b257 |
||
|
|
749c0353ef |
||
|
|
1bd7895b5f |
||
|
|
b458008f07 |
||
|
|
ebe067f6b3 |
||
|
|
4630d7424e |
||
|
|
418034f2b0 |
39 changed files with 829 additions and 60 deletions
10
.github/workflows/conformance-weekly.yaml
vendored
10
.github/workflows/conformance-weekly.yaml
vendored
|
|
@ -125,10 +125,11 @@ jobs:
|
||||||
name: Open issue on failure
|
name: Open issue on failure
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
needs: [server, client]
|
needs: [server, client]
|
||||||
if: failure() && github.event_name == 'schedule'
|
if: failure()
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
GH_REPO: ${{ github.repository }}
|
GH_REPO: ${{ github.repository }}
|
||||||
|
EVENT_NAME: ${{ github.event_name }}
|
||||||
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||||
steps:
|
steps:
|
||||||
- name: File or comment tracking issue
|
- name: File or comment tracking issue
|
||||||
|
|
@ -140,12 +141,13 @@ jobs:
|
||||||
gh issue create \
|
gh issue create \
|
||||||
--title '[conformance] Weekly conformance run failed' \
|
--title '[conformance] Weekly conformance run failed' \
|
||||||
--label conformance-weekly \
|
--label conformance-weekly \
|
||||||
--body "Weekly conformance against \`@modelcontextprotocol/conformance@latest\` failed.
|
--body "Conformance against the newest published \`@modelcontextprotocol/conformance\` failed.
|
||||||
|
|
||||||
- Run: $RUN_URL
|
- 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
|
fi
|
||||||
|
|
||||||
publish:
|
publish:
|
||||||
|
|
|
||||||
2
.github/workflows/docs.yml
vendored
2
.github/workflows/docs.yml
vendored
|
|
@ -35,7 +35,7 @@ jobs:
|
||||||
uses: "ramsey/composer-install@v4"
|
uses: "ramsey/composer-install@v4"
|
||||||
|
|
||||||
- name: Install uv
|
- name: Install uv
|
||||||
uses: astral-sh/setup-uv@v10.0.1
|
uses: astral-sh/setup-uv@v10.1.0
|
||||||
with:
|
with:
|
||||||
enable-cache: true
|
enable-cache: true
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,13 @@
|
||||||
|
|
||||||
All notable changes to `mcp/sdk` will be documented in this file.
|
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
|
0.8.0
|
||||||
-----
|
-----
|
||||||
|
|
||||||
|
|
|
||||||
20
README.md
20
README.md
|
|
@ -1,19 +1,10 @@
|
||||||
# MCP PHP SDK
|
# MCP PHP SDK
|
||||||
|
|
||||||
<div align="center">
|
|
||||||
|
|
||||||
[](https://packagist.org/packages/mcp/sdk)
|
[](https://packagist.org/packages/mcp/sdk)
|
||||||
[](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/pipeline.yaml)
|
[](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/pipeline.yaml)
|
||||||
[](https://packagist.org/packages/mcp/sdk)
|
[](https://packagist.org/packages/mcp/sdk)
|
||||||
[](LICENSE)
|
[](LICENSE)
|
||||||
|
|
||||||
[](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml)
|
|
||||||
[](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml)
|
|
||||||
[](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml)
|
|
||||||
[](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
|
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
|
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).
|
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
|
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.
|
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` | [](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml) | [](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml) |
|
||||||
|
| `2025-11-25` | [](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml) | [](https://github.com/modelcontextprotocol/php-sdk/actions/workflows/conformance-weekly.yaml) |
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|
|
||||||
|
|
@ -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.
|
**Dispatched**: When any request is received from the client, before it's processed by handlers.
|
||||||
|
|
||||||
**Properties**:
|
**Properties**:
|
||||||
|
|
||||||
- `getRequest(): Request` - The incoming request
|
- `getRequest(): Request` - The incoming request
|
||||||
- `setRequest(Request $request): void` - Modify the request before processing
|
- `setRequest(Request $request): void` - Modify the request before processing
|
||||||
- `getSession(): SessionInterface` - The current session
|
- `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.
|
**Dispatched**: When a successful response is ready to be sent to the client, after handler execution.
|
||||||
|
|
||||||
**Properties**:
|
**Properties**:
|
||||||
|
|
||||||
- `getResponse(): Response` - The response being sent
|
- `getResponse(): Response` - The response being sent
|
||||||
- `setResponse(Response $response): void` - Modify the response before sending
|
- `setResponse(Response $response): void` - Modify the response before sending
|
||||||
- `getRequest(): Request` - The original request
|
- `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.
|
**Dispatched**: When an error occurs during request processing.
|
||||||
|
|
||||||
**Properties**:
|
**Properties**:
|
||||||
|
|
||||||
- `getError(): Error` - The error being sent
|
- `getError(): Error` - The error being sent
|
||||||
- `setError(Error $error): void` - Modify the error before sending
|
- `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.
|
- `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.
|
**Dispatched**: When a notification is received from the client, before it's processed by handlers.
|
||||||
|
|
||||||
**Properties**:
|
**Properties**:
|
||||||
|
|
||||||
- `getNotification(): Notification` - The incoming notification
|
- `getNotification(): Notification` - The incoming notification
|
||||||
- `setNotification(Notification $notification): void` - Modify the notification before processing
|
- `setNotification(Notification $notification): void` - Modify the notification before processing
|
||||||
- `getSession(): SessionInterface` - The current session
|
- `getSession(): SessionInterface` - The current session
|
||||||
|
|
|
||||||
|
|
@ -169,6 +169,7 @@ $client->connect($transport);
|
||||||
```
|
```
|
||||||
|
|
||||||
The `connect()` method performs the MCP initialization handshake:
|
The `connect()` method performs the MCP initialization handshake:
|
||||||
|
|
||||||
1. Opens the transport connection
|
1. Opens the transport connection
|
||||||
2. Sends InitializeRequest with client capabilities
|
2. Sends InitializeRequest with client capabilities
|
||||||
3. Waits for InitializeResult from server
|
3. Waits for InitializeResult from server
|
||||||
|
|
|
||||||
|
|
@ -18,6 +18,7 @@ $transport = new StdioTransport(
|
||||||
```
|
```
|
||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `command` (string): The command to execute
|
- `command` (string): The command to execute
|
||||||
- `args` (array): Command arguments
|
- `args` (array): Command arguments
|
||||||
- `cwd` (string|null): Working directory for the process
|
- `cwd` (string|null): Working directory for the process
|
||||||
|
|
@ -39,6 +40,7 @@ $transport = new HttpTransport(
|
||||||
```
|
```
|
||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `endpoint` (string): The MCP server URL
|
- `endpoint` (string): The MCP server URL
|
||||||
- `headers` (array): Additional HTTP headers
|
- `headers` (array): Additional HTTP headers
|
||||||
- `httpClient` (ClientInterface|null): PSR-18 HTTP client (auto-discovered)
|
- `httpClient` (ClientInterface|null): PSR-18 HTTP client (auto-discovered)
|
||||||
|
|
@ -50,6 +52,7 @@ $transport = new HttpTransport(
|
||||||
**PSR-18 Auto-Discovery:**
|
**PSR-18 Auto-Discovery:**
|
||||||
|
|
||||||
The transport automatically discovers PSR-18 HTTP clients from:
|
The transport automatically discovers PSR-18 HTTP clients from:
|
||||||
|
|
||||||
- `php-http/guzzle7-adapter`
|
- `php-http/guzzle7-adapter`
|
||||||
- `php-http/curl-client`
|
- `php-http/curl-client`
|
||||||
- `symfony/http-client`
|
- `symfony/http-client`
|
||||||
|
|
|
||||||
|
|
@ -54,6 +54,7 @@ $server = Server::builder()
|
||||||
```
|
```
|
||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `$name` (string): The server name
|
- `$name` (string): The server name
|
||||||
- `$version` (string): Version string (semantic versioning recommended)
|
- `$version` (string): Version string (semantic versioning recommended)
|
||||||
- `$description` (string|null): Optional description
|
- `$description` (string|null): Optional description
|
||||||
|
|
@ -152,6 +153,7 @@ $server = Server::builder()
|
||||||
```
|
```
|
||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `$basePath` (string): Base directory for discovery (typically `__DIR__`)
|
- `$basePath` (string): Base directory for discovery (typically `__DIR__`)
|
||||||
- `$scanDirs` (array): Directories to recursively scan for `#[McpTool]`, `#[McpResource]`, etc. All subdirectories are included. (default: `['.', 'src']`)
|
- `$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
|
- `$excludeDirs` (array): Directory names to exclude **within** the scanned directories during recursive scanning
|
||||||
|
|
@ -189,6 +191,7 @@ $server = Server::builder()
|
||||||
```
|
```
|
||||||
|
|
||||||
**How `excludeDirs` works:**
|
**How `excludeDirs` works:**
|
||||||
|
|
||||||
- If scanning `src/` and there's `src/vendor/`, it will be excluded
|
- If scanning `src/` and there's `src/vendor/`, it will be excluded
|
||||||
- If scanning `lib/` and there's `lib/tests/`, 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`)
|
- 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:**
|
**Basic Container Features:**
|
||||||
|
|
||||||
- Supports constructor auto-wiring for classes with parameterless constructors
|
- Supports constructor auto-wiring for classes with parameterless constructors
|
||||||
- Resolves dependencies where all parameters are type-hinted classes/interfaces known to the container
|
- Resolves dependencies where all parameters are type-hinted classes/interfaces known to the container
|
||||||
- Supports parameters with default values
|
- Supports parameters with default values
|
||||||
|
|
|
||||||
|
|
@ -74,6 +74,7 @@ $server = Server::builder()
|
||||||
```
|
```
|
||||||
|
|
||||||
**Parameters:**
|
**Parameters:**
|
||||||
|
|
||||||
- `$gcProbability` (int): The numerator of the GC probability fraction (default: `1`). Set to `0` to disable GC.
|
- `$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.
|
- `$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.
|
> the `gcProbability` and `gcDivisor` settings are ignored — you control GC behavior in your own implementation.
|
||||||
|
|
||||||
**Available Session Stores:**
|
**Available Session Stores:**
|
||||||
|
|
||||||
- `InMemorySessionStore`: Fast in-memory storage (default)
|
- `InMemorySessionStore`: Fast in-memory storage (default)
|
||||||
- `FileSessionStore`: Persistent file-based storage
|
- `FileSessionStore`: Persistent file-based storage
|
||||||
- `Psr16SessionStore`: PSR-16 compliant cache-based storage
|
- `Psr16SessionStore`: PSR-16 compliant cache-based storage
|
||||||
|
|
|
||||||
|
|
@ -87,6 +87,7 @@ public function getUserProfile(
|
||||||
```
|
```
|
||||||
|
|
||||||
**Provider Resolution:**
|
**Provider Resolution:**
|
||||||
|
|
||||||
- **Class strings** (`Provider::class`) → Resolved from PSR-11 container
|
- **Class strings** (`Provider::class`) → Resolved from PSR-11 container
|
||||||
- **Instances** (`new Provider()`) → Used directly
|
- **Instances** (`new Provider()`) → Used directly
|
||||||
- **Values** (`['a', 'b']`) → Wrapped in `ListCompletionProvider`
|
- **Values** (`['a', 'b']`) → Wrapped in `ListCompletionProvider`
|
||||||
|
|
|
||||||
|
|
@ -100,6 +100,7 @@ makes the prompt handler throw.
|
||||||
### Error Handling
|
### Error Handling
|
||||||
|
|
||||||
Prompt handlers can throw any exception, but the type determines how it's handled:
|
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
|
- **`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
|
- **Any other exception**: Converted to JSON-RPC error response, but with a generic error message
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ registry somehow. There are three ways to get it there, and they mix freely.
|
||||||
## Attribute-Based Discovery
|
## Attribute-Based Discovery
|
||||||
|
|
||||||
**Advantages:**
|
**Advantages:**
|
||||||
|
|
||||||
- Declarative and readable
|
- Declarative and readable
|
||||||
- Automatic parameter inference
|
- Automatic parameter inference
|
||||||
- DocBlock integration
|
- DocBlock integration
|
||||||
|
|
@ -25,6 +26,7 @@ Register MCP elements programmatically without using attributes. The handler is
|
||||||
any PHP callable.
|
any PHP callable.
|
||||||
|
|
||||||
**Advantages:**
|
**Advantages:**
|
||||||
|
|
||||||
- Fine-grained control
|
- Fine-grained control
|
||||||
- Runtime configuration
|
- Runtime configuration
|
||||||
- Conditional registration
|
- Conditional registration
|
||||||
|
|
|
||||||
|
|
@ -24,9 +24,9 @@ class CompletionProvider
|
||||||
* @param class-string<ProviderInterface>|ProviderInterface|null $provider if a class-string, it will be resolved
|
* @param class-string<ProviderInterface>|ProviderInterface|null $provider if a class-string, it will be resolved
|
||||||
* from the container at the point of use
|
* from the container at the point of use
|
||||||
* @param ?array<int, int|float|string> $values a list of values to use for completion
|
* @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 function __construct(
|
||||||
public ?string $providerClass = null,
|
|
||||||
public string|ProviderInterface|null $provider = null,
|
public string|ProviderInterface|null $provider = null,
|
||||||
public ?array $values = null,
|
public ?array $values = null,
|
||||||
public ?string $enum = null,
|
public ?string $enum = null,
|
||||||
|
|
|
||||||
|
|
@ -325,8 +325,6 @@ final class Discoverer implements DiscovererInterface
|
||||||
|
|
||||||
if ($attributeInstance->provider) {
|
if ($attributeInstance->provider) {
|
||||||
$completionProviders[$param->getName()] = $attributeInstance->provider;
|
$completionProviders[$param->getName()] = $attributeInstance->provider;
|
||||||
} elseif ($attributeInstance->providerClass) {
|
|
||||||
$completionProviders[$param->getName()] = $attributeInstance->provider;
|
|
||||||
} elseif ($attributeInstance->values) {
|
} elseif ($attributeInstance->values) {
|
||||||
$completionProviders[$param->getName()] = new ListCompletionProvider($attributeInstance->values);
|
$completionProviders[$param->getName()] = new ListCompletionProvider($attributeInstance->values);
|
||||||
} elseif ($attributeInstance->enum) {
|
} elseif ($attributeInstance->enum) {
|
||||||
|
|
|
||||||
|
|
@ -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
|
private function getCompletionProviders(\ReflectionMethod|\ReflectionFunction $reflection): array
|
||||||
{
|
{
|
||||||
|
|
@ -307,8 +307,6 @@ final class ReflectedElementLoader implements LoaderInterface
|
||||||
|
|
||||||
if ($attributeInstance->provider) {
|
if ($attributeInstance->provider) {
|
||||||
$completionProviders[$param->getName()] = $attributeInstance->provider;
|
$completionProviders[$param->getName()] = $attributeInstance->provider;
|
||||||
} elseif ($attributeInstance->providerClass) {
|
|
||||||
$completionProviders[$param->getName()] = $attributeInstance->providerClass;
|
|
||||||
} elseif ($attributeInstance->values) {
|
} elseif ($attributeInstance->values) {
|
||||||
$completionProviders[$param->getName()] = new ListCompletionProvider($attributeInstance->values);
|
$completionProviders[$param->getName()] = new ListCompletionProvider($attributeInstance->values);
|
||||||
} elseif ($attributeInstance->enum) {
|
} elseif ($attributeInstance->enum) {
|
||||||
|
|
|
||||||
|
|
@ -121,6 +121,22 @@ class HttpTransport extends BaseTransport implements HeaderAwareTransportInterfa
|
||||||
$this->headerCallback = $callback;
|
$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
|
public function send(string $data): void
|
||||||
{
|
{
|
||||||
$request = $this->requestFactory->createRequest('POST', $this->endpoint)
|
$request = $this->requestFactory->createRequest('POST', $this->endpoint)
|
||||||
|
|
|
||||||
|
|
@ -74,7 +74,7 @@ abstract class Notification implements HasMethodInterface, MessageInterface
|
||||||
$array['params'] = $params;
|
$array['params'] = $params;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (null !== $this->meta && !isset($params['meta'])) {
|
if (null !== $this->meta && !isset($params['_meta'])) {
|
||||||
$array['params']['_meta'] = $this->meta;
|
$array['params']['_meta'] = $this->meta;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -122,7 +122,7 @@ abstract class Request implements HasMethodInterface, MessageInterface
|
||||||
$array['params'] = $params;
|
$array['params'] = $params;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (null !== $this->meta && !isset($params['meta'])) {
|
if (null !== $this->meta && !isset($params['_meta'])) {
|
||||||
$array['params']['_meta'] = $this->meta;
|
$array['params']['_meta'] = $this->meta;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -303,9 +303,11 @@ class Protocol
|
||||||
$notification = $result['notification'];
|
$notification = $result['notification'];
|
||||||
$this->sendNotification($notification, $session);
|
$this->sendNotification($notification, $session);
|
||||||
} elseif ('request' === $result['type']) {
|
} 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;
|
$timeout = $result['timeout'] ?? 120;
|
||||||
$this->sendRequest($request, $timeout, $session);
|
$this->sendRequest($outboundRequest, $timeout, $session);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,8 @@ namespace Mcp\Server\Session;
|
||||||
use Mcp\Exception\RuntimeException;
|
use Mcp\Exception\RuntimeException;
|
||||||
use Mcp\Server\NativeClock;
|
use Mcp\Server\NativeClock;
|
||||||
use Psr\Clock\ClockInterface;
|
use Psr\Clock\ClockInterface;
|
||||||
|
use Psr\Log\LoggerInterface;
|
||||||
|
use Psr\Log\NullLogger;
|
||||||
use Symfony\Component\Uid\Uuid;
|
use Symfony\Component\Uid\Uuid;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
@ -26,9 +28,13 @@ class FileSessionStore implements SessionStoreInterface
|
||||||
private readonly string $directory,
|
private readonly string $directory,
|
||||||
private readonly int $ttl = 3600,
|
private readonly int $ttl = 3600,
|
||||||
private readonly ClockInterface $clock = new NativeClock(),
|
private readonly ClockInterface $clock = new NativeClock(),
|
||||||
|
private readonly LoggerInterface $logger = new NullLogger(),
|
||||||
) {
|
) {
|
||||||
if (!is_dir($this->directory)) {
|
if (!is_dir($this->directory) && !@mkdir($this->directory, 0775, true) && !is_dir($this->directory)) {
|
||||||
@mkdir($this->directory, 0775, true);
|
$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)) {
|
if (!is_dir($this->directory) || !is_writable($this->directory)) {
|
||||||
|
|
@ -59,13 +65,23 @@ class FileSessionStore implements SessionStoreInterface
|
||||||
|
|
||||||
$mtime = @filemtime($path) ?: 0;
|
$mtime = @filemtime($path) ?: 0;
|
||||||
if (($this->clock->now()->getTimestamp() - $mtime) > $this->ttl) {
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
$data = @file_get_contents($path);
|
$data = @file_get_contents($path);
|
||||||
if (false === $data) {
|
if (false === $data) {
|
||||||
|
$this->logger->warning('Failed to read session file.', [
|
||||||
|
'path' => $path,
|
||||||
|
'error' => error_get_last()['message'] ?? 'unknown',
|
||||||
|
]);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -78,6 +94,11 @@ class FileSessionStore implements SessionStoreInterface
|
||||||
|
|
||||||
$tmp = $path.'.tmp';
|
$tmp = $path.'.tmp';
|
||||||
if (false === @file_put_contents($tmp, $data, \LOCK_EX)) {
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -85,6 +106,10 @@ class FileSessionStore implements SessionStoreInterface
|
||||||
if (!@rename($tmp, $path)) {
|
if (!@rename($tmp, $path)) {
|
||||||
// Fallback if rename fails cross-device
|
// Fallback if rename fails cross-device
|
||||||
if (false === @copy($tmp, $path)) {
|
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);
|
@unlink($tmp);
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
|
|
@ -101,8 +126,11 @@ class FileSessionStore implements SessionStoreInterface
|
||||||
{
|
{
|
||||||
$path = $this->pathFor($id);
|
$path = $this->pathFor($id);
|
||||||
|
|
||||||
if (is_file($path)) {
|
if (is_file($path) && !@unlink($path) && is_file($path)) {
|
||||||
@unlink($path);
|
$this->logger->warning('Failed to delete session file.', [
|
||||||
|
'path' => $path,
|
||||||
|
'error' => error_get_last()['message'] ?? 'unknown',
|
||||||
|
]);
|
||||||
}
|
}
|
||||||
|
|
||||||
return true;
|
return true;
|
||||||
|
|
@ -119,6 +147,11 @@ class FileSessionStore implements SessionStoreInterface
|
||||||
|
|
||||||
$dir = @opendir($this->directory);
|
$dir = @opendir($this->directory);
|
||||||
if (false === $dir) {
|
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;
|
return $deleted;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -140,7 +173,15 @@ class FileSessionStore implements SessionStoreInterface
|
||||||
|
|
||||||
$mtime = @filemtime($path) ?: 0;
|
$mtime = @filemtime($path) ?: 0;
|
||||||
if (($now - $mtime) > $this->ttl) {
|
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);
|
$deleted[] = Uuid::fromString($entry);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue