All files / adapters/fastify index.ts

51.35% Statements 95/185
29.12% Branches 30/103
60% Functions 12/20
51.35% Lines 95/185

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 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780                                                                                                                                                                                                                                                          1x                               6x     6x 1x       5x 1x       5x 20x 11x         5x               5x 5x           5x                 8x   8x 8x     8x     8x 8x 2x             6x     6x     6x                           5x                     2x 2x     2x 2x   1x             1x     1x 1x               1x     1x     1x                             5x                                                                                                               5x 4x         4x   4x                           5x                 1x 1x   1x     1x 1x               1x 1x             1x     1x   1x                           5x                     2x 2x   2x 2x     1x 1x               1x 2x             1x     1x   1x     1x 1x                   5x                 1x   1x 1x     1x     1x   1x                           5x                     1x 1x   1x     1x     1x   1x                             5x                                                                                     5x 5x           5x                                                                                                                                                                                                                 5x                                                     5x                 5x 1x   1x 1x     1x 1x     5x                                                             1x       1x   1x          
/**
 * Fastify adapter for Drizzle Cube
 * Provides Cube.js-compatible API endpoints as a Fastify plugin with Drizzle ORM
 */
 
import { FastifyPluginCallback, FastifyRequest, FastifyReply, FastifyInstance } from 'fastify'
import type { FastifyCorsOptions } from '@fastify/cors'
import type {
  SemanticQuery,
  SecurityContext,
  DatabaseExecutor,
  DrizzleDatabase,
  Cube,
  CacheConfig,
  ExplainOptions
} from '../../server'
import { SemanticLayerCompiler } from '../../server/compiler'
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import type { MySql2Database } from 'drizzle-orm/mysql2'
import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3'
import {
  handleDryRun,
  formatCubeResponse,
  formatSqlResponse,
  formatMetaResponse,
  formatErrorResponse,
  handleBatchRequest,
  type MCPOptions
} from '../utils'
import {
  buildJsonRpcError,
  buildJsonRpcResult,
  dispatchMcpMethod,
  isNotification,
  negotiateProtocol,
  parseJsonRpc,
  primeEventId,
  serializeSseEvent,
  wantsEventStream,
  validateAcceptHeader,
  validateOriginHeader,
  MCP_SESSION_ID_HEADER
} from '../mcp-transport'
 
export interface FastifyAdapterOptions {
  /**
   * Array of cube definitions to register
   */
  cubes: Cube[]
  
  /**
   * Drizzle database instance (REQUIRED)
   * This is the core of drizzle-cube - Drizzle ORM integration
   * Accepts PostgreSQL, MySQL, or SQLite database instances
   */
  drizzle: PostgresJsDatabase<any> | MySql2Database<any> | BetterSQLite3Database<any> | DrizzleDatabase
  
  /**
   * Database schema for type inference (RECOMMENDED)
   * Provides full type safety for cube definitions
   */
  schema?: any
  
  /**
   * Extract security context from incoming HTTP request.
   * Called for EVERY API request to determine user permissions and multi-tenant isolation.
   * 
   * This is your security boundary - ensure proper authentication and authorization here.
   * 
   * @param request - Fastify Request object containing the incoming HTTP request
   * @returns Security context with organisationId, userId, roles, etc.
   * 
   * @example
   * extractSecurityContext: async (request) => {
   *   // Extract JWT from Authorization header
   *   const token = request.headers.authorization?.replace('Bearer ', '')
   *   const decoded = await verifyJWT(token)
   *   
   *   // Return context that will be available in all cube SQL functions
   *   return {
   *     organisationId: decoded.orgId,
   *     userId: decoded.userId,
   *     roles: decoded.roles
   *   }
   * }
   */
  extractSecurityContext: (request: FastifyRequest) => SecurityContext | Promise<SecurityContext>
  
  /**
   * Database engine type (optional - auto-detected if not provided)
   */
  engineType?: 'postgres' | 'mysql' | 'sqlite' | 'singlestore' | 'duckdb'
  
  /**
   * CORS configuration (optional)
   */
  cors?: FastifyCorsOptions
  
  /**
   * API base path (default: '/cubejs-api/v1')
   */
  basePath?: string
 
  /**
   * JSON body parser limit (default: 10485760 - 10MB)
   */
  bodyLimit?: number
 
  /**
   * Cache configuration for query result caching
   * When provided, query results will be cached using the specified provider
   */
  cache?: CacheConfig
 
  /**
   * MCP (AI-Ready) endpoint configuration
   * Enables AI agents to discover and query your data
   * @default { enabled: true }
   */
  mcp?: MCPOptions
}
 
/**
 * Fastify plugin for Cube.js-compatible API
 */
export const cubePlugin: FastifyPluginCallback<FastifyAdapterOptions> = function cubePlugin(
  fastify: FastifyInstance, 
  options: FastifyAdapterOptions, 
  done: (err?: Error) => void
) {
  const {
    cubes,
    drizzle,
    schema,
    extractSecurityContext,
    engineType,
    cors: corsConfig,
    basePath = '/cubejs-api/v1',
    bodyLimit = 10485760, // 10MB
    cache,
    mcp = { enabled: true }
  } = options
 
  // Validate required options
  if (!cubes || cubes.length === 0) {
    return done(new Error('At least one cube must be provided in the cubes array'))
  }
 
  // Register CORS plugin if configured
  if (corsConfig) {
    fastify.register(import('@fastify/cors'), corsConfig)
  }
 
  // Configure body limit - just a placeholder hook that doesn't use reply
  fastify.addHook('onRequest', async (request, _reply) => {
    if (request.method === 'POST') {
      request.body = undefined // Reset body to allow parsing with custom limit
    }
  })
 
  // Create semantic layer and register all cubes
  const semanticLayer = new SemanticLayerCompiler({
    drizzle,
    schema,
    engineType,
    cache
  })
 
  // Register all provided cubes
  cubes.forEach(cube => {
    semanticLayer.registerCube(cube)
  })
 
  /**
   * POST /cubejs-api/v1/load - Execute queries
   */
  fastify.post(`${basePath}/load`, {
    bodyLimit,
    schema: {
      body: {
        type: 'object',
        additionalProperties: true
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      // Handle both direct query and nested query formats
      const body = request.body as any
      const query: SemanticQuery = body.query || body
 
      // Extract security context using user-provided function
      const securityContext = await extractSecurityContext(request)
 
      // Validate query structure and field existence
      const validation = semanticLayer.validateQuery(query)
      if (!validation.isValid) {
        return reply.status(400).send(formatErrorResponse(
          `Query validation failed: ${validation.errors.join(', ')}`,
          400
        ))
      }
 
      // Check for cache bypass header (X-Cache-Control: no-cache)
      const skipCache = request.headers['x-cache-control'] === 'no-cache'
 
      // Execute multi-cube query (handles both single and multi-cube automatically)
      const result = await semanticLayer.executeMultiCubeQuery(query, securityContext, { skipCache })
 
      // Return in official Cube.js format
      return formatCubeResponse(query, result, semanticLayer)
 
    } catch (error) {
      request.log.error(error, 'Query execution error')
      return reply.status(500).send(formatErrorResponse(
        error instanceof Error ? error.message : 'Query execution failed',
        500
      ))
    }
  })
 
  /**
   * GET /cubejs-api/v1/load - Execute queries via query string
   */
  fastify.get(`${basePath}/load`, {
    schema: {
      querystring: {
        type: 'object',
        properties: {
          query: { type: 'string' }
        },
        required: ['query']
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const { query: queryParam } = request.query as { query: string }
 
      let query: SemanticQuery
      try {
        query = JSON.parse(queryParam)
      } catch {
        return reply.status(400).send(formatErrorResponse(
          'Invalid JSON in query parameter',
          400
        ))
      }
 
      // Extract security context
      const securityContext = await extractSecurityContext(request)
 
      // Validate query structure and field existence
      const validation = semanticLayer.validateQuery(query)
      Iif (!validation.isValid) {
        return reply.status(400).send(formatErrorResponse(
          `Query validation failed: ${validation.errors.join(', ')}`,
          400
        ))
      }
 
      // Check for cache bypass header (X-Cache-Control: no-cache)
      const skipCache = request.headers['x-cache-control'] === 'no-cache'
 
      // Execute multi-cube query (handles both single and multi-cube automatically)
      const result = await semanticLayer.executeMultiCubeQuery(query, securityContext, { skipCache })
 
      // Return in official Cube.js format
      return formatCubeResponse(query, result, semanticLayer)
 
    } catch (error) {
      request.log.error(error, 'Query execution error')
      return reply.status(500).send(formatErrorResponse(
        error instanceof Error ? error.message : 'Query execution failed',
        500
      ))
    }
  })
 
  /**
   * POST /cubejs-api/v1/batch - Execute multiple queries in a single request
   * Optimizes network overhead for dashboards with many portlets
   */
  fastify.post(`${basePath}/batch`, {
    bodyLimit,
    schema: {
      body: {
        type: 'object',
        required: ['queries'],
        properties: {
          queries: {
            type: 'array',
            items: { type: 'object' }
          }
        }
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const { queries } = request.body as { queries: SemanticQuery[] }
 
      if (!queries || !Array.isArray(queries)) {
        return reply.status(400).send(formatErrorResponse(
          'Request body must contain a "queries" array',
          400
        ))
      }
 
      if (queries.length === 0) {
        return reply.status(400).send(formatErrorResponse(
          'Queries array cannot be empty',
          400
        ))
      }
 
      // Extract security context ONCE (shared across all queries)
      const securityContext = await extractSecurityContext(request)
 
      // Check for cache bypass header (X-Cache-Control: no-cache)
      const skipCache = request.headers['x-cache-control'] === 'no-cache'
 
      // Use shared batch handler (wraps existing single query logic)
      const batchResult = await handleBatchRequest(queries, securityContext, semanticLayer, { skipCache })
 
      return batchResult
 
    } catch (error) {
      request.log.error(error, 'Batch execution error')
      return reply.status(500).send(formatErrorResponse(
        error instanceof Error ? error.message : 'Batch execution failed',
        500
      ))
    }
  })
 
  /**
   * GET /cubejs-api/v1/meta - Get cube metadata
   * Optimized for fast response times with caching
   */
  fastify.get(`${basePath}/meta`, async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      // Extract security context (some apps may want to filter cubes by context)
      // await getSecurityContext(request) // Available if needed for filtering
      
      // Get cached metadata (fast path)
      const metadata = semanticLayer.getMetadata()
      
      return formatMetaResponse(metadata)
      
    } catch (error) {
      request.log.error(error, 'Metadata error')
      return reply.status(500).send(formatErrorResponse(
        error instanceof Error ? error.message : 'Failed to fetch metadata',
        500
      ))
    }
  })
 
  /**
   * POST /cubejs-api/v1/sql - Generate SQL without execution (dry run)
   */
  fastify.post(`${basePath}/sql`, {
    bodyLimit,
    schema: {
      body: {
        type: 'object',
        additionalProperties: true
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const query: SemanticQuery = request.body as SemanticQuery
      
      const securityContext = await extractSecurityContext(request)
      
      // Validate query structure and field existence
      const validation = semanticLayer.validateQuery(query)
      Iif (!validation.isValid) {
        return reply.status(400).send(formatErrorResponse(
          `Query validation failed: ${validation.errors.join(', ')}`,
          400
        ))
      }
 
      // For SQL generation, we need at least one cube referenced
      const firstMember = query.measures?.[0] || query.dimensions?.[0]
      Iif (!firstMember) {
        return reply.status(400).send(formatErrorResponse(
          'No measures or dimensions specified',
          400
        ))
      }
 
      const cubeName = firstMember.split('.')[0]
      
      // Generate SQL using the semantic layer compiler
      const sqlResult = await semanticLayer.generateSQL(cubeName, query, securityContext)
      
      return formatSqlResponse(query, sqlResult)
      
    } catch (error) {
      request.log.error(error, 'SQL generation error')
      return reply.status(500).send(formatErrorResponse(
        error instanceof Error ? error.message : 'SQL generation failed',
        500
      ))
    }
  })
 
  /**
   * GET /cubejs-api/v1/sql - Generate SQL via query string
   */
  fastify.get(`${basePath}/sql`, {
    schema: {
      querystring: {
        type: 'object',
        properties: {
          query: { type: 'string' }
        },
        required: ['query']
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const { query: queryParam } = request.query as { query: string }
 
      const query: SemanticQuery = JSON.parse(queryParam)
      const securityContext = await extractSecurityContext(request)
      
      // Validate query structure and field existence
      const validation = semanticLayer.validateQuery(query)
      Iif (!validation.isValid) {
        return reply.status(400).send(formatErrorResponse(
          `Query validation failed: ${validation.errors.join(', ')}`,
          400
        ))
      }
 
      // For SQL generation, we need at least one cube referenced
      const firstMember = query.measures?.[0] || query.dimensions?.[0]
      Iif (!firstMember) {
        return reply.status(400).send(formatErrorResponse(
          'No measures or dimensions specified',
          400
        ))
      }
 
      const cubeName = firstMember.split('.')[0]
      
      // Generate SQL using the semantic layer compiler
      const sqlResult = await semanticLayer.generateSQL(cubeName, query, securityContext)
      
      return formatSqlResponse(query, sqlResult)
      
    } catch (error) {
      request.log.error(error, 'SQL generation error')
      return reply.status(500).send(formatErrorResponse(
        error instanceof Error ? error.message : 'SQL generation failed',
        500
      ))
    }
  })
 
  /**
   * POST /cubejs-api/v1/dry-run - Validate queries without execution
   */
  fastify.post(`${basePath}/dry-run`, {
    bodyLimit,
    schema: {
      body: {
        type: 'object',
        additionalProperties: true
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      // Handle both direct query and nested query formats
      const body = request.body as any
      const query: SemanticQuery = body.query || body
      
      // Extract security context using user-provided function
      const securityContext = await extractSecurityContext(request)
      
      // Perform dry-run analysis
      const result = await handleDryRun(query, securityContext, semanticLayer)
      
      return result
      
    } catch (error) {
      request.log.error(error, 'Dry-run error')
      return reply.status(400).send({
        error: error instanceof Error ? error.message : 'Dry-run validation failed',
        valid: false
      })
    }
  })
 
  /**
   * GET /cubejs-api/v1/dry-run - Validate queries via query string
   */
  fastify.get(`${basePath}/dry-run`, {
    schema: {
      querystring: {
        type: 'object',
        properties: {
          query: { type: 'string' }
        },
        required: ['query']
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      const { query: queryParam } = request.query as { query: string }
 
      const query: SemanticQuery = JSON.parse(queryParam)
 
      // Extract security context
      const securityContext = await extractSecurityContext(request)
 
      // Perform dry-run analysis
      const result = await handleDryRun(query, securityContext, semanticLayer)
 
      return result
 
    } catch (error) {
      request.log.error(error, 'Dry-run error')
      return reply.status(400).send({
        error: error instanceof Error ? error.message : 'Dry-run validation failed',
        valid: false
      })
    }
  })
 
  /**
   * POST /cubejs-api/v1/explain - Get execution plan for a query
   * Returns normalized EXPLAIN output across PostgreSQL, MySQL, and SQLite
   */
  fastify.post(`${basePath}/explain`, {
    bodyLimit,
    schema: {
      body: {
        type: 'object',
        additionalProperties: true
      }
    }
  }, async (request: FastifyRequest, reply: FastifyReply) => {
    try {
      // Handle both direct query and nested query formats
      const body = request.body as any
      const query: SemanticQuery = body.query || body
      const options: ExplainOptions = body.options || {}
 
      // Extract security context using user-provided function
      const securityContext = await extractSecurityContext(request)
 
      // Validate query structure and field existence
      const validation = semanticLayer.validateQuery(query)
      if (!validation.isValid) {
        return reply.status(400).send({
          error: `Query validation failed: ${validation.errors.join(', ')}`
        })
      }
 
      // Execute EXPLAIN using the semantic layer
      const explainResult = await semanticLayer.explainQuery(query, securityContext, options)
 
      return explainResult
 
    } catch (error) {
      request.log.error(error, 'Explain error')
      return reply.status(500).send({
        error: error instanceof Error ? error.message : 'Explain query failed'
      })
    }
  })
 
  // ============================================
  // MCP (AI-Ready) Endpoints
  // ============================================
 
  Eif (mcp.enabled !== false) {
    const mcpBasePath = mcp.basePath ?? '/mcp'
 
    /**
     * MCP Streamable HTTP endpoint (JSON-RPC 2.0 + optional SSE)
     * Implements MCP 2025-11-25 spec
     */
    fastify.post(`${mcpBasePath}`, {
      bodyLimit,
      schema: {
        body: {
          type: 'object',
          additionalProperties: true
        }
      }
    }, async (request: FastifyRequest, reply: FastifyReply) => {
      // Validate Origin header (MCP 2025-11-25: MUST validate, return 403 if invalid)
      const originValidation = validateOriginHeader(
        request.headers.origin as string | undefined,
        mcp.allowedOrigins ? { allowedOrigins: mcp.allowedOrigins } : {}
      )
      if (!originValidation.valid) {
        return reply.status(403).send(buildJsonRpcError(null, -32600, originValidation.reason))
      }
 
      // Validate Accept header (MCP 2025-11-25: MUST include both application/json and text/event-stream)
      const acceptHeader = request.headers.accept as string | undefined
      if (!validateAcceptHeader(acceptHeader)) {
        return reply.status(400).send(buildJsonRpcError(null, -32600, 'Accept header must include both application/json and text/event-stream'))
      }
 
      const protocol = negotiateProtocol(request.headers as Record<string, string>)
      if (!protocol.ok) {
        return reply.status(426).send({
          error: 'Unsupported MCP protocol version',
          supported: protocol.supported
        })
      }
 
      const rpcRequest = parseJsonRpc(request.body)
      if (!rpcRequest) {
        return reply.status(400).send(buildJsonRpcError(null, -32600, 'Invalid JSON-RPC 2.0 request'))
      }
 
      const wantsStream = wantsEventStream(acceptHeader)
      const isInitialize = rpcRequest.method === 'initialize'
 
      try {
        const result = await dispatchMcpMethod(
          rpcRequest.method,
          rpcRequest.params,
          {
            semanticLayer,
            extractSecurityContext,
            rawRequest: request,
            rawResponse: reply,
            negotiatedProtocol: protocol.negotiated
          }
        )
 
        if (isNotification(rpcRequest)) {
          return reply.status(202).send()
        }
 
        // Extract session ID for header (MCP 2025-11-25: return in MCP-Session-Id header)
        const sessionId = isInitialize && result && typeof result === 'object' && 'sessionId' in result
          ? (result as { sessionId?: string }).sessionId
          : undefined
 
        if (sessionId) {
          reply.header(MCP_SESSION_ID_HEADER, sessionId)
        }
 
        const response = buildJsonRpcResult(rpcRequest.id ?? null, result)
        if (wantsStream) {
          const eventId = primeEventId()
          reply
            .header('Content-Type', 'text/event-stream')
            .header('Cache-Control', 'no-cache')
            .header('Connection', 'keep-alive')
            .send(`id: ${eventId}\n\n${serializeSseEvent(response, eventId)}`)
          return
        }
 
        return reply.send(response)
      } catch (error) {
        // Log notification errors before returning 202 (P3 fix)
        if (isNotification(rpcRequest)) {
          request.log.error(error, 'MCP notification processing error')
          return reply.status(202).send()
        }
 
        request.log.error(error, 'MCP RPC error')
        const code = (error as any)?.code ?? -32603
        const data = (error as any)?.data
        const message = (error as Error).message || 'MCP request failed'
        const rpcError = buildJsonRpcError(rpcRequest.id ?? null, code, message, data)
 
        if (wantsStream) {
          const eventId = primeEventId()
          reply
            .header('Content-Type', 'text/event-stream')
            .header('Cache-Control', 'no-cache')
            .header('Connection', 'keep-alive')
            .send(`id: ${eventId}\n\n${serializeSseEvent(rpcError, eventId)}`)
          return
        }
 
        return reply.send(rpcError)
      }
    })
 
    fastify.get(`${mcpBasePath}`, async (request: FastifyRequest, reply: FastifyReply) => {
      const eventId = primeEventId()
      reply.raw.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        Connection: 'keep-alive'
      })
 
      reply.raw.write(serializeSseEvent({
        jsonrpc: '2.0',
        method: 'mcp/ready',
        params: { protocol: 'streamable-http' }
      }, eventId, 15000))
 
      const keepAlive = setInterval(() => {
        reply.raw.write(': keep-alive\n\n')
      }, 15000)
 
      request.raw.on('close', () => {
        clearInterval(keepAlive)
      })
    })
 
    /**
     * DELETE handler for session termination (MCP 2025-11-25)
     * Clients SHOULD send DELETE to terminate sessions
     */
    fastify.delete(`${mcpBasePath}`, async (_request: FastifyRequest, reply: FastifyReply) => {
      // For now, return 405 Method Not Allowed as we don't track sessions server-side
      // A full implementation would track sessions and clean up resources here
      return reply.status(405).send({ error: 'Session termination not supported' })
    })
 
  }
 
  // Global error handler
  fastify.setErrorHandler(async (error, request, reply) => {
    request.log.error(error, 'Fastify cube adapter error')
 
    Eif (reply.statusCode < 400) {
      reply.status(500)
    }
 
    const errorArg = error instanceof Error ? error : String(error)
    return formatErrorResponse(errorArg, reply.statusCode)
  })
 
  done()
}
 
/**
 * Helper function to register cube routes on an existing Fastify instance
 */
export async function registerCubeRoutes(
  fastify: FastifyInstance,
  options: FastifyAdapterOptions
): Promise<void> {
  await fastify.register(cubePlugin as any, options)
}
 
/**
 * Create a complete Fastify instance with Cube.js routes
 * 
 * @example
 * const app = createCubeApp({
 *   cubes: [salesCube, employeesCube],
 *   drizzle: db,
 *   schema,
 *   extractSecurityContext: async (request) => {
 *     const token = request.headers.authorization?.replace('Bearer ', '')
 *     const decoded = await verifyJWT(token)
 *     return { organisationId: decoded.orgId, userId: decoded.userId }
 *   }
 * })
 */
export function createCubeApp(
  options: FastifyAdapterOptions
): FastifyInstance {
  const fastify = require('fastify')({
    logger: true
  })
  
  fastify.register(cubePlugin as any, options)
  
  return fastify
}
 
// Re-export types for convenience
export type { SecurityContext, DatabaseExecutor, SemanticQuery, DrizzleDatabase, FastifyCorsOptions }