All files / scripts/mcp-client/transport session.ts

56.52% Statements 13/23
55.55% Branches 10/18
33.33% Functions 1/3
60% Lines 12/20

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 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106                                                                                            1x   1x 1x   1x 1x         1x   1x                               1x         1x       1x         1x                         1x      
/**
 * @module mcp-client/transport/session
 * @description MCP session bootstrap + SSE response parsing helpers.
 *
 * Extracted from `jsonrpc.ts` so the wire-level request loop stays focused
 * on JSON-RPC dispatch + retry, while session lifecycle (initialize +
 * notifications/initialized) lives in one auditable place.
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import type { JsonRpcResponse } from '../../types/mcp.js';
import { performPost } from '../transport.js';
 
/**
 * Parse an SSE-framed JSON-RPC response. Falls back to plain-JSON parsing
 * when no `data:` lines are present.
 */
export function parseSSEResponse(text: string): JsonRpcResponse {
  const lines = text.split('\n');
  for (const line of lines) {
    if (line.startsWith('data: ')) {
      return JSON.parse(line.substring(6)) as JsonRpcResponse;
    }
  }
  return JSON.parse(text) as JsonRpcResponse;
}
 
export interface SessionInitContext {
  readonly baseURL: string;
  readonly timeout: number;
  readonly customHeaders: Readonly<Record<string, string>>;
  readonly authToken: string;
  sessionId: string | null;
  nextJsonRpcId(): number;
}
 
/**
 * Perform the MCP session handshake (initialize + notifications/initialized).
 *
 * No-op when the context already has a session id or when no auth token is
 * configured (anonymous gateway). On success, `ctx.sessionId` is mutated
 * with the returned `Mcp-Session-Id` header value (when present).
 */
export async function initializeSession(ctx: SessionInitContext): Promise<void> {
  Iif (ctx.sessionId || !ctx.authToken) return;
 
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), ctx.timeout);
 
  try {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      Accept: 'application/json, text/event-stream',
      ...ctx.customHeaders,
    };
    Eif (ctx.authToken) headers['Authorization'] = ctx.authToken;
 
    const response = await performPost(
      ctx.baseURL,
      headers,
      JSON.stringify({
        jsonrpc: '2.0',
        id: ctx.nextJsonRpcId(),
        method: 'initialize',
        params: {
          protocolVersion: '2024-11-05',
          capabilities: {},
          clientInfo: { name: 'riksdagsmonitor-news', version: '1.0.0' },
        },
      }),
      controller.signal,
    );
 
    Iif (!response.ok) {
      throw new Error(`Session init failed: ${response.status} ${response.statusText}`);
    }
 
    const sessionId =
      response.headers && typeof response.headers.get === 'function'
        ? response.headers.get('Mcp-Session-Id')
        : null;
 
    Iif (sessionId) {
      ctx.sessionId = sessionId;
      console.log(`  🔗 MCP session initialized: ${sessionId.substring(0, 8)}...`);
    }
 
    await performPost(
      ctx.baseURL,
      {
        ...headers,
        ...(ctx.sessionId ? { 'Mcp-Session-Id': ctx.sessionId } : {}),
      },
      JSON.stringify({
        jsonrpc: '2.0',
        method: 'notifications/initialized',
      }),
      controller.signal,
    );
  } finally {
    clearTimeout(timeoutId);
  }
}