Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
28.3 KB
Raw Blame
/**
 * MCP Server — StreamableHTTP on :port/mcp/v1.
 *
 * Follows the pattern from tests/e2e/fixtures/mock-mcp-server/src/index.ts
 * with session management and health endpoint.
 *
 * Source of truth: PHASE-4-MCP-SERVER-INTERFACE.md §5.3
 */
import * as k8s from '@kubernetes/client-node'
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
import http from 'node:http'
import { z } from 'zod/v3'
import { loadConfig } from '../config'
import { WorkflowRecipeProvider } from '../k8sClient'
import { registry } from '../metrics'
import { HttpMcpHostClient } from '../workflow/httpMcpHostClient'
import { JwtTokenFactory } from '../workflow/jwtTokenFactory'
import { K8sSecretReaderImpl } from '../workflow/k8sSecretReaderImpl'
import { ModelConfigHandler, type PluginSdkCredentialTarget } from '../workflow/modelConfigHandler'
import { createWorkflowEndpointHandlers, verifyIncomingToken } from '../workflow/restEndpoints'
import {
  verifyPluginSdkBrokerCallerToken,
  verifyPluginSdkCredentialTicket,
} from '../workflow/workflowAuth'
import {
  CallerIdentity,
  handleDeleteRecipe,
  handleDeployRecipe,
  handleGetRecipeStatus,
  handleListPolicies,
  handleListRecipes,
  handleRollbackRecipe,
  handleSearchRegistry,
  handleValidateRecipe,
} from './handlers'

const MAX_SESSIONS = 100
// Status reports can include full step output (research steps produce 50-200KB).
// Previous 64KB limit caused `req.destroy()` → coordinator received `socket hang up`
// instead of a proper 413 response, triggering false step retries.
const MAX_BODY_BYTES = 512 * 1024 // 512KB
const CONTROL_API_BASE_URL =
  process.env.CONTROL_API_BASE_URL || 'http://control-api.control-plane.svc.cluster.local:8090'

/**
 * Bind a credential request to the already verified signed-ticket target.
 * Callers may echo the target for diagnostics, but the resolver must receive
 * only these ticket claims. A mismatch is denied before any Secret lookup.
 */
export function bindPluginSdkCredentialTarget(
  ticketTarget: PluginSdkCredentialTarget,
  bodyTarget: PluginSdkCredentialTarget
): PluginSdkCredentialTarget | null {
  if (
    ticketTarget.targetRef !== bodyTarget.targetRef ||
    ticketTarget.provider !== bodyTarget.provider ||
    ticketTarget.model !== bodyTarget.model ||
    ticketTarget.credentialSlot !== bodyTarget.credentialSlot
  ) {
    return null
  }
  return { ...ticketTarget }
}

/**
 * The request may echo the target for diagnostics, but this predicate is
 * never an authority source. The signed ticket remains the only value used by
 * revalidation and Secret resolution (see the broker route below).
 */
export function pluginSdkCredentialTargetEchoMatches(
  signedTarget: PluginSdkCredentialTarget,
  bodyTarget: PluginSdkCredentialTarget
): boolean {
  return (
    signedTarget.targetRef === bodyTarget.targetRef &&
    signedTarget.provider === bodyTarget.provider &&
    signedTarget.model === bodyTarget.model &&
    signedTarget.credentialSlot === bodyTarget.credentialSlot
  )
}

export async function revalidatePluginSdkCredentialTicket(input: {
  runtimeToken: string
  credentialTicket: string
  invocationId: string
  targetRef: string
  attemptGeneration: number
  providerAttemptId: string
  providerAttemptIndex: number
  /** Consume the control-plane jti after the Secret read, not during preflight. */
  redeem?: boolean
  fetchImpl?: typeof fetch
  controlApiBaseUrl?: string
}): Promise<boolean> {
  const fetchImpl = input.fetchImpl ?? fetch
  try {
    const response = await fetchImpl(
      `${(input.controlApiBaseUrl ?? CONTROL_API_BASE_URL).replace(/\/+$/, '')}/api/v1/mcp-host/plugin-workload-sdk/credential-ticket/introspect`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${input.runtimeToken}`,
        },
        body: JSON.stringify({
          credentialTicket: input.credentialTicket,
          invocationId: input.invocationId,
          targetRef: input.targetRef,
          attemptGeneration: input.attemptGeneration,
          providerAttemptId: input.providerAttemptId,
          providerAttemptIndex: input.providerAttemptIndex,
          ...(input.redeem ? { redeem: true } : {}),
        }),
      }
    )
    if (!response.ok) return false
    const body = (await response.json().catch(() => null)) as { active?: unknown } | null
    return body?.active === true
  } catch {
    return false
  }
}

type ParseResult =
  | { ok: true; body: Record<string, unknown> }
  | { ok: false; reason: 'too_large' | 'invalid_json' | 'stream_error' }

export function parseJsonBody(req: http.IncomingMessage): Promise<ParseResult> {
  return new Promise(resolve => {
    let data = ''
    let size = 0
    let settled = false
    req.on('data', (chunk: Buffer) => {
      if (settled) return
      size += chunk.length
      if (size > MAX_BODY_BYTES) {
        settled = true
        resolve({ ok: false, reason: 'too_large' })
        req.destroy()
        return
      }
      data += chunk.toString()
    })
    req.on('end', () => {
      if (settled) return
      settled = true
      try {
        const parsed: unknown = JSON.parse(data)
        if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
          resolve({ ok: false, reason: 'invalid_json' })
          return
        }
        resolve({ ok: true, body: parsed as Record<string, unknown> })
      } catch {
        resolve({ ok: false, reason: 'invalid_json' })
      }
    })
    req.on('error', () => {
      if (!settled) {
        settled = true
        resolve({ ok: false, reason: 'stream_error' })
      }
    })
  })
}

export class ClerumMcpServer {
  private httpServer: http.Server | null = null
  private sessions: Map<string, StreamableHTTPServerTransport> = new Map()
  /** One-shot broker redemption cache; tickets are short-lived (60s). */
  private readonly consumedPluginSdkTicketJtis = new Map<string, number>()
  private provider: WorkflowRecipeProvider
  private port: number
  private customApi: k8s.CustomObjectsApi
  private namespace: string
  private sandboxNamespace: string
  private workflowHandlers: ReturnType<typeof createWorkflowEndpointHandlers> | null = null
  private modelConfigHandler: ModelConfigHandler | null
  private tokenFactory: JwtTokenFactory | null

  constructor(
    provider: WorkflowRecipeProvider,
    port: number,
    customApi: k8s.CustomObjectsApi,
    namespace: string,
    kc?: k8s.KubeConfig,
    sandboxNamespace = 'sandbox-recipes',
    tokenFactory?: JwtTokenFactory
  ) {
    this.provider = provider
    this.port = port
    this.customApi = customApi
    this.namespace = namespace
    this.sandboxNamespace = sandboxNamespace
    this.tokenFactory = tokenFactory ?? null

    // Wire ModelConfigHandler DI — K8sSecretReader + McpHostClient
    const coreApi = kc ? kc.makeApiClient(k8s.CoreV1Api) : null
    const k8sReader = coreApi ? new K8sSecretReaderImpl(coreApi) : null
    const mcpHostClient = new HttpMcpHostClient()
    // Handler requires K8sSecretReader; if unavailable (dev mode), configureModel returns 501.
    // The Grok flag keeps `grantRedeemable` in step with the recipe verdict.
    this.modelConfigHandler = k8sReader
      ? new ModelConfigHandler(k8sReader, mcpHostClient, undefined, {
          grokSubscriptionEnabled: loadConfig().grokSubscriptionEnabled,
        })
      : null
  }

  private consumePluginSdkTicket(jti: string): boolean {
    const now = Date.now()
    for (const [entry, expiresAt] of this.consumedPluginSdkTicketJtis) {
      if (expiresAt <= now) this.consumedPluginSdkTicketJtis.delete(entry)
    }
    const existing = this.consumedPluginSdkTicketJtis.get(jti)
    if (existing !== undefined && existing > now) return false
    // Keep the cache bounded even if a compromised host floods distinct
    // signed tickets within their TTL.
    if (this.consumedPluginSdkTicketJtis.size >= 10_000) {
      const oldest = this.consumedPluginSdkTicketJtis.keys().next().value
      if (typeof oldest === 'string') this.consumedPluginSdkTicketJtis.delete(oldest)
    }
    this.consumedPluginSdkTicketJtis.set(jti, now + 60_000)
    return true
  }

  private createMcpServer(): McpServer {
    const server = new McpServer({
      name: 'workflow-recipes',
      version: '0.1.0',
    })

    const provider = this.provider

    // Identity headers are extracted from the HTTP request before
    // the MCP transport processes it. For unit-testable handlers,
    // we pass a default identity here — real header validation
    // happens at the HTTP layer in production (Phase 5+).
    const defaultIdentity: CallerIdentity = { agentId: 'unknown', contextRef: 'unknown' }

    server.tool(
      'deploy_recipe',
      'Deploy a WorkflowRecipe (optional version for registry)',
      {
        recipe_name: z.string().describe('Name of the WorkflowRecipe to deploy'),
        namespace: z.string().optional().describe('Target namespace'),
        version: z.string().optional().describe('Specific version from registry'),
      },
      async ({
        recipe_name,
        namespace,
        version,
      }: {
        recipe_name: string
        namespace?: string
        version?: string
      }) => {
        return handleDeployRecipe(
          { recipe_name, namespace, version },
          provider,
          defaultIdentity,
          this.namespace
        )
      }
    )

    server.tool(
      'list_recipes',
      'List all WorkflowRecipes with optional status filter',
      {
        status_filter: z.string().optional().describe('Filter by recipe phase'),
      },
      async ({ status_filter }: { status_filter?: string }) => {
        return handleListRecipes({ status_filter }, provider)
      }
    )

    server.tool(
      'get_recipe_status',
      'Get detailed status of a WorkflowRecipe',
      {
        name: z.string().describe('Name of the WorkflowRecipe'),
      },
      async ({ name }: { name: string }) => {
        return handleGetRecipeStatus({ name }, provider)
      }
    )

    server.tool(
      'rollback_recipe',
      'Trigger rollback on a WorkflowRecipe',
      {
        name: z.string().describe('Name of the WorkflowRecipe to rollback'),
        version: z.number().optional().describe('Target version to rollback to'),
      },
      async ({ name, version }: { name: string; version?: number }) => {
        return handleRollbackRecipe({ name, version }, provider)
      }
    )

    server.tool(
      'delete_recipe',
      'Delete a WorkflowRecipe and its managed resources',
      {
        name: z.string().describe('Name of the WorkflowRecipe to delete'),
      },
      async ({ name }: { name: string }) => {
        return handleDeleteRecipe({ name }, provider)
      }
    )

    server.tool(
      'validate_recipe',
      'Validate WorkflowRecipe YAML without deploying',
      {
        recipe_yaml: z.string().describe('WorkflowRecipe JSON string to validate'),
      },
      async ({ recipe_yaml }: { recipe_yaml: string }) => {
        return handleValidateRecipe({ recipe_yaml })
      }
    )

    server.tool(
      'search_registry',
      'Search the WorkflowRecipe registry',
      {
        query: z.string().optional().describe('Search query'),
        category: z.string().optional().describe('Filter by category'),
      },
      async ({ query, category }: { query?: string; category?: string }) => {
        return handleSearchRegistry({ query, category })
      }
    )

    const customApi = this.customApi
    const namespace = this.namespace

    server.tool('list_policies', 'List active WorkflowRecipePolicies', {}, async () => {
      return handleListPolicies(customApi, namespace)
    })

    return server
  }

  /**
   * Handle the ordinary workflow REST surface after the route name has been
   * bound to a verified JWT. Keeping this branch separate from the SDK
   * credential broker makes the broker's path guard an early abort rather
   * than a user-controlled condition around Secret resolution.
   */
  private async handleStandardWorkflowRestRequest(
    req: http.IncomingMessage,
    res: http.ServerResponse,
    routeRecipeName: string,
    subPath: string
  ): Promise<void> {
    const authHeader = req.headers.authorization
    const token = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''
    let claims
    try {
      claims = await verifyIncomingToken(token)
    } catch {
      // Do not reflect the request URL or parser error in logs: both can carry
      // attacker-controlled control characters or format tokens. The stable
      // event is sufficient for auth telemetry and avoids log/format injection.
      console.error('[WRC-AUTH] Token verification failed')
      res.writeHead(401, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Unauthorized' }))
      return
    }

    // The URL is only a routing hint. Every workflow operation below uses
    // the recipe identity from the verified token after this binding check;
    // no path-controlled value reaches a handler or Kubernetes resolver.
    if (claims.recipeName !== routeRecipeName || claims.recipeNamespace !== this.sandboxNamespace) {
      res.writeHead(403, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Workflow recipe binding mismatch' }))
      return
    }
    const recipeName = claims.recipeName

    if (!this.workflowHandlers) {
      this.workflowHandlers = createWorkflowEndpointHandlers(
        this.customApi,
        this.sandboxNamespace,
        this.tokenFactory ?? undefined,
        { traceReporter: this.provider.getTraceReporter() }
      )
    }
    const handlers = this.workflowHandlers

    const artifactMatch = subPath.match(/^\/artifacts\/([^/]+)$/)
    if (req.method === 'GET' && artifactMatch) {
      const filename = decodeURIComponent(artifactMatch[1])
      const result = await handlers.getArtifact(recipeName, filename, claims)
      if (result.status === 200 && Buffer.isBuffer(result.body)) {
        res.writeHead(200, result.headers ?? { 'Content-Type': 'application/octet-stream' })
        res.end(result.body)
      } else {
        res.writeHead(result.status, { 'Content-Type': 'application/json' })
        res.end(JSON.stringify(result.body))
      }
      return
    }

    if (req.method === 'DELETE' && artifactMatch) {
      const filename = decodeURIComponent(artifactMatch[1])
      const result = await handlers.deleteArtifactFile(recipeName, filename, claims)
      res.writeHead(result.status, { 'Content-Type': 'application/json' })
      res.end(result.status === 204 ? '' : JSON.stringify(result.body))
      return
    }

    if (req.method === 'DELETE' && subPath === '/artifacts') {
      const result = await handlers.deleteArtifact(recipeName, claims)
      res.writeHead(result.status, { 'Content-Type': 'application/json' })
      res.end(result.status === 204 ? '' : JSON.stringify(result.body))
      return
    }

    if (req.method === 'GET' && subPath === '/status') {
      const result = await handlers.getWorkflowStatus(recipeName, claims)
      res.writeHead(result.status, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify(result.body))
      return
    }

    if (req.method === 'GET' && subPath === '/health') {
      const result = await handlers.getHealth(recipeName, claims)
      res.writeHead(result.status, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify(result.body))
      return
    }

    if (req.method === 'GET' && subPath === '/signals') {
      const result = await handlers.getSignals(recipeName, claims)
      res.writeHead(result.status, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify(result.body))
      return
    }

    if (req.method === 'POST') {
      const parseResult = await parseJsonBody(req)
      if (!parseResult.ok) {
        const status = parseResult.reason === 'too_large' ? 413 : 400
        const error =
          parseResult.reason === 'too_large' ? 'Request body too large' : 'Invalid JSON body'
        res.writeHead(status, { 'Content-Type': 'application/json' })
        res.end(JSON.stringify({ error }))
        return
      }
      const body = parseResult.body

      if (subPath === '/status') {
        const result = await handlers.postStepStatus(recipeName, claims, body as never)
        res.writeHead(result.status, { 'Content-Type': 'application/json' })
        res.end(JSON.stringify(result.body))
        return
      }

      if (subPath === '/configure-model') {
        const result = await handlers.configureModel(
          recipeName,
          claims,
          body as never,
          this.modelConfigHandler ?? undefined
        )
        res.writeHead(result.status, { 'Content-Type': 'application/json' })
        res.end(JSON.stringify(result.body))
        return
      }

      if (subPath === '/injections/model') {
        const result = await handlers.requestModelInjection(
          recipeName,
          claims,
          body as never,
          this.modelConfigHandler ?? undefined
        )
        res.writeHead(result.status, { 'Content-Type': 'application/json' })
        res.end(JSON.stringify(result.body))
        return
      }
    }

    res.writeHead(404, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify({ error: 'Not found' }))
  }

  private async handleHttpRequest(
    req: http.IncomingMessage,
    res: http.ServerResponse
  ): Promise<void> {
    const url = req.url ?? ''
    const sessions = this.sessions

    // Health endpoint
    if (url === '/health' && req.method === 'GET') {
      res.writeHead(200, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ status: 'ok' }))
      return
    }

    // Prometheus metrics
    if (url === '/metrics' && req.method === 'GET') {
      const metrics = await registry.metrics()
      res.writeHead(200, { 'Content-Type': registry.contentType })
      res.end(metrics)
      return
    }

    // MCP endpoint
    if (url === '/mcp/v1') {
      if (req.method === 'POST') {
        const sessionId = req.headers['mcp-session-id'] as string | undefined

        if (sessionId && sessions.has(sessionId)) {
          const transport = sessions.get(sessionId)!
          await transport.handleRequest(req, res)
        } else {
          // Reject if session limit reached — prevents unbounded memory growth
          if (sessions.size >= MAX_SESSIONS) {
            res.writeHead(503, { 'Content-Type': 'application/json' })
            res.end(JSON.stringify({ error: 'Too many active sessions', limit: MAX_SESSIONS }))
            return
          }

          // Create a NEW McpServer per session — the SDK requires one
          // connect() per McpServer lifetime (#MCP-SDK constraint).
          const sessionMcp = this.createMcpServer()
          const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined })
          await sessionMcp.connect(transport)
          await transport.handleRequest(req, res)

          const newSessionId = (transport as unknown as { sessionId?: string }).sessionId
          if (newSessionId) {
            sessions.set(newSessionId, transport)

            transport.onclose = () => {
              sessions.delete(newSessionId)
              sessionMcp.close().catch(() => {
                /* best-effort cleanup */
              })
              console.log(`[MCP-Server] Session ${newSessionId} closed (${sessions.size} active)`)
            }

            console.log(`[MCP-Server] New session ${newSessionId} (${sessions.size} active)`)
          }
        }
        return
      }

      if (req.method === 'DELETE') {
        const sessionId = req.headers['mcp-session-id'] as string | undefined
        if (sessionId && sessions.has(sessionId)) {
          const transport = sessions.get(sessionId)!
          await transport.handleRequest(req, res)
          sessions.delete(sessionId)
        } else {
          res.writeHead(404)
          res.end()
        }
        return
      }
    }

    // ─── Workflow REST API (/api/v1/workflow/:name/...) ──────────────
    const workflowMatch = url.match(/^\/api\/v1\/workflow\/([^/]+)(\/.*)?$/)
    if (!workflowMatch) {
      res.writeHead(404, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Not found' }))
      return
    }
    const routeRecipeName = decodeURIComponent(workflowMatch[1])
    const subPath = workflowMatch[2] ?? ''

    // SEC: validate the route label before any API call.
    // Prevents Host header injection and path traversal via crafted recipe names.
    if (!/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/.test(routeRecipeName)) {
      res.writeHead(400, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Invalid recipe name format' }))
      return
    }

    // The standard workflow branch is an early abort. The broker below is
    // reached only after this path/method guard, so a user-controlled URL does
    // not syntactically wrap the sensitive Secret-resolution operation.
    if (req.method !== 'POST' || subPath !== '/plugin-workload-sdk/credentials') {
      await this.handleStandardWorkflowRestRequest(req, res, routeRecipeName, subPath)
      return
    }

    // Plugin Workload SDK credential broker. This route deliberately uses a
    // different audience from the workflow REST API: an mcp-host runtime JWT
    // authenticates the caller and a second short-lived signed ticket binds
    // the exact target that control-api already authorized.
    const authHeader = req.headers.authorization
    const runtimeToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''
    let callerClaims
    try {
      callerClaims = await verifyPluginSdkBrokerCallerToken(runtimeToken)
    } catch {
      res.writeHead(401, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Unauthorized' }))
      return
    }
    const boundRecipeName = callerClaims.recipeName
    if (
      boundRecipeName !== routeRecipeName ||
      callerClaims.recipeNamespace !== this.sandboxNamespace ||
      !callerClaims.workflowControlScopes.includes('plugin-workload-sdk')
    ) {
      res.writeHead(403, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Credential broker scope denied' }))
      return
    }

    const parseResult = await parseJsonBody(req)
    if (!parseResult.ok) {
      res.writeHead(parseResult.reason === 'too_large' ? 413 : 400, {
        'Content-Type': 'application/json',
      })
      res.end(JSON.stringify({ error: 'Invalid credential broker request' }))
      return
    }
    const body = parseResult.body
    const target = body.target as PluginSdkCredentialTarget | undefined
    if (
      body.recipeNamespace !== this.sandboxNamespace ||
      typeof body.invocationId !== 'string' ||
      !Number.isInteger(body.attemptGeneration) ||
      Number(body.attemptGeneration) < 1 ||
      typeof body.providerAttemptId !== 'string' ||
      !body.providerAttemptId ||
      !Number.isInteger(body.providerAttemptIndex) ||
      Number(body.providerAttemptIndex) < 1 ||
      !target ||
      typeof target.targetRef !== 'string' ||
      typeof target.provider !== 'string' ||
      typeof target.model !== 'string' ||
      typeof target.credentialSlot !== 'string' ||
      typeof body.credentialTicket !== 'string'
    ) {
      res.writeHead(400, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Invalid credential broker request' }))
      return
    }

    let ticket
    try {
      ticket = await verifyPluginSdkCredentialTicket(body.credentialTicket)
    } catch {
      res.writeHead(403, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Credential ticket denied' }))
      return
    }
    // Derive the resolver target directly from the verified JWT claims.
    // `target` is an untrusted diagnostic echo and must not flow into any
    // policy, revalidation, or Secret-resolution operation.
    const signedTarget: PluginSdkCredentialTarget = {
      targetRef: ticket.targetRef,
      provider: ticket.provider,
      model: ticket.model,
      credentialSlot: ticket.credentialSlot,
    }
    if (
      ticket.recipeName !== boundRecipeName ||
      ticket.recipeNamespace !== this.sandboxNamespace ||
      ticket.invocationId !== body.invocationId ||
      ticket.attemptGeneration !== Number(body.attemptGeneration) ||
      ticket.providerAttemptId !== body.providerAttemptId ||
      ticket.providerAttemptIndex !== Number(body.providerAttemptIndex) ||
      !pluginSdkCredentialTargetEchoMatches(signedTarget, target)
    ) {
      res.writeHead(403, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Credential ticket denied' }))
      return
    }
    // The request body is only an equality check. Once the signed ticket
    // is verified, use its claims as the sole identity passed to the
    // Secret resolver and to all subsequent policy revalidation calls.
    const boundInvocationId = ticket.invocationId
    // TOCTOU gate: ticket signature proves what was authorized, while this
    // control-api read proves that the invocation and policy revision/hash
    // are still current immediately before the Secret lookup.
    const ticketStillActive = await revalidatePluginSdkCredentialTicket({
      runtimeToken,
      credentialTicket: body.credentialTicket,
      invocationId: boundInvocationId,
      targetRef: signedTarget.targetRef,
      attemptGeneration: ticket.attemptGeneration,
      providerAttemptId: ticket.providerAttemptId,
      providerAttemptIndex: ticket.providerAttemptIndex,
    })
    if (!ticketStillActive) {
      res.writeHead(403, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Credential ticket denied' }))
      return
    }
    if (!this.modelConfigHandler) {
      res.writeHead(503, { 'Content-Type': 'application/json' })
      res.end(JSON.stringify({ error: 'Credential broker unavailable' }))
      return
    }
    const result = await this.modelConfigHandler.resolvePluginSdkCredential(signedTarget)
    // Re-check after the Secret read as well as before it.  Control API
    // and the WRC Secret store are separate systems, so a single remote
    // check cannot be atomic with the read; the post-read gate ensures a
    // revocation observed during resolution never returns credentials.
    if (result.status === 200) {
      const ticketStillActiveAfterResolve = await revalidatePluginSdkCredentialTicket({
        runtimeToken,
        credentialTicket: body.credentialTicket,
        invocationId: boundInvocationId,
        targetRef: signedTarget.targetRef,
        attemptGeneration: ticket.attemptGeneration,
        providerAttemptId: ticket.providerAttemptId,
        providerAttemptIndex: ticket.providerAttemptIndex,
        redeem: true,
      })
      if (!ticketStillActiveAfterResolve) {
        res.writeHead(403, { 'Content-Type': 'application/json' })
        res.end(JSON.stringify({ error: 'Credential ticket denied' }))
        return
      }
      if (!this.consumePluginSdkTicket(ticket.jti)) {
        res.writeHead(403, { 'Content-Type': 'application/json' })
        res.end(JSON.stringify({ error: 'Credential ticket denied' }))
        return
      }
    }
    res.writeHead(result.status, { 'Content-Type': 'application/json' })
    res.end(JSON.stringify(result.body))
    return
  }

  async start(): Promise<void> {
    this.httpServer = http.createServer((req, res) => {
      this.handleHttpRequest(req, res).catch((error: unknown) => {
        console.error('[MCP-Server] Unhandled error in request handler:', error)
        if (!res.headersSent) {
          res.writeHead(500, { 'Content-Type': 'application/json' })
          res.end(JSON.stringify({ error: 'Internal server error' }))
        }
      })
    })

    return new Promise<void>(resolve => {
      this.httpServer!.listen(this.port, () => {
        console.log(`[MCP-Server] Listening on :${this.port}`)
        console.log(`[MCP-Server] MCP endpoint: POST /mcp/v1`)
        console.log(`[MCP-Server] Health endpoint: GET /health`)
        resolve()
      })
    })
  }

  async stop(): Promise<void> {
    for (const [id, transport] of this.sessions) {
      try {
        await transport.close()
      } catch {
        // Ignore close errors during shutdown
      }
      this.sessions.delete(id)
    }

    return new Promise<void>(resolve => {
      if (this.httpServer) {
        this.httpServer.close(() => {
          console.log('[MCP-Server] HTTP server closed')
          resolve()
        })
      } else {
        resolve()
      }
    })
  }

  getSessionCount(): number {
    return this.sessions.size
  }
}