forked from modelcontextprotocol/php-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSessionSubscriptionManager.php
More file actions
94 lines (83 loc) · 2.74 KB
/
SessionSubscriptionManager.php
File metadata and controls
94 lines (83 loc) · 2.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
<?php
/*
* This file is part of the official PHP MCP SDK.
*
* A collaboration between Symfony and the PHP Foundation.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Mcp\Server\Resource;
use Mcp\Schema\Notification\ResourceUpdatedNotification;
use Mcp\Server\Protocol;
use Mcp\Server\Session\SessionInterface;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
use Psr\SimpleCache\InvalidArgumentException;
/**
* The default Subscription manager implementation manages subscriptions per session only.
* It is in-memory and does not support cross-session or cross-client subscriptions.
*
* The SDK allows injecting alternative SubscriptionManagerInterface
* implementations via Builder::setResourceSubscriptionManager().
*
* @author Larry Sule-balogun <suleabimbola@gmail.com>
*/
final class SessionSubscriptionManager implements SubscriptionManagerInterface
{
public function __construct(
private readonly LoggerInterface $logger = new NullLogger(),
) {
}
/**
* @throws InvalidArgumentException
*/
public function subscribe(SessionInterface $session, string $uri): void
{
$subscriptions = $session->get('resource_subscriptions', []);
$subscriptions[$uri] = true;
$session->set('resource_subscriptions', $subscriptions);
$session->save();
}
/**
* @throws InvalidArgumentException
*/
public function unsubscribe(SessionInterface $session, string $uri): void
{
$subscriptions = $session->get('resource_subscriptions', []);
unset($subscriptions[$uri]);
$session->set('resource_subscriptions', $subscriptions);
$session->save();
}
/**
* @throws InvalidArgumentException
*/
public function isSubscribed(SessionInterface $session, string $uri): bool
{
$subscriptions = $session->get('resource_subscriptions', []);
return isset($subscriptions[$uri]);
}
/**
* @throws InvalidArgumentException
*/
public function notifyResourceChanged(Protocol $protocol, SessionInterface $session, string $uri): void
{
$activeSession = $this->isSubscribed($session, $uri);
if (!$activeSession) {
return;
}
try {
$protocol->sendNotification(
new ResourceUpdatedNotification($uri),
$session
);
} catch (InvalidArgumentException $e) {
$this->logger->error('Error sending resource notification to session', [
'session_id' => $session->getId()->toRfc4122(),
'uri' => $uri,
'exception' => $e,
]);
throw $e;
}
}
}