All files / src/mcp/transport sse-parser.ts

100% Statements 9/9
100% Branches 4/4
100% Functions 1/1
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39                                            16x 16x 29x 29x 17x 17x 15x 15x             4x    
// SPDX-FileCopyrightText: 2024-2026 Hack23 AB
// SPDX-License-Identifier: Apache-2.0
 
/**
 * @module MCP/transport/sse-parser
 * @description Server-Sent Events parser for MCP Streamable HTTP responses.
 */
 
import type { JSONRPCResponse } from '../../types/index.js';
 
/**
 * Parse an SSE (Server-Sent Events) response body to extract the first valid JSON-RPC message.
 *
 * The MCP Streamable HTTP protocol sends JSON-RPC responses as SSE `data:` lines.
 * This function returns the **first** successfully parsed JSON-RPC message; any
 * subsequent `data:` lines are ignored. This matches the MCP protocol expectation
 * of one JSON-RPC response per HTTP request/response cycle.
 *
 * @param body - Raw SSE response text (may contain multiple lines including `event:` and `data:`)
 * @returns The first valid JSON-RPC response found, or null if no valid message exists
 */
export function parseSSEResponse(body: string): JSONRPCResponse | null {
  const lines = body.split('\n');
  for (const line of lines) {
    const trimmed = line.trim();
    if (trimmed.startsWith('data:')) {
      const jsonStr = trimmed.slice(5).trim();
      if (jsonStr) {
        try {
          return JSON.parse(jsonStr) as JSONRPCResponse;
        } catch {
          // Continue to next data line
        }
      }
    }
  }
  return null;
}