forked from modelcontextprotocol/php-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSamplingRequestHandler.php
More file actions
67 lines (57 loc) · 2.06 KB
/
Copy pathSamplingRequestHandler.php
File metadata and controls
67 lines (57 loc) · 2.06 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
<?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\Client\Handler\Request;
use Mcp\Exception\SamplingException;
use Mcp\Schema\JsonRpc\Error;
use Mcp\Schema\JsonRpc\Request;
use Mcp\Schema\JsonRpc\Response;
use Mcp\Schema\Request\CreateSamplingMessageRequest;
use Mcp\Schema\Result\CreateSamplingMessageResult;
use Psr\Log\LoggerInterface;
use Psr\Log\NullLogger;
/**
* Handler for sampling requests from the server.
*
* The MCP server may request the client to sample an LLM during tool execution.
* This handler wraps a user-provided callback that performs the actual LLM call.
*
* @implements RequestHandlerInterface<CreateSamplingMessageResult>
*
* @author Kyrian Obikwelu <koshnawaza@gmail.com>
*/
class SamplingRequestHandler implements RequestHandlerInterface
{
public function __construct(
private readonly SamplingCallbackInterface $callback,
private readonly LoggerInterface $logger = new NullLogger(),
) {
}
public function supports(Request $request): bool
{
return $request instanceof CreateSamplingMessageRequest;
}
/**
* @return Response<CreateSamplingMessageResult>|Error
*/
public function handle(Request $request): Response|Error
{
\assert($request instanceof CreateSamplingMessageRequest);
try {
$result = $this->callback->__invoke($request);
return new Response($request->getId(), $result);
} catch (SamplingException $e) {
$this->logger->error('Sampling failed: '.$e->getMessage(), ['exception' => $e]);
return Error::forInternalError($e->getMessage(), $request->getId());
} catch (\Throwable $e) {
$this->logger->error('Unexpected error during sampling', ['exception' => $e]);
return Error::forInternalError('Error while sampling LLM', $request->getId());
}
}
}