|  | 
| 4 | 4 | 
 | 
| 5 | 5 | use Illuminate\Http\JsonResponse; | 
| 6 | 6 | use Illuminate\Http\Request; | 
|  | 7 | +use Illuminate\Http\Response; | 
| 7 | 8 | use Illuminate\Routing\Controller; | 
| 8 | 9 | use Kirschbaum\Loop\McpHandler; | 
|  | 10 | +use Kirschbaum\Loop\Services\SseService; | 
|  | 11 | +use Symfony\Component\HttpFoundation\StreamedResponse; | 
| 9 | 12 | 
 | 
| 10 | 13 | class McpController extends Controller | 
| 11 | 14 | { | 
| 12 |  | -    public function __invoke(Request $request, McpHandler $mcpHandler): JsonResponse | 
|  | 15 | +    public function __construct(protected McpHandler $mcpHandler, protected SseService $sseService) {} | 
|  | 16 | + | 
|  | 17 | +    /** | 
|  | 18 | +     * Handle MCP requests. | 
|  | 19 | +     */ | 
|  | 20 | +    public function __invoke(Request $request): JsonResponse|StreamedResponse|Response | 
|  | 21 | +    { | 
|  | 22 | +        if ($request->isMethod('GET')) { | 
|  | 23 | +            return $this->handleGetRequest($request); | 
|  | 24 | +        } | 
|  | 25 | + | 
|  | 26 | +        $acceptsEventStream = strpos($request->header('Accept', ''), 'text/event-stream') !== false; | 
|  | 27 | +        $acceptsJson = strpos($request->header('Accept', ''), 'application/json') !== false; | 
|  | 28 | + | 
|  | 29 | +        if (! $acceptsEventStream && ! $acceptsJson) { | 
|  | 30 | +            return response()->json([ | 
|  | 31 | +                'jsonrpc' => '2.0', | 
|  | 32 | +                'id' => null, | 
|  | 33 | +                'error' => [ | 
|  | 34 | +                    'message' => 'Not Acceptable: Client must accept text/event-stream or application/json', | 
|  | 35 | +                ], | 
|  | 36 | +            ], 406); | 
|  | 37 | +        } | 
|  | 38 | + | 
|  | 39 | +        $requestData = $request->all(); | 
|  | 40 | +        $containsRequests = $this->containsJsonRpcRequests($requestData); | 
|  | 41 | + | 
|  | 42 | +        if (! $containsRequests) { | 
|  | 43 | +            $this->mcpHandler->handle($requestData); | 
|  | 44 | + | 
|  | 45 | +            return response('', 202); | 
|  | 46 | +        } | 
|  | 47 | + | 
|  | 48 | +        if ($this->clientPrefersJson($acceptsJson, $acceptsEventStream)) { | 
|  | 49 | +            return $this->handlePostJsonResponse($requestData); | 
|  | 50 | +        } | 
|  | 51 | + | 
|  | 52 | +        return $this->handlePostSseResponse($requestData); | 
|  | 53 | +    } | 
|  | 54 | + | 
|  | 55 | +    /** | 
|  | 56 | +     * Handle SSE response for POST requests. | 
|  | 57 | +     * | 
|  | 58 | +     * @param  array<array-key, mixed>  $messages  JSON-RPC messages from the client | 
|  | 59 | +     */ | 
|  | 60 | +    protected function handlePostSseResponse(array $messages): StreamedResponse | 
|  | 61 | +    { | 
|  | 62 | +        $response = $this->sseService->createPostSseResponse( | 
|  | 63 | +            $messages, | 
|  | 64 | +            fn ($message) => $this->mcpHandler->handle($message), | 
|  | 65 | +        ); | 
|  | 66 | + | 
|  | 67 | +        return $response; | 
|  | 68 | +    } | 
|  | 69 | + | 
|  | 70 | +    /** | 
|  | 71 | +     * Handle JSON response for POST requests. | 
|  | 72 | +     * | 
|  | 73 | +     * @param  array<array-key, mixed>  $messages  JSON-RPC messages from the client | 
|  | 74 | +     */ | 
|  | 75 | +    protected function handlePostJsonResponse(array $messages): JsonResponse | 
|  | 76 | +    { | 
|  | 77 | +        $response = $this->mcpHandler->handle($messages); | 
|  | 78 | + | 
|  | 79 | +        return response()->json($response); | 
|  | 80 | +    } | 
|  | 81 | + | 
|  | 82 | +    /** | 
|  | 83 | +     * Handle GET requests for backwards compatibility with older clients | 
|  | 84 | +     * expecting an SSE stream for server-initiated messages. | 
|  | 85 | +     */ | 
|  | 86 | +    protected function handleGetRequest(Request $request): StreamedResponse|JsonResponse|Response | 
|  | 87 | +    { | 
|  | 88 | +        if (strpos($request->header('Accept', ''), 'text/event-stream') === false) { | 
|  | 89 | +            return response()->json([ | 
|  | 90 | +                'jsonrpc' => '2.0', | 
|  | 91 | +                'id' => null, | 
|  | 92 | +                'error' => [ | 
|  | 93 | +                    // Using a generic error code; consult JSON-RPC spec for specific codes if necessary | 
|  | 94 | +                    'code' => -32000, | 
|  | 95 | +                    'message' => 'Not Acceptable: Client must include "Accept: text/event-stream" for this endpoint.', | 
|  | 96 | +                ], | 
|  | 97 | +            ], 406); | 
|  | 98 | +        } | 
|  | 99 | + | 
|  | 100 | +        // Placeholder for the "endpoint event" data structure. | 
|  | 101 | +        // Adjust this to match what older clients expect. | 
|  | 102 | +        $endpointEventData = [ | 
|  | 103 | +            'status' => 'connected', | 
|  | 104 | +            'transport_protocol' => 'http_sse_deprecated_2024_11_05', | 
|  | 105 | +            'message' => 'SSE connection established for server-initiated messages.', | 
|  | 106 | +        ]; | 
|  | 107 | + | 
|  | 108 | +        return new StreamedResponse(function () use ($endpointEventData) { | 
|  | 109 | +            // Send the initial "endpoint event" | 
|  | 110 | +            // The event name 'endpoint' is a placeholder; adjust if old clients expect a different name. | 
|  | 111 | +            echo 'event: endpoint | 
|  | 112 | +'; | 
|  | 113 | +            echo 'data: '.json_encode($endpointEventData).' | 
|  | 114 | +
 | 
|  | 115 | +'; | 
|  | 116 | +            flush(); | 
|  | 117 | + | 
|  | 118 | +            // This loop maintains the connection and sends heartbeats. | 
|  | 119 | +            // In a production environment, this section would need to integrate | 
|  | 120 | +            // with an event bus or message queue to push actual application events | 
|  | 121 | +            // to the client. | 
|  | 122 | +            while (true) { | 
|  | 123 | +                if (connection_aborted()) { | 
|  | 124 | +                    break; | 
|  | 125 | +                } | 
|  | 126 | + | 
|  | 127 | +                // Send an SSE comment as a heartbeat to keep the connection alive | 
|  | 128 | +                // and help with proxy buffering. | 
|  | 129 | +                echo ': heartbeat | 
|  | 130 | +
 | 
|  | 131 | +'; | 
|  | 132 | +                flush(); | 
|  | 133 | + | 
|  | 134 | +                // Pause before sending the next heartbeat. | 
|  | 135 | +                // The frequency of heartbeats can be adjusted. | 
|  | 136 | +                sleep(15); | 
|  | 137 | +            } | 
|  | 138 | +        }, 200, [ | 
|  | 139 | +            'Content-Type' => 'text/event-stream', | 
|  | 140 | +            'Cache-Control' => 'no-cache', | 
|  | 141 | +            'X-Accel-Buffering' => 'no', // Important for Nginx and other reverse proxies | 
|  | 142 | +            'Connection' => 'keep-alive', | 
|  | 143 | +        ]); | 
|  | 144 | +    } | 
|  | 145 | + | 
|  | 146 | +    /** | 
|  | 147 | +     * Check if the input contains any JSON-RPC requests. | 
|  | 148 | +     * | 
|  | 149 | +     * @param  mixed  $input | 
|  | 150 | +     */ | 
|  | 151 | +    protected function containsJsonRpcRequests($input): bool | 
| 13 | 152 |     { | 
| 14 |  | -        $message = $request->all(); | 
|  | 153 | +        // If input is an array with numeric keys, it's a batch | 
|  | 154 | +        if (is_array($input) && array_keys($input) === range(0, count($input) - 1)) { | 
|  | 155 | +            foreach ($input as $item) { | 
|  | 156 | +                if ($this->isJsonRpcRequest($item)) { | 
|  | 157 | +                    return true; | 
|  | 158 | +                } | 
|  | 159 | +            } | 
|  | 160 | + | 
|  | 161 | +            return false; | 
|  | 162 | +        } | 
|  | 163 | + | 
|  | 164 | +        return $this->isJsonRpcRequest($input); | 
|  | 165 | +    } | 
| 15 | 166 | 
 | 
| 16 |  | -        return response()->json($mcpHandler->handle($message)); | 
|  | 167 | +    /** | 
|  | 168 | +     * Check if the client prefers JSON over SSE. | 
|  | 169 | +     * | 
|  | 170 | +     * @param  mixed  $acceptsJson | 
|  | 171 | +     * @param  mixed  $acceptsEventStream | 
|  | 172 | +     */ | 
|  | 173 | +    protected function clientPrefersJson($acceptsJson, $acceptsEventStream): bool | 
|  | 174 | +    { | 
|  | 175 | +        return $acceptsJson && $acceptsEventStream === false; | 
|  | 176 | +    } | 
|  | 177 | + | 
|  | 178 | +    /** | 
|  | 179 | +     * Check if an item is a JSON-RPC request. | 
|  | 180 | +     * | 
|  | 181 | +     * @param  mixed  $item | 
|  | 182 | +     */ | 
|  | 183 | +    protected function isJsonRpcRequest($item): bool | 
|  | 184 | +    { | 
|  | 185 | +        return is_array($item) && | 
|  | 186 | +               isset($item['jsonrpc']) && | 
|  | 187 | +               $item['jsonrpc'] === '2.0' && | 
|  | 188 | +               isset($item['method']) && | 
|  | 189 | +               isset($item['id']); | 
| 17 | 190 |     } | 
| 18 | 191 | } | 
0 commit comments