|
2 | 2 |
|
3 | 3 | namespace OPGG\LaravelMcpServer\Server\Request; |
4 | 4 |
|
| 5 | +use JsonException; |
5 | 6 | use OPGG\LaravelMcpServer\Enums\ProcessMessageType; |
6 | 7 | use OPGG\LaravelMcpServer\Exceptions\Enums\JsonRpcErrorCode; |
7 | 8 | use OPGG\LaravelMcpServer\Exceptions\JsonRpcErrorException; |
@@ -73,15 +74,60 @@ public function execute(string $method, ?array $params = null): array |
73 | 74 | return $preparedResult; |
74 | 75 | } |
75 | 76 |
|
76 | | - if (is_array($preparedResult) && array_key_exists('content', $preparedResult)) { |
77 | | - return $preparedResult; |
| 77 | + if (is_array($preparedResult)) { |
| 78 | + if (array_key_exists('content', $preparedResult) |
| 79 | + || array_key_exists('structuredContent', $preparedResult) |
| 80 | + || array_key_exists('isError', $preparedResult)) { |
| 81 | + return $preparedResult; |
| 82 | + } |
| 83 | + |
| 84 | + try { |
| 85 | + $json = json_encode($preparedResult, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE); |
| 86 | + } catch (JsonException $exception) { |
| 87 | + throw new JsonRpcErrorException( |
| 88 | + message: 'Failed to encode tool result as JSON: '.$exception->getMessage(), |
| 89 | + code: JsonRpcErrorCode::INTERNAL_ERROR |
| 90 | + ); |
| 91 | + } |
| 92 | + |
| 93 | + return [ |
| 94 | + 'content' => [ |
| 95 | + [ |
| 96 | + 'type' => 'text', |
| 97 | + 'text' => $json, |
| 98 | + ], |
| 99 | + ], |
| 100 | + // Provide structuredContent alongside text per MCP 2025-06-18 guidance. |
| 101 | + // @see https://modelcontextprotocol.io/specification/2025-06-18#structured-content |
| 102 | + 'structuredContent' => $preparedResult, |
| 103 | + ]; |
| 104 | + } |
| 105 | + |
| 106 | + if (is_string($preparedResult)) { |
| 107 | + return [ |
| 108 | + 'content' => [ |
| 109 | + [ |
| 110 | + 'type' => 'text', |
| 111 | + 'text' => $preparedResult, |
| 112 | + ], |
| 113 | + ], |
| 114 | + ]; |
| 115 | + } |
| 116 | + |
| 117 | + try { |
| 118 | + $text = json_encode($preparedResult, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE); |
| 119 | + } catch (JsonException $exception) { |
| 120 | + throw new JsonRpcErrorException( |
| 121 | + message: 'Failed to encode tool result as JSON: '.$exception->getMessage(), |
| 122 | + code: JsonRpcErrorCode::INTERNAL_ERROR |
| 123 | + ); |
78 | 124 | } |
79 | 125 |
|
80 | 126 | return [ |
81 | 127 | 'content' => [ |
82 | 128 | [ |
83 | 129 | 'type' => 'text', |
84 | | - 'text' => is_string($preparedResult) ? $preparedResult : json_encode($preparedResult, JSON_UNESCAPED_UNICODE), |
| 130 | + 'text' => $text, |
85 | 131 | ], |
86 | 132 | ], |
87 | 133 | ]; |
|
0 commit comments