All files adapters/mcp-transport.ts

97.76% Statements 131/134
89.16% Branches 107/120
100% Functions 27/27
99.15% Lines 118/119

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                                                                                                              20x 20x     28x 28x 28x               40x 44x 32x 32x   32x           20x         20x                 32x 40x 28x 36x 24x                                                     36x     36x 12x 8x   4x       24x 8x         16x 16x   4x       12x 20x 20x         12x 8x     4x       24x 24x 8x   24x 4x   24x 24x 24x 24x       20x               16x               36x 20x 20x 8x           8x               120x 120x 120x   120x       16x     16x   4x     12x     16x                                                 16x       28x     4x 8x                   4x     8x 12x 8x 8x                       4x 16x         4x           4x     8x 20x 8x 8x               4x   8x 8x 4x   4x     8x 8x 4x   4x 4x     4x         40x 40x 40x 4x   40x       48x 36x 16x   20x       20x       32x       16x                                                                                                                                                                                                       28x 28x 28x 4x   24x 24x   4x   8x 8x 4x     8x 8x 4x 4x     4x         12x                                 20x   20x                                                                                                                                                                                                                   28x       28x    
import type { SemanticLayerCompiler, SecurityContext } from '../server'
import { getDefaultMCPPrompts, type MCPPrompt } from '../server/ai/mcp-prompts'
import {
  handleDiscover,
  handleValidate,
  handleLoad,
  generateRequestId,
  type DiscoverRequest,
  type ValidateRequest,
  type LoadRequest
} from './utils'
 
// Re-export MCPPrompt for external consumers
export { type MCPPrompt }
 
export type JsonRpcId = string | number | null | undefined
 
export interface JsonRpcRequest {
  jsonrpc: '2.0'
  id?: JsonRpcId
  method: string
  params?: unknown
}
 
export interface JsonRpcResponse {
  jsonrpc: '2.0'
  id: JsonRpcId
  result?: unknown
  error?: { code: number; message: string; data?: unknown }
}
 
export interface McpDispatchContext {
  semanticLayer: SemanticLayerCompiler
  extractSecurityContext: (req: any, res: any) => SecurityContext | Promise<SecurityContext>
  rawRequest: unknown
  rawResponse: unknown
  negotiatedProtocol?: string | null
  resources?: MCPResource[]
  prompts?: MCPPrompt[]
}
 
export interface MCPResource {
  uri: string
  name: string
  description: string
  mimeType: string
  text: string
}
 
export interface ProtocolNegotiation {
  ok: boolean
  negotiated: string | null
  supported: string[]
}
 
export const SUPPORTED_MCP_PROTOCOLS = ['2025-11-25', '2025-06-18', '2025-03-26']
export const DEFAULT_MCP_PROTOCOL = '2025-11-25'
 
export function negotiateProtocol(headers: Record<string, string | string[] | undefined>): ProtocolNegotiation {
  const requested = normalizeHeader(headers['mcp-protocol-version'])
  const negotiated = requested || DEFAULT_MCP_PROTOCOL
  return {
    ok: SUPPORTED_MCP_PROTOCOLS.includes(negotiated),
    negotiated: SUPPORTED_MCP_PROTOCOLS.includes(negotiated) ? negotiated : null,
    supported: SUPPORTED_MCP_PROTOCOLS
  }
}
 
export function wantsEventStream(accept: string | null | undefined): boolean {
  if (!accept) return false
  const values = accept.split(',').map(v => v.trim().toLowerCase())
  const hasSse = values.includes('text/event-stream')
  const hasJson = values.includes('application/json')
  // Prefer JSON when both are offered; stream only when client explicitly prefers SSE
  return hasSse && !hasJson
}
 
/**
 * MCP Session ID header name (per 2025-11-25 spec)
 */
export const MCP_SESSION_ID_HEADER = 'mcp-session-id'
 
/**
 * MCP Protocol Version header name (per 2025-11-25 spec)
 */
export const MCP_PROTOCOL_VERSION_HEADER = 'mcp-protocol-version'
 
/**
 * Validate the Accept header per MCP 2025-11-25 spec.
 * Client MUST include both `application/json` and `text/event-stream` as supported content types.
 *
 * @returns true if valid, false if invalid
 */
export function validateAcceptHeader(accept: string | null | undefined): boolean {
  if (!accept) return false
  const values = accept.split(',').map(v => v.trim().toLowerCase().split(';')[0])
  const hasJson = values.some(v => v === 'application/json')
  const hasSse = values.some(v => v === 'text/event-stream')
  return hasJson && hasSse
}
 
export interface OriginValidationOptions {
  /**
   * List of allowed origins (e.g., ['http://localhost:3000', 'https://myapp.com'])
   * If not provided, defaults to localhost origins only
   */
  allowedOrigins?: string[]
  /**
   * If true, allows requests without an Origin header (non-browser clients)
   * @default true
   */
  allowMissingOrigin?: boolean
}
 
/**
 * Validate the Origin header per MCP 2025-11-25 spec.
 * Servers MUST validate Origin to prevent DNS rebinding attacks.
 * If Origin is present and invalid, MUST respond with 403 Forbidden.
 *
 * @returns { valid: true } if allowed, or { valid: false, reason: string } if blocked
 */
export function validateOriginHeader(
  origin: string | null | undefined,
  options: OriginValidationOptions = {}
): { valid: true } | { valid: false; reason: string } {
  const { allowMissingOrigin = true, allowedOrigins } = options
 
  // No Origin header - typically non-browser clients (curl, Postman, etc.)
  if (!origin) {
    if (allowMissingOrigin) {
      return { valid: true }
    }
    return { valid: false, reason: 'Origin header is required' }
  }
 
  // If no allowedOrigins configured, allow all origins (permissive mode)
  if (!allowedOrigins || allowedOrigins.length === 0) {
    return { valid: true }
  }
 
  // Parse the origin
  let parsedOrigin: URL
  try {
    parsedOrigin = new URL(origin)
  } catch {
    return { valid: false, reason: 'Invalid Origin header format' }
  }
 
  // Check against explicit allowed origins
  const normalized = allowedOrigins.map(o => {
    try {
      return new URL(o).origin
    } catch {
      return o
    }
  })
  if (normalized.includes(parsedOrigin.origin)) {
    return { valid: true }
  }
 
  return { valid: false, reason: 'Origin not in allowed list' }
}
 
export function serializeSseEvent(payload: unknown, eventId?: string, retryMs?: number): string {
  const lines: string[] = []
  if (eventId) {
    lines.push(`id: ${eventId}`)
  }
  if (retryMs && retryMs > 0) {
    lines.push(`retry: ${retryMs}`)
  }
  lines.push(`event: message`)
  lines.push(`data: ${JSON.stringify(payload)}`)
  lines.push('')
  return lines.join('\n')
}
 
export function buildJsonRpcError(id: JsonRpcId, code: number, message: string, data?: unknown): JsonRpcResponse {
  return {
    jsonrpc: '2.0',
    id: id ?? null,
    error: { code, message, ...(data !== undefined ? { data } : {}) }
  }
}
 
export function buildJsonRpcResult(id: JsonRpcId, result: unknown): JsonRpcResponse {
  return {
    jsonrpc: '2.0',
    id: id ?? null,
    result
  }
}
 
export function parseJsonRpc(body: unknown): JsonRpcRequest | null {
  if (!body || typeof body !== 'object') return null
  const candidate = body as Record<string, unknown>
  if (candidate.jsonrpc !== '2.0' || typeof candidate.method !== 'string') return null
  const request: JsonRpcRequest = {
    jsonrpc: '2.0',
    method: candidate.method,
    id: candidate.id as JsonRpcId,
    params: candidate.params
  }
  return request
}
 
export async function dispatchMcpMethod(
  method: string,
  params: unknown,
  ctx: McpDispatchContext
): Promise<unknown> {
  const { semanticLayer, extractSecurityContext, rawRequest, rawResponse } = ctx
  const prompts = ctx.prompts ?? PROMPTS
  const resources = ctx.resources ?? RESOURCES
 
  switch (method) {
    case 'initialize': {
      // MCP 2025-11-25: Client sends protocolVersion in params
      // If we support it, respond with same version; otherwise respond with our latest supported
      const clientRequestedVersion = (params as any)?.protocolVersion as string | undefined
      let responseVersion: string
 
      if (clientRequestedVersion && SUPPORTED_MCP_PROTOCOLS.includes(clientRequestedVersion)) {
        // We support the client's requested version
        responseVersion = clientRequestedVersion
      } else {
        // Fall back to our latest supported version (client will disconnect if unsupported)
        responseVersion = DEFAULT_MCP_PROTOCOL
      }
 
      return {
        protocolVersion: responseVersion,
        capabilities: {
          tools: {
            listChanged: false
          },
          resources: {
            listChanged: false
          },
          prompts: {
            listChanged: false
          },
          sampling: {}
        },
        sessionId: primeEventId(),
        serverInfo: {
          name: 'drizzle-cube',
          // Use safe check for process.env to support edge runtimes (Cloudflare Workers, etc.)
          version: typeof process !== 'undefined' ? process.env?.npm_package_version || 'dev' : 'worker'
        }
      }
    }
 
    case 'list_tools':
    case 'tools/list':
      return { tools: buildToolList(), nextCursor: '' }
 
    case 'call_tool':
    case 'tools/call':
      return executeToolCall(params, ctx)
 
    case 'resources/list':
      return {
        resources: resources.map(({ uri, name, description, mimeType }) => ({
          uri,
          name,
          description,
          mimeType
        })),
        nextCursor: ''
      }
 
    case 'resources/templates/list':
      return { resourceTemplates: [], nextCursor: '' }
 
    case 'resources/read': {
      const uri = (params as any)?.uri as string | undefined
      const resource = resources.find(r => r.uri === uri) || resources[0]
      Iif (!resource) throw jsonRpcError(-32602, 'resource not found')
      return {
        contents: [
          {
            uri: resource.uri,
            mimeType: resource.mimeType,
            text: resource.text
          }
        ]
      }
    }
 
    case 'prompts/list':
      return {
        prompts: prompts.map(({ name, description }) => ({ name, description })),
        nextCursor: ''
      }
 
    case 'ping':
      return { }
 
    // Handle the initialized notification (sent by client after receiving InitializeResult)
    case 'notifications/initialized':
      // Client is indicating it's ready for normal operations
      // No response needed (this is a notification)
      return {}
 
    case 'prompts/get': {
      const name = (params as any)?.name as string | undefined
      const prompt = prompts.find(p => p.name === name) || prompts[0]
      Iif (!prompt) throw jsonRpcError(-32602, 'prompt not found')
      return {
        name: prompt.name,
        description: prompt.description,
        messages: prompt.messages
      }
    }
 
    case 'discover':
      return handleDiscover(semanticLayer, (params || {}) as DiscoverRequest)
    case 'validate': {
      const p = (params || {}) as ValidateRequest
      if (!p.query) {
        throw jsonRpcError(-32602, 'query is required')
      }
      return handleValidate(semanticLayer, p)
    }
    case 'load': {
      const p = (params || {}) as LoadRequest
      if (!p.query) {
        throw jsonRpcError(-32602, 'query is required')
      }
      const securityContext = await extractSecurityContext(rawRequest, rawResponse)
      return handleLoad(semanticLayer, securityContext, p)
    }
    default:
      throw jsonRpcError(-32601, `Unknown MCP method: ${method}`)
  }
}
 
export function jsonRpcError(code: number, message: string, data?: unknown): Error & { code: number; data?: unknown } {
  const err = new Error(message) as Error & { code: number; data?: unknown }
  err.code = code
  if (data !== undefined) {
    err.data = data
  }
  return err
}
 
export function normalizeHeader(value: string | string[] | undefined): string | null {
  if (!value) return null
  if (Array.isArray(value)) {
    return value[0] || null
  }
  return value
}
 
export function isNotification(request: JsonRpcRequest): boolean {
  return request.id === undefined || request.id === null
}
 
export function primeEventId(): string {
  return `evt-${generateRequestId()}`
}
 
function buildToolList() {
  return [
    {
      name: 'discover',
      description: `Find relevant cubes based on topic or intent. Call this FIRST to understand available data.
 
Returns cubes with:
- All measures and dimensions with their types
- Relationship information (joins) showing how cubes connect
- Metadata hints (eventStream for funnels, etc.)
 
IMPORTANT: The 'joins' property shows relationships between cubes. You can include dimensions from ANY related cube in your query - the system auto-joins them.
 
Example: If Productivity has a join to Employees, you can query:
{ "measures": ["Productivity.totalPullRequests"], "dimensions": ["Employees.name"] }`,
      inputSchema: {
        type: 'object',
        properties: {
          topic: { type: 'string', description: 'Keyword to search (e.g., "sales", "employees")' },
          intent: { type: 'string', description: 'Natural language goal (e.g., "analyze productivity trends")' },
          limit: { type: 'number', description: 'Max results (default: 10)' },
          minScore: { type: 'number', description: 'Min relevance 0-1 (default: 0.1)' }
        }
      }
    },
    {
      name: 'validate',
      description: `Validate a query and get auto-corrections for issues.
 
Checks:
- Field existence (measures, dimensions exist in schema)
- Filter syntax and operators
- Cross-cube join validity
 
Returns corrected query if issues found.`,
      inputSchema: {
        type: 'object',
        required: ['query'],
        properties: {
          query: {
            type: 'object',
            description: 'CubeQuery to validate'
          }
        }
      }
    },
    {
      name: 'load',
      description: `Execute a semantic query and return aggregated results.
 
QUERY CONSTRUCTION RULES:
 
1. CROSS-CUBE JOINS (use dimensions from related cubes!)
   Check 'joins' in discover results. Include dimensions from ANY related cube.
   Example - get employee names with their productivity:
   {
     "measures": ["Productivity.totalPullRequests"],
     "dimensions": ["Employees.name"],
     "filters": [{ "member": "Productivity.date", "operator": "inDateRange", "values": ["last 3 months"] }]
   }
 
2. DATE FILTERING vs TIME GROUPING
   For AGGREGATED TOTALS: use 'filters' with 'inDateRange' (NOT timeDimensions)
   {
     "measures": ["Productivity.totalPullRequests"],
     "dimensions": ["Employees.name"],
     "filters": [{ "member": "Productivity.date", "operator": "inDateRange", "values": ["last 3 months"] }],
     "order": { "Productivity.totalPullRequests": "desc" },
     "limit": 5
   }
 
   For TIME SERIES: use 'timeDimensions' WITH 'granularity'
   {
     "measures": ["Productivity.totalPullRequests"],
     "timeDimensions": [{ "dimension": "Productivity.date", "dateRange": "last 3 months", "granularity": "month" }]
   }
 
   WARNING: timeDimensions WITHOUT granularity groups by day, returning many rows!
 
3. TOP N PATTERN: filters + order + limit`,
      inputSchema: {
        type: 'object',
        required: ['query'],
        properties: {
          query: {
            type: 'object',
            description: `CubeQuery object with:
- measures: string[] - Aggregations (from any cube)
- dimensions: string[] - Grouping fields (can be from RELATED cubes via joins)
- filters: [{ member, operator, values }] - Use 'inDateRange' for date filtering
- timeDimensions: [{ dimension, granularity, dateRange }] - ONLY for time series
- order: { "Cube.field": "asc"|"desc" }
- limit: number`
          }
        }
      }
    }
  ]
}
 
async function executeToolCall(params: unknown, ctx: McpDispatchContext) {
  const { semanticLayer, extractSecurityContext, rawRequest, rawResponse } = ctx
  const p = (params || {}) as { name?: string; arguments?: unknown }
  if (!p.name) {
    throw jsonRpcError(-32602, 'name is required for tools/call')
  }
  const args = p.arguments
  switch (p.name) {
    case 'discover':
      return wrapContent(await handleDiscover(semanticLayer, (args || {}) as DiscoverRequest))
    case 'validate': {
      const body = (args || {}) as ValidateRequest
      if (!body.query) throw jsonRpcError(-32602, 'query is required')
      return wrapContent(await handleValidate(semanticLayer, body))
    }
    case 'load': {
      const body = (args || {}) as LoadRequest
      if (!body.query) throw jsonRpcError(-32602, 'query is required')
      const securityContext = await extractSecurityContext(rawRequest, rawResponse)
      return wrapContent(await handleLoad(semanticLayer, securityContext, body))
    }
    default:
      throw jsonRpcError(-32601, `Unknown tool: ${p.name}`)
  }
}
 
function wrapContent(result: unknown) {
  return {
    content: [
      {
        type: 'text' as const,
        text: typeof result === 'string' ? result : JSON.stringify(result)
      }
    ],
    isError: false
  }
}
 
// ---------------------------------------------
// Static prompts and resources for MCP clients
// Prompts are defined in src/server/ai/mcp-prompts.ts
// ---------------------------------------------
 
// Use prompts from AI module
const PROMPTS = getDefaultMCPPrompts()
 
const RESOURCES = [
  {
    uri: 'drizzle-cube://quickstart',
    name: 'Drizzle Cube MCP Quickstart',
    description: 'Minimal guide for using discover/suggest/validate/load',
    mimeType: 'text/markdown',
    text: [
      '# Drizzle Cube MCP Quickstart',
      '',
      'Tools:',
      '- discover: { topic?, intent?, limit?, minScore? } → cubes list',
      '- suggest: { naturalLanguage, cube? } → draft query',
      '- validate: { query } → corrected query + issues',
      '- load: { query } → data + annotation',
      '',
      'Recommended flow:',
      '1) tools/list',
      '2) tools/call name=discover intent="<goal>"',
      '3) tools/call name=suggest naturalLanguage="<goal>"',
      '4) tools/call name=validate query=<from suggest>',
      '5) tools/call name=load query=<validated>',
      '',
      'Query shapes supported:',
      '- regular Cube.js-style query { measures, dimensions, filters, timeDimensions, order, limit, offset }',
      '- funnel { bindingKey, timeDimension, steps[], includeTimeMetrics? }',
      '- flow { bindingKey, eventDimension, steps?, window? }',
      '- retention { bindingKey, timeDimension, periods, granularity, retentionType, breakdownDimensions }',
      '',
      'Filter rules: flat arrays of { member, operator, values }; do not nest arrays.'
    ].join('\n')
  },
  {
    uri: 'drizzle-cube://query-shapes',
    name: 'Query Shapes Reference',
    description: 'Detailed schema examples for regular, funnel, flow, and retention queries',
    mimeType: 'text/markdown',
    text: [
      '# Query Shapes',
      '',
      '## Regular query',
      '```json',
      '{',
      '  "measures": ["Sales.count"],',
      '  "dimensions": ["Sales.channel"],',
      '  "filters": [ { "member": "Sales.status", "operator": "equals", "values": ["paid"] } ],',
      '  "timeDimensions": [ { "dimension": "Sales.createdAt", "dateRange": "last 30 days", "granularity": "day" } ],',
      '  "order": { "Sales.createdAt": "asc" },',
      '  "limit": 500',
      '}',
      '```',
      '',
      '## Funnel',
      '```json',
      '{',
      '  "funnel": {',
      '    "bindingKey": "Events.userId",',
      '    "timeDimension": "Events.timestamp",',
      '    "steps": [',
      '      { "name": "Signup", "filter": [{ "member": "Events.eventType", "operator": "equals", "values": ["signup"] }] },',
      '      { "name": "Purchase", "filter": [{ "member": "Events.eventType", "operator": "equals", "values": ["purchase"] }] }',
      '    ],',
      '    "includeTimeMetrics": true',
      '  }',
      '}',
      '```',
      '',
      '## Flow',
      '```json',
      '{',
      '  "flow": {',
      '    "bindingKey": "Events.sessionId",',
      '    "eventDimension": "Events.eventType",',
      '    "steps": ["view", "add_to_cart", "checkout"],',
      '    "window": { "unit": "minute", "value": 30 }',
      '  }',
      '}',
      '```',
      '',
      '## Retention',
      '```json',
      '{',
      '  "retention": {',
      '    "bindingKey": "Users.id",',
      '    "timeDimension": "Events.timestamp",',
      '    "periods": 8,',
      '    "granularity": "week",',
      '    "retentionType": "rolling",',
      '    "breakdownDimensions": ["Events.country"]',
      '  }',
      '}',
      '```',
      '',
      '### Filter rules',
      '- Always a flat array of filter objects: [{ member, operator, values }]',
      '- For funnels, put time filter (inDateRange) only on step 0',
      '- Operators: equals, notEquals, inDateRange, gt, gte, lt, lte, contains, notContains, set, notSet',
      '',
      '### Time handling',
      '- Relative ranges ("last 3 months") -> add ONLY an inDateRange filter on the time dimension (do NOT add timeDimensions unless grouping is requested).',
      '- Grouping ("by month/week/day") -> add timeDimensions entry with granularity.',
      '- Both can be combined: inDateRange filter + timeDimensions granularity.'
    ].join('\n')
  }
]
 
export function getDefaultResources(): MCPResource[] {
  return RESOURCES
}
 
export function getDefaultPrompts(): MCPPrompt[] {
  return PROMPTS
}