Skip to content

Commit 09d415e

Browse files
Fix WP_Error handling in Prompts and Resources handlers (#74)
Add proper WP_Error detection after ability execution in PromptsHandler and ResourcesHandler to prevent crashes and return graceful error responses.
1 parent 8af590d commit 09d415e

File tree

2 files changed

+52
-1
lines changed

2 files changed

+52
-1
lines changed

includes/Handlers/Prompts/PromptsHandler.php

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,33 @@ public function get_prompt( array $params, int $request_id = 0 ): array {
159159
);
160160
}
161161

162-
$result = $ability->execute( $arguments );
162+
$result = $ability->execute( $arguments );
163+
164+
// Handle WP_Error objects that weren't converted by the ability.
165+
if ( is_wp_error( $result ) ) {
166+
$this->mcp->error_handler->log(
167+
'Ability returned WP_Error object',
168+
array(
169+
'ability' => $ability->get_name(),
170+
'error_code' => $result->get_error_code(),
171+
'error_message' => $result->get_error_message(),
172+
)
173+
);
174+
175+
return array(
176+
'error' => McpErrorFactory::internal_error( $request_id, $result->get_error_message() )['error'],
177+
'_metadata' => array(
178+
'component_type' => 'prompt',
179+
'prompt_name' => $prompt_name,
180+
'ability_name' => $ability->get_name(),
181+
'failure_reason' => 'wp_error',
182+
'error_code' => $result->get_error_code(),
183+
'is_builder' => false,
184+
),
185+
);
186+
}
187+
188+
// Successful execution - add metadata.
163189
$result['_metadata'] = array(
164190
'component_type' => 'prompt',
165191
'prompt_name' => $prompt_name,

includes/Handlers/Resources/ResourcesHandler.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,31 @@ public function read_resource( array $params, int $request_id = 0 ): array {
130130

131131
$contents = $ability->execute( $request_params );
132132

133+
// Handle WP_Error objects that weren't converted by the ability.
134+
if ( is_wp_error( $contents ) ) {
135+
$this->mcp->error_handler->log(
136+
'Ability returned WP_Error object',
137+
array(
138+
'ability' => $ability->get_name(),
139+
'error_code' => $contents->get_error_code(),
140+
'error_message' => $contents->get_error_message(),
141+
)
142+
);
143+
144+
return array(
145+
'error' => McpErrorFactory::internal_error( $request_id, $contents->get_error_message() )['error'],
146+
'_metadata' => array(
147+
'component_type' => 'resource',
148+
'resource_uri' => $uri,
149+
'resource_name' => $resource->get_name(),
150+
'ability_name' => $ability->get_name(),
151+
'failure_reason' => 'wp_error',
152+
'error_code' => $contents->get_error_code(),
153+
),
154+
);
155+
}
156+
157+
// Successful execution - return contents.
133158
return array(
134159
'contents' => $contents,
135160
'_metadata' => array(

0 commit comments

Comments
 (0)