@@ -89,28 +89,14 @@ public function execute(string $method, ?array $params = null): array
8989 }
9090
9191 if ($ autoStructuredOutput ) {
92- try {
93- json_encode ($ preparedResult , JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE );
94- } catch (JsonException $ exception ) {
95- throw new JsonRpcErrorException (
96- message: 'Failed to encode tool result as JSON: ' .$ exception ->getMessage (),
97- code: JsonRpcErrorCode::INTERNAL_ERROR
98- );
99- }
92+ $ this ->encodeJson ($ preparedResult );
10093
10194 return [
10295 'structuredContent ' => $ preparedResult ,
10396 ];
10497 }
10598
106- try {
107- $ text = json_encode ($ preparedResult , JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE );
108- } catch (JsonException $ exception ) {
109- throw new JsonRpcErrorException (
110- message: 'Failed to encode tool result as JSON: ' .$ exception ->getMessage (),
111- code: JsonRpcErrorCode::INTERNAL_ERROR
112- );
113- }
99+ $ text = $ this ->encodeJson ($ preparedResult );
114100
115101 return [
116102 'content ' => [
@@ -133,14 +119,7 @@ public function execute(string $method, ?array $params = null): array
133119 ];
134120 }
135121
136- try {
137- $ text = json_encode ($ preparedResult , JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE );
138- } catch (JsonException $ exception ) {
139- throw new JsonRpcErrorException (
140- message: 'Failed to encode tool result as JSON: ' .$ exception ->getMessage (),
141- code: JsonRpcErrorCode::INTERNAL_ERROR
142- );
143- }
122+ $ text = $ this ->encodeJson ($ preparedResult );
144123
145124 return [
146125 'content ' => [
@@ -156,4 +135,19 @@ public function execute(string $method, ?array $params = null): array
156135 ];
157136 }
158137 }
138+
139+ /**
140+ * Ensure results remain JSON serializable while providing consistent error handling.
141+ */
142+ private function encodeJson (mixed $ value ): string
143+ {
144+ try {
145+ return json_encode ($ value , JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE );
146+ } catch (JsonException $ exception ) {
147+ throw new JsonRpcErrorException (
148+ message: 'Failed to encode tool result as JSON: ' .$ exception ->getMessage (),
149+ code: JsonRpcErrorCode::INTERNAL_ERROR
150+ );
151+ }
152+ }
159153}
0 commit comments