1: <?php
2:
3: declare(strict_types=1);
4:
5: /**
6: * This file is part of the Nexus MCP SDK package.
7: *
8: * (c) 2026 John Paul E. Balandan, CPA <paulbalandan@gmail.com>
9: *
10: * For the full copyright and license information, please view
11: * the LICENSE file that was distributed with this source code.
12: */
13:
14: namespace Nexus\Mcp\Extension\Tasks\Server\Handler;
15:
16: use Nexus\Mcp\Core\Exception\InvalidParamsException;
17: use Nexus\Mcp\Core\Handler\AbstractContext;
18: use Nexus\Mcp\Core\Handler\RequestHandlerInterface;
19: use Nexus\Mcp\Core\Schema\JsonRpc\JsonRpcRequest;
20: use Nexus\Mcp\Core\Schema\Result\EmptyResult;
21: use Nexus\Mcp\Extension\Tasks\Schema\Request\CancelTaskRequest;
22: use Nexus\Mcp\Extension\Tasks\Server\Store\TaskStoreInterface;
23: use Nexus\Mcp\Extension\Tasks\Server\TaskCancellationRegistry;
24: use Nexus\Mcp\Server\ServerContext;
25:
26: /**
27: * Handles the `tasks/cancel` request, idempotently on a terminal task.
28: *
29: * @implements RequestHandlerInterface<'tasks/cancel', EmptyResult, ServerContext>
30: */
31: final readonly class CancelTaskRequestHandler implements RequestHandlerInterface
32: {
33: public function __construct(
34: private TaskStoreInterface $store,
35: private TaskCancellationRegistry $cancellations,
36: ) {
37: }
38:
39: #[\Override]
40: public function handle(JsonRpcRequest $request, AbstractContext $context): EmptyResult
41: {
42: \assert($request instanceof CancelTaskRequest);
43:
44: $taskId = $request->params->taskId;
45:
46: if ($this->store->findTask($taskId) === null) {
47: throw new InvalidParamsException($context->requestId, '"params.taskId" does not name a known task.');
48: }
49:
50: $this->store->trySetCancelled($taskId);
51: $this->cancellations->cancel($taskId);
52:
53: return new EmptyResult();
54: }
55: }
56: