Skip to content

Commit 93a3e6a

Browse files
refactor: use specific exceptions in examples for better error handling
1 parent 7c65b85 commit 93a3e6a

File tree

5 files changed

+16
-24
lines changed

5 files changed

+16
-24
lines changed

examples/http-client-communication/server.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
use Http\Discovery\Psr17Factory;
1616
use Laminas\HttpHandlerRunner\Emitter\SapiEmitter;
17+
use Mcp\Exception\ToolCallException;
1718
use Mcp\Schema\Content\TextContent;
1819
use Mcp\Schema\Enum\LoggingLevel;
1920
use Mcp\Schema\JsonRpc\Error as JsonRpcError;
@@ -64,7 +65,7 @@ function (string $projectName, array $milestones, ClientGateway $client): array
6465
);
6566

6667
if ($response instanceof JsonRpcError) {
67-
throw new RuntimeException(sprintf('Sampling request failed (%d): %s', $response->code, $response->message));
68+
throw new ToolCallException(sprintf('Sampling request failed (%d): %s', $response->code, $response->message));
6869
}
6970

7071
$result = $response->result;

examples/http-discovery-userprofile/McpElements.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,8 @@
1616
use Mcp\Capability\Attribute\McpResource;
1717
use Mcp\Capability\Attribute\McpResourceTemplate;
1818
use Mcp\Capability\Attribute\McpTool;
19+
use Mcp\Exception\PromptGetException;
20+
use Mcp\Exception\ResourceReadException;
1921
use Psr\Log\LoggerInterface;
2022

2123
/**
@@ -47,7 +49,7 @@ public function __construct(
4749
*
4850
* @return User user profile data
4951
*
50-
* @throws McpServerException if the user is not found
52+
* @throws ResourceReadException if the user is not found
5153
*/
5254
#[McpResourceTemplate(
5355
uriTemplate: 'user://{userId}/profile',
@@ -61,8 +63,7 @@ public function getUserProfile(
6163
): array {
6264
$this->logger->info('Reading resource: user profile', ['userId' => $userId]);
6365
if (!isset($this->users[$userId])) {
64-
// Throwing an exception that Processor can turn into an error response
65-
throw McpServerException::invalidParams("User profile not found for ID: {$userId}");
66+
throw new ResourceReadException("User not found for ID: {$userId}");
6667
}
6768

6869
return $this->users[$userId];
@@ -130,7 +131,7 @@ public function testToolWithoutParams(): array
130131
*
131132
* @return array<string, string>[] prompt messages
132133
*
133-
* @throws McpServerException if user not found
134+
* @throws PromptGetException if user not found
134135
*/
135136
#[McpPrompt(name: 'generate_bio_prompt')]
136137
public function generateBio(
@@ -140,7 +141,7 @@ public function generateBio(
140141
): array {
141142
$this->logger->info('Executing prompt: generate_bio', ['userId' => $userId, 'tone' => $tone]);
142143
if (!isset($this->users[$userId])) {
143-
throw McpServerException::invalidParams("User not found for bio prompt: {$userId}");
144+
throw new PromptGetException("User not found for bio prompt: {$userId}");
144145
}
145146
$user = $this->users[$userId];
146147

examples/stdio-cached-discovery/CachedCalculatorElements.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
namespace Mcp\Example\StdioCachedDiscovery;
1515

1616
use Mcp\Capability\Attribute\McpTool;
17+
use Mcp\Exception\ToolCallException;
1718

1819
/**
1920
* Example MCP elements for demonstrating cached discovery.
@@ -39,7 +40,7 @@ public function multiply(int $a, int $b): int
3940
public function divide(int $a, int $b): float
4041
{
4142
if (0 === $b) {
42-
throw new \InvalidArgumentException('Division by zero is not allowed');
43+
throw new ToolCallException('Division by zero is not allowed');
4344
}
4445

4546
return $a / $b;

examples/stdio-discovery-calculator/McpElements.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313

1414
use Mcp\Capability\Attribute\McpResource;
1515
use Mcp\Capability\Attribute\McpTool;
16+
use Mcp\Exception\ToolCallException;
1617
use Psr\Log\LoggerInterface;
1718
use Psr\Log\NullLogger;
1819

@@ -44,10 +45,10 @@ public function __construct(
4445
* @param float $b the second operand
4546
* @param string $operation the operation ('add', 'subtract', 'multiply', 'divide')
4647
*
47-
* @return float|string the result of the calculation, or an error message string
48+
* @return float the result of the calculation
4849
*/
4950
#[McpTool(name: 'calculate')]
50-
public function calculate(float $a, float $b, string $operation): float|string
51+
public function calculate(float $a, float $b, string $operation): float
5152
{
5253
$this->logger->info(\sprintf('Calculating: %f %s %f', $a, $operation, $b));
5354

@@ -65,16 +66,16 @@ public function calculate(float $a, float $b, string $operation): float|string
6566
break;
6667
case 'divide':
6768
if (0 == $b) {
68-
return 'Error: Division by zero.';
69+
throw new ToolCallException('Division by zero is not allowed.');
6970
}
7071
$result = $a / $b;
7172
break;
7273
default:
73-
return "Error: Unknown operation '{$operation}'. Supported: add, subtract, multiply, divide.";
74+
throw new ToolCallException("Unknown operation '{$operation}'. Supported: add, subtract, multiply, divide.");
7475
}
7576

7677
if (!$this->config['allow_negative'] && $result < 0) {
77-
return 'Error: Negative results are disabled.';
78+
throw new ToolCallException('Negative results are disabled.');
7879
}
7980

8081
return round($result, $this->config['precision']);

phpstan-baseline.neon

Lines changed: 0 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,5 @@
11
parameters:
22
ignoreErrors:
3-
-
4-
message: '#^Call to static method invalidParams\(\) on an unknown class Mcp\\Example\\HttpDiscoveryUserProfile\\McpServerException\.$#'
5-
identifier: class.notFound
6-
count: 2
7-
path: examples/http-discovery-userprofile/McpElements.php
8-
9-
-
10-
message: '#^PHPDoc tag @throws with type Mcp\\Example\\HttpDiscoveryUserProfile\\McpServerException is not subtype of Throwable$#'
11-
identifier: throws.notThrowable
12-
count: 2
13-
path: examples/http-discovery-userprofile/McpElements.php
14-
153
-
164
message: '#^Method Mcp\\Schema\\Result\\ReadResourceResult\:\:jsonSerialize\(\) should return array\{contents\: array\<Mcp\\Schema\\Content\\BlobResourceContents\|Mcp\\Schema\\Content\\TextResourceContents\>\} but returns array\{contents\: array\<Mcp\\Schema\\Content\\ResourceContents\>\}\.$#'
175
identifier: return.type

0 commit comments

Comments
 (0)