asyncapi: '2.6.0'

info:
  title: MCP Service Events
  version: 1.0.0
  description: |
    AsyncAPI specification for the Model Context Protocol (MCP) service.
    mcp-svc handles workflow orchestration, tool execution, approval workflows,
    AI credit budget tracking, remote MCP server management, and marketplace operations.

    All events use CloudEvents 1.0 envelope format.
    Kafka partition key: tenant_id.
    Source identifier: eventzr.mcp-svc
  contact:
    name: EventZR Platform Team
  license:
    name: Proprietary

servers:
  staging:
    url: boot-gpm4u49z.c2.kafka-serverless.us-east-1.amazonaws.com:9098
    protocol: kafka
    protocolVersion: '3.6'
    description: Amazon MSK Serverless (staging, us-east-1)
    security:
      - saslOauthbearer: []
    bindings:
      kafka:
        schemaRegistryUrl: false

defaultContentType: application/cloudevents+json

channels:
  # ===========================================================================
  # PRODUCED: Tool Events (6)
  # ===========================================================================
  eventzr.mcp.tool.registered.v1:
    description: Emitted when a new MCP tool is registered in the catalog.
    publish:
      operationId: publishToolRegistered
      summary: Tool registered
      message:
        $ref: '#/components/messages/ToolRegistered'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.tool.updated.v1:
    description: Emitted when an existing tool definition is updated.
    publish:
      operationId: publishToolUpdated
      summary: Tool updated
      message:
        $ref: '#/components/messages/ToolUpdated'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.tool.deprecated.v1:
    description: Emitted when a tool is marked as deprecated.
    publish:
      operationId: publishToolDeprecated
      summary: Tool deprecated
      message:
        $ref: '#/components/messages/ToolDeprecated'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.tool.deleted.v1:
    description: Emitted when a tool is permanently deleted.
    publish:
      operationId: publishToolDeleted
      summary: Tool deleted
      message:
        $ref: '#/components/messages/ToolDeleted'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.tool.published.v1:
    description: Emitted when a tool is published to the marketplace.
    publish:
      operationId: publishToolPublished
      summary: Tool published to marketplace
      message:
        $ref: '#/components/messages/ToolPublished'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.tool.purchased.v1:
    description: Emitted when a tenant purchases a marketplace tool.
    publish:
      operationId: publishToolPurchased
      summary: Tool purchased from marketplace
      message:
        $ref: '#/components/messages/ToolPurchased'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  # ===========================================================================
  # PRODUCED: Tool Execution Events (5)
  # ===========================================================================
  eventzr.mcp.tool-execution.started.v1:
    description: Emitted when a tool execution begins.
    publish:
      operationId: publishToolExecutionStarted
      summary: Tool execution started
      message:
        $ref: '#/components/messages/ToolExecutionStarted'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.tool-execution.completed.v1:
    description: Emitted when a tool execution completes successfully.
    publish:
      operationId: publishToolExecutionCompleted
      summary: Tool execution completed
      message:
        $ref: '#/components/messages/ToolExecutionCompleted'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.tool-execution.failed.v1:
    description: Emitted when a tool execution fails with an error.
    publish:
      operationId: publishToolExecutionFailed
      summary: Tool execution failed
      message:
        $ref: '#/components/messages/ToolExecutionFailed'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.tool-execution.timeout.v1:
    description: Emitted when a tool execution exceeds its configured timeout.
    publish:
      operationId: publishToolExecutionTimeout
      summary: Tool execution timed out
      message:
        $ref: '#/components/messages/ToolExecutionTimeout'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.tool-execution.cancelled.v1:
    description: Emitted when a tool execution is cancelled by a user or system.
    publish:
      operationId: publishToolExecutionCancelled
      summary: Tool execution cancelled
      message:
        $ref: '#/components/messages/ToolExecutionCancelled'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  # ===========================================================================
  # PRODUCED: Workflow Events (5)
  # ===========================================================================
  eventzr.mcp.workflow.created.v1:
    description: Emitted when a new workflow definition is created.
    publish:
      operationId: publishWorkflowCreated
      summary: Workflow created
      message:
        $ref: '#/components/messages/WorkflowCreated'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow.updated.v1:
    description: Emitted when a workflow definition is updated.
    publish:
      operationId: publishWorkflowUpdated
      summary: Workflow updated
      message:
        $ref: '#/components/messages/WorkflowUpdated'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow.activated.v1:
    description: Emitted when a workflow is activated and becomes available for execution.
    publish:
      operationId: publishWorkflowActivated
      summary: Workflow activated
      message:
        $ref: '#/components/messages/WorkflowActivated'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow.deactivated.v1:
    description: Emitted when a workflow is deactivated and can no longer be executed.
    publish:
      operationId: publishWorkflowDeactivated
      summary: Workflow deactivated
      message:
        $ref: '#/components/messages/WorkflowDeactivated'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow.deleted.v1:
    description: Emitted when a workflow definition is permanently deleted.
    publish:
      operationId: publishWorkflowDeleted
      summary: Workflow deleted
      message:
        $ref: '#/components/messages/WorkflowDeleted'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  # ===========================================================================
  # PRODUCED: Workflow Execution Events (8)
  # ===========================================================================
  eventzr.mcp.workflow-execution.started.v1:
    description: Emitted when a workflow execution begins.
    publish:
      operationId: publishWorkflowExecutionStarted
      summary: Workflow execution started
      message:
        $ref: '#/components/messages/WorkflowExecutionStarted'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow-execution.step-completed.v1:
    description: Emitted when a single step within a workflow execution finishes.
    publish:
      operationId: publishWorkflowExecutionStepCompleted
      summary: Workflow step completed
      message:
        $ref: '#/components/messages/WorkflowExecutionStepCompleted'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow-execution.completed.v1:
    description: Emitted when all steps in a workflow execution have completed.
    publish:
      operationId: publishWorkflowExecutionCompleted
      summary: Workflow execution completed
      message:
        $ref: '#/components/messages/WorkflowExecutionCompleted'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow-execution.failed.v1:
    description: Emitted when a workflow execution fails at any step.
    publish:
      operationId: publishWorkflowExecutionFailed
      summary: Workflow execution failed
      message:
        $ref: '#/components/messages/WorkflowExecutionFailed'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow-execution.paused.v1:
    description: Emitted when a workflow execution is paused (e.g. budget exhaustion or manual pause).
    publish:
      operationId: publishWorkflowExecutionPaused
      summary: Workflow execution paused
      message:
        $ref: '#/components/messages/WorkflowExecutionPaused'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow-execution.resumed.v1:
    description: Emitted when a previously paused workflow execution is resumed.
    publish:
      operationId: publishWorkflowExecutionResumed
      summary: Workflow execution resumed
      message:
        $ref: '#/components/messages/WorkflowExecutionResumed'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow-execution.cancelled.v1:
    description: Emitted when a workflow execution is cancelled by a user or system.
    publish:
      operationId: publishWorkflowExecutionCancelled
      summary: Workflow execution cancelled
      message:
        $ref: '#/components/messages/WorkflowExecutionCancelled'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.workflow-execution.rolled-back.v1:
    description: Emitted when a failed workflow execution has been rolled back to a checkpoint.
    publish:
      operationId: publishWorkflowExecutionRolledBack
      summary: Workflow execution rolled back
      message:
        $ref: '#/components/messages/WorkflowExecutionRolledBack'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  # ===========================================================================
  # PRODUCED: Budget Events (4)
  # ===========================================================================
  eventzr.mcp.budget.credit-consumed.v1:
    description: Emitted when AI credits are consumed from a tenant budget.
    publish:
      operationId: publishBudgetCreditConsumed
      summary: Budget credit consumed
      message:
        $ref: '#/components/messages/BudgetCreditConsumed'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.budget.credit-exceeded.v1:
    description: Emitted when a credit consumption attempt exceeds the budget limit.
    publish:
      operationId: publishBudgetCreditExceeded
      summary: Budget credit exceeded
      message:
        $ref: '#/components/messages/BudgetCreditExceeded'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.budget.credit-warning.v1:
    description: Emitted when budget usage crosses a warning or critical threshold.
    publish:
      operationId: publishBudgetCreditWarning
      summary: Budget credit warning
      message:
        $ref: '#/components/messages/BudgetCreditWarning'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.budget.period-reset.v1:
    description: Emitted when a budget period ends and usage counters are reset.
    publish:
      operationId: publishBudgetPeriodReset
      summary: Budget period reset
      message:
        $ref: '#/components/messages/BudgetPeriodReset'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  # ===========================================================================
  # PRODUCED: Approval Events (4)
  # ===========================================================================
  eventzr.mcp.approval.requested.v1:
    description: Emitted when approval is requested for a tool or workflow execution.
    publish:
      operationId: publishApprovalRequested
      summary: Approval requested
      message:
        $ref: '#/components/messages/ApprovalRequested'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.approval.approved.v1:
    description: Emitted when an approval request is granted.
    publish:
      operationId: publishApprovalApproved
      summary: Approval approved
      message:
        $ref: '#/components/messages/ApprovalApproved'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.approval.rejected.v1:
    description: Emitted when an approval request is rejected.
    publish:
      operationId: publishApprovalRejected
      summary: Approval rejected
      message:
        $ref: '#/components/messages/ApprovalRejected'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.approval.expired.v1:
    description: Emitted when an approval request expires without a decision.
    publish:
      operationId: publishApprovalExpired
      summary: Approval expired
      message:
        $ref: '#/components/messages/ApprovalExpired'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  # ===========================================================================
  # PRODUCED: Remote Server Events (3)
  # ===========================================================================
  eventzr.mcp.remote-server.registered.v1:
    description: Emitted when a remote MCP server is registered.
    publish:
      operationId: publishRemoteServerRegistered
      summary: Remote server registered
      message:
        $ref: '#/components/messages/RemoteServerRegistered'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.remote-server.health-changed.v1:
    description: Emitted when a remote MCP server health status changes.
    publish:
      operationId: publishRemoteServerHealthChanged
      summary: Remote server health changed
      message:
        $ref: '#/components/messages/RemoteServerHealthChanged'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  eventzr.mcp.remote-server.disconnected.v1:
    description: Emitted when a remote MCP server becomes disconnected.
    publish:
      operationId: publishRemoteServerDisconnected
      summary: Remote server disconnected
      message:
        $ref: '#/components/messages/RemoteServerDisconnected'
      bindings:
        kafka:
          clientId:
            type: string
            enum: [mcp-svc]

  # ===========================================================================
  # CONSUMED: Events from Other Services (4)
  # ===========================================================================
  eventzr.wallet.credit.updated.v1:
    description: |
      Consumed from wallet-svc. Triggers budget sync and may resume paused
      workflow executions when credits are replenished.
    subscribe:
      operationId: handleWalletCreditUpdated
      summary: Wallet credit updated
      message:
        $ref: '#/components/messages/WalletCreditUpdated'
      bindings:
        kafka:
          groupId:
            type: string
            enum: [mcp-svc-wallet-events]

  eventzr.aibrain.processing.completed.v1:
    description: |
      Consumed from aibrain-svc. Updates tool/workflow AI classification
      results and invalidates relevant caches.
    subscribe:
      operationId: handleAiBrainProcessingCompleted
      summary: AI Brain processing completed
      message:
        $ref: '#/components/messages/AiBrainProcessingCompleted'
      bindings:
        kafka:
          groupId:
            type: string
            enum: [mcp-svc-aibrain-events]

  eventzr.auth.tenant.created.v1:
    description: |
      Consumed from auth-svc. Creates default AI credit budget for new
      tenants and initializes tenant-specific configurations.
    subscribe:
      operationId: handleAuthTenantCreated
      summary: Auth tenant created
      message:
        $ref: '#/components/messages/AuthTenantCreated'
      bindings:
        kafka:
          groupId:
            type: string
            enum: [mcp-svc-auth-events]

  eventzr.taxonomy.category.updated.v1:
    description: |
      Consumed from taxonomy-svc. Refreshes category cache and updates
      tools/workflows that reference the changed category.
    subscribe:
      operationId: handleTaxonomyCategoryUpdated
      summary: Taxonomy category updated
      message:
        $ref: '#/components/messages/TaxonomyCategoryUpdated'
      bindings:
        kafka:
          groupId:
            type: string
            enum: [mcp-svc-taxonomy-events]

components:
  securitySchemes:
    saslOauthbearer:
      type: oauth2
      description: AWS MSK IAM authentication via SASL/OAUTHBEARER
      flows:
        clientCredentials:
          tokenUrl: https://sts.amazonaws.com
          scopes: {}

  messages:
    # =========================================================================
    # Tool Messages
    # =========================================================================
    ToolRegistered:
      name: ToolRegistered
      title: Tool Registered
      summary: A new MCP tool was registered in the catalog.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolRegisteredPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ToolUpdated:
      name: ToolUpdated
      title: Tool Updated
      summary: An existing tool definition was updated.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolUpdatedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ToolDeprecated:
      name: ToolDeprecated
      title: Tool Deprecated
      summary: A tool was marked as deprecated.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolDeprecatedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ToolDeleted:
      name: ToolDeleted
      title: Tool Deleted
      summary: A tool was permanently deleted.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolDeletedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ToolPublished:
      name: ToolPublished
      title: Tool Published
      summary: A tool was published to the marketplace.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolPublishedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ToolPurchased:
      name: ToolPurchased
      title: Tool Purchased
      summary: A tenant purchased a marketplace tool.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolPurchasedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    # =========================================================================
    # Tool Execution Messages
    # =========================================================================
    ToolExecutionStarted:
      name: ToolExecutionStarted
      title: Tool Execution Started
      summary: A tool execution has begun.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolExecutionStartedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ToolExecutionCompleted:
      name: ToolExecutionCompleted
      title: Tool Execution Completed
      summary: A tool execution completed successfully.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolExecutionCompletedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ToolExecutionFailed:
      name: ToolExecutionFailed
      title: Tool Execution Failed
      summary: A tool execution failed with an error.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolExecutionFailedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ToolExecutionTimeout:
      name: ToolExecutionTimeout
      title: Tool Execution Timeout
      summary: A tool execution exceeded its configured timeout.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolExecutionTimeoutPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ToolExecutionCancelled:
      name: ToolExecutionCancelled
      title: Tool Execution Cancelled
      summary: A tool execution was cancelled.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ToolExecutionCancelledPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    # =========================================================================
    # Workflow Messages
    # =========================================================================
    WorkflowCreated:
      name: WorkflowCreated
      title: Workflow Created
      summary: A new workflow definition was created.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowCreatedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowUpdated:
      name: WorkflowUpdated
      title: Workflow Updated
      summary: A workflow definition was updated.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowUpdatedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowActivated:
      name: WorkflowActivated
      title: Workflow Activated
      summary: A workflow was activated.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowActivatedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowDeactivated:
      name: WorkflowDeactivated
      title: Workflow Deactivated
      summary: A workflow was deactivated.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowDeactivatedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowDeleted:
      name: WorkflowDeleted
      title: Workflow Deleted
      summary: A workflow definition was permanently deleted.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowDeletedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    # =========================================================================
    # Workflow Execution Messages
    # =========================================================================
    WorkflowExecutionStarted:
      name: WorkflowExecutionStarted
      title: Workflow Execution Started
      summary: A workflow execution has begun.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowExecutionStartedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowExecutionStepCompleted:
      name: WorkflowExecutionStepCompleted
      title: Workflow Execution Step Completed
      summary: A single step within a workflow execution has finished.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowExecutionStepCompletedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowExecutionCompleted:
      name: WorkflowExecutionCompleted
      title: Workflow Execution Completed
      summary: All steps in a workflow execution completed.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowExecutionCompletedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowExecutionFailed:
      name: WorkflowExecutionFailed
      title: Workflow Execution Failed
      summary: A workflow execution failed at a step.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowExecutionFailedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowExecutionPaused:
      name: WorkflowExecutionPaused
      title: Workflow Execution Paused
      summary: A workflow execution was paused.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowExecutionPausedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowExecutionResumed:
      name: WorkflowExecutionResumed
      title: Workflow Execution Resumed
      summary: A paused workflow execution was resumed.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowExecutionResumedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowExecutionCancelled:
      name: WorkflowExecutionCancelled
      title: Workflow Execution Cancelled
      summary: A workflow execution was cancelled.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowExecutionCancelledPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    WorkflowExecutionRolledBack:
      name: WorkflowExecutionRolledBack
      title: Workflow Execution Rolled Back
      summary: A failed workflow execution was rolled back to a checkpoint.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WorkflowExecutionRolledBackPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    # =========================================================================
    # Budget Messages
    # =========================================================================
    BudgetCreditConsumed:
      name: BudgetCreditConsumed
      title: Budget Credit Consumed
      summary: AI credits were consumed from a tenant budget.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_BudgetCreditConsumedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    BudgetCreditExceeded:
      name: BudgetCreditExceeded
      title: Budget Credit Exceeded
      summary: A credit consumption attempt exceeded the budget limit.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_BudgetCreditExceededPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    BudgetCreditWarning:
      name: BudgetCreditWarning
      title: Budget Credit Warning
      summary: Budget usage crossed a warning or critical threshold.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_BudgetCreditWarningPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    BudgetPeriodReset:
      name: BudgetPeriodReset
      title: Budget Period Reset
      summary: A budget period ended and usage counters were reset.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_BudgetPeriodResetPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    # =========================================================================
    # Approval Messages
    # =========================================================================
    ApprovalRequested:
      name: ApprovalRequested
      title: Approval Requested
      summary: Approval was requested for a tool or workflow execution.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ApprovalRequestedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ApprovalApproved:
      name: ApprovalApproved
      title: Approval Approved
      summary: An approval request was granted.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ApprovalApprovedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ApprovalRejected:
      name: ApprovalRejected
      title: Approval Rejected
      summary: An approval request was rejected.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ApprovalRejectedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    ApprovalExpired:
      name: ApprovalExpired
      title: Approval Expired
      summary: An approval request expired without a decision.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_ApprovalExpiredPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    # =========================================================================
    # Remote Server Messages
    # =========================================================================
    RemoteServerRegistered:
      name: RemoteServerRegistered
      title: Remote Server Registered
      summary: A remote MCP server was registered.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_RemoteServerRegisteredPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    RemoteServerHealthChanged:
      name: RemoteServerHealthChanged
      title: Remote Server Health Changed
      summary: A remote MCP server health status changed.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_RemoteServerHealthChangedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    RemoteServerDisconnected:
      name: RemoteServerDisconnected
      title: Remote Server Disconnected
      summary: A remote MCP server became disconnected.
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_RemoteServerDisconnectedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    # =========================================================================
    # Consumed Messages from Other Services
    # =========================================================================
    WalletCreditUpdated:
      name: WalletCreditUpdated
      title: Wallet Credit Updated
      summary: Wallet balance changed (from wallet-svc).
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_WalletCreditUpdatedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    AiBrainProcessingCompleted:
      name: AiBrainProcessingCompleted
      title: AI Brain Processing Completed
      summary: AI classification/processing finished (from aibrain-svc).
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_AiBrainProcessingCompletedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    AuthTenantCreated:
      name: AuthTenantCreated
      title: Auth Tenant Created
      summary: A new tenant was created (from auth-svc).
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_AuthTenantCreatedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

    TaxonomyCategoryUpdated:
      name: TaxonomyCategoryUpdated
      title: Taxonomy Category Updated
      summary: A taxonomy category was updated (from taxonomy-svc).
      contentType: application/cloudevents+json
      payload:
        $ref: '#/components/schemas/CloudEvent_TaxonomyCategoryUpdatedPayload'
      bindings:
        kafka:
          key:
            type: string
            description: tenant_id used as partition key

  schemas:
    # =========================================================================
    # CloudEvents Envelope (reusable base)
    # =========================================================================
    CloudEventEnvelope:
      type: object
      description: CloudEvents v1.0 envelope structure used by all mcp-svc events.
      required:
        - specversion
        - type
        - source
        - id
        - time
        - tenantid
        - data
      properties:
        specversion:
          type: string
          const: '1.0'
          description: CloudEvents specification version.
        type:
          type: string
          description: Event type identifier matching the Kafka topic name.
        source:
          type: string
          const: eventzr.mcp-svc
          description: Event source identifier.
        id:
          type: string
          description: Unique event identifier (ULID).
        time:
          type: string
          format: date-time
          description: Event timestamp in ISO 8601 format.
        tenantid:
          type: string
          format: uuid
          description: Tenant identifier for multi-tenancy isolation.
        datacontenttype:
          type: string
          const: application/json
          description: Content type of the data field.
        subject:
          type: string
          description: Event subject (e.g. tool/<id>, workflow-execution/<id>).
        data:
          type: object
          description: Event-specific payload.

    # =========================================================================
    # Enums
    # =========================================================================
    ToolStatus:
      type: string
      enum: [ACTIVE, INACTIVE, DEPRECATED]

    ToolVisibility:
      type: string
      enum: [PUBLIC, TENANT, PRIVATE]

    ApprovalRequirement:
      type: string
      enum: [NONE, MANAGER, ORG_ADMIN, PLATFORM_ADMIN]

    WorkflowStatus:
      type: string
      enum: [DRAFT, ACTIVE, INACTIVE, DEPRECATED]

    ExecutionStatus:
      type: string
      enum:
        [
          PENDING,
          PENDING_APPROVAL,
          APPROVED,
          REJECTED,
          RUNNING,
          AWAITING_INPUT,
          SUCCESS,
          FAILED,
          TIMEOUT,
          CANCELLED,
        ]

    WorkflowExecutionStatus:
      type: string
      enum:
        [
          PENDING,
          PENDING_APPROVAL,
          APPROVED,
          REJECTED,
          RUNNING,
          PAUSED,
          SUCCESS,
          PARTIAL_SUCCESS,
          FAILED,
          TIMEOUT,
          CANCELLED,
          ROLLING_BACK,
          ROLLED_BACK,
        ]

    BudgetPeriod:
      type: string
      enum: [DAILY, WEEKLY, MONTHLY]

    BudgetAlertLevel:
      type: string
      enum: [NORMAL, WARNING, CRITICAL, EXCEEDED]

    ApprovalStatus:
      type: string
      enum: [PENDING, APPROVED, REJECTED, EXPIRED, CANCELLED]

    ApprovalTargetType:
      type: string
      enum: [TOOL_EXECUTION, WORKFLOW_EXECUTION]

    # =========================================================================
    # Reusable Sub-Schemas
    # =========================================================================
    FieldChange:
      type: object
      required: [field, oldValue, newValue]
      properties:
        field:
          type: string
        oldValue: {}
        newValue: {}

    WorkflowStep:
      type: object
      required: [step_index, name, tool_id, parameter_mapping, on_failure]
      properties:
        step_index:
          type: integer
        name:
          type: string
        tool_id:
          type: string
          format: uuid
        parameter_mapping:
          type: object
          additionalProperties: true
        condition:
          type: object
          properties:
            type:
              type: string
              enum: [always, if_success, if_failure, expression]
            expression:
              type: string
        on_failure:
          type: string
          enum: [fail, skip, retry]
        max_retries:
          type: integer
        timeout_ms:
          type: integer
        approval_required:
          $ref: '#/components/schemas/ApprovalRequirement'

    StepExecutionState:
      type: object
      required: [step_index, step_name, tool_id, execution_id, status, retry_count]
      properties:
        step_index:
          type: integer
        step_name:
          type: string
        tool_id:
          type: string
          format: uuid
        execution_id:
          type: string
          format: uuid
          nullable: true
        status:
          type: string
          enum: [PENDING, RUNNING, SUCCESS, FAILED, SKIPPED, ROLLED_BACK, ROLLBACK_FAILED]
        started_at:
          type: string
          format: date-time
          nullable: true
        completed_at:
          type: string
          format: date-time
          nullable: true
        duration_ms:
          type: integer
          nullable: true
        output:
          type: object
          nullable: true
          additionalProperties: true
        error:
          type: string
          nullable: true
        retry_count:
          type: integer

    # =========================================================================
    # Tool Event Payloads (wrapped in CloudEvent)
    # =========================================================================
    ToolRegisteredPayload:
      type: object
      required:
        [
          toolId,
          tenantId,
          serviceKey,
          name,
          displayName,
          description,
          version,
          status,
          visibility,
          approvalRequired,
          creditCost,
          createdBy,
          createdAt,
        ]
      properties:
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        serviceKey:
          type: string
        name:
          type: string
        displayName:
          type: string
        description:
          type: string
        version:
          type: string
        status:
          $ref: '#/components/schemas/ToolStatus'
        visibility:
          $ref: '#/components/schemas/ToolVisibility'
        approvalRequired:
          $ref: '#/components/schemas/ApprovalRequirement'
        creditCost:
          type: number
        tags:
          type: array
          items:
            type: string
        categoryIds:
          type: array
          items:
            type: string
            format: uuid
        remoteMcpServerId:
          type: string
          format: uuid
        createdBy:
          type: string
          format: uuid
        createdAt:
          type: string
          format: date-time

    CloudEvent_ToolRegisteredPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolRegisteredPayload'

    ToolUpdatedPayload:
      type: object
      required: [toolId, tenantId, name, displayName, version, changes, updatedBy, updatedAt]
      properties:
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        displayName:
          type: string
        version:
          type: string
        changes:
          type: array
          items:
            $ref: '#/components/schemas/FieldChange'
        updatedBy:
          type: string
          format: uuid
        updatedAt:
          type: string
          format: date-time

    CloudEvent_ToolUpdatedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolUpdatedPayload'

    ToolDeprecatedPayload:
      type: object
      required: [toolId, tenantId, name, version, reason, deprecatedBy, deprecatedAt]
      properties:
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        version:
          type: string
        replacementToolId:
          type: string
          format: uuid
        reason:
          type: string
        deprecatedBy:
          type: string
          format: uuid
        deprecatedAt:
          type: string
          format: date-time

    CloudEvent_ToolDeprecatedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolDeprecatedPayload'

    ToolDeletedPayload:
      type: object
      required: [toolId, tenantId, name, version, deletedBy, deletedAt]
      properties:
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        version:
          type: string
        deletedBy:
          type: string
          format: uuid
        deletedAt:
          type: string
          format: date-time

    CloudEvent_ToolDeletedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolDeletedPayload'

    ToolPublishedPayload:
      type: object
      required: [toolId, tenantId, name, version, publisherId, marketplacePrice, publishedAt]
      properties:
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        version:
          type: string
        publisherId:
          type: string
          format: uuid
        marketplacePrice:
          type: number
        publishedAt:
          type: string
          format: date-time

    CloudEvent_ToolPublishedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolPublishedPayload'

    ToolPurchasedPayload:
      type: object
      required: [toolId, tenantId, sourceToolId, buyerTenantId, price, purchasedAt]
      properties:
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        sourceToolId:
          type: string
          format: uuid
        buyerTenantId:
          type: string
          format: uuid
        price:
          type: number
        purchasedAt:
          type: string
          format: date-time

    CloudEvent_ToolPurchasedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolPurchasedPayload'

    # =========================================================================
    # Tool Execution Event Payloads
    # =========================================================================
    ToolExecutionStartedPayload:
      type: object
      required:
        [
          executionId,
          toolId,
          tenantId,
          userId,
          toolName,
          toolVersion,
          inputParameters,
          creditCost,
          startedAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        toolName:
          type: string
        toolVersion:
          type: string
        inputParameters:
          type: object
          additionalProperties: true
        creditCost:
          type: number
        workflowExecutionId:
          type: string
          format: uuid
        workflowStepIndex:
          type: integer
        correlationId:
          type: string
        startedAt:
          type: string
          format: date-time

    CloudEvent_ToolExecutionStartedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolExecutionStartedPayload'

    ToolExecutionCompletedPayload:
      type: object
      required:
        [
          executionId,
          toolId,
          tenantId,
          userId,
          toolName,
          inputParameters,
          outputResult,
          creditsConsumed,
          durationMs,
          startedAt,
          completedAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        toolName:
          type: string
        inputParameters:
          type: object
          additionalProperties: true
        outputResult:
          type: object
          additionalProperties: true
        creditsConsumed:
          type: number
        durationMs:
          type: integer
        workflowExecutionId:
          type: string
          format: uuid
        workflowStepIndex:
          type: integer
        correlationId:
          type: string
        startedAt:
          type: string
          format: date-time
        completedAt:
          type: string
          format: date-time

    CloudEvent_ToolExecutionCompletedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolExecutionCompletedPayload'

    ToolExecutionFailedPayload:
      type: object
      required:
        [
          executionId,
          toolId,
          tenantId,
          userId,
          toolName,
          inputParameters,
          errorMessage,
          creditsConsumed,
          durationMs,
          retryCount,
          startedAt,
          failedAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        toolName:
          type: string
        inputParameters:
          type: object
          additionalProperties: true
        errorMessage:
          type: string
        errorCode:
          type: string
        errorDetails:
          type: object
          additionalProperties: true
        creditsConsumed:
          type: number
        durationMs:
          type: integer
        retryCount:
          type: integer
        workflowExecutionId:
          type: string
          format: uuid
        workflowStepIndex:
          type: integer
        correlationId:
          type: string
        startedAt:
          type: string
          format: date-time
        failedAt:
          type: string
          format: date-time

    CloudEvent_ToolExecutionFailedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolExecutionFailedPayload'

    ToolExecutionTimeoutPayload:
      type: object
      required:
        [
          executionId,
          toolId,
          tenantId,
          userId,
          toolName,
          inputParameters,
          timeoutMs,
          durationMs,
          creditsConsumed,
          startedAt,
          timeoutAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        toolName:
          type: string
        inputParameters:
          type: object
          additionalProperties: true
        timeoutMs:
          type: integer
        durationMs:
          type: integer
        creditsConsumed:
          type: number
        workflowExecutionId:
          type: string
          format: uuid
        correlationId:
          type: string
        startedAt:
          type: string
          format: date-time
        timeoutAt:
          type: string
          format: date-time

    CloudEvent_ToolExecutionTimeoutPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolExecutionTimeoutPayload'

    ToolExecutionCancelledPayload:
      type: object
      required:
        [
          executionId,
          toolId,
          tenantId,
          userId,
          toolName,
          cancelledBy,
          reason,
          durationMs,
          creditsConsumed,
          startedAt,
          cancelledAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        toolId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        toolName:
          type: string
        cancelledBy:
          type: string
          format: uuid
        reason:
          type: string
        durationMs:
          type: integer
        creditsConsumed:
          type: number
        workflowExecutionId:
          type: string
          format: uuid
        correlationId:
          type: string
        startedAt:
          type: string
          format: date-time
        cancelledAt:
          type: string
          format: date-time

    CloudEvent_ToolExecutionCancelledPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ToolExecutionCancelledPayload'

    # =========================================================================
    # Workflow Event Payloads
    # =========================================================================
    WorkflowCreatedPayload:
      type: object
      required:
        [
          workflowId,
          tenantId,
          name,
          displayName,
          description,
          version,
          status,
          steps,
          estimatedCreditCost,
          estimatedDurationMs,
          createdBy,
          createdAt,
        ]
      properties:
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        displayName:
          type: string
        description:
          type: string
        version:
          type: string
        status:
          $ref: '#/components/schemas/WorkflowStatus'
        steps:
          type: array
          items:
            $ref: '#/components/schemas/WorkflowStep'
        estimatedCreditCost:
          type: number
        estimatedDurationMs:
          type: integer
        createdBy:
          type: string
          format: uuid
        createdAt:
          type: string
          format: date-time

    CloudEvent_WorkflowCreatedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowCreatedPayload'

    WorkflowUpdatedPayload:
      type: object
      required: [workflowId, tenantId, name, version, changes, updatedBy, updatedAt]
      properties:
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        version:
          type: string
        changes:
          type: array
          items:
            $ref: '#/components/schemas/FieldChange'
        updatedBy:
          type: string
          format: uuid
        updatedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowUpdatedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowUpdatedPayload'

    WorkflowActivatedPayload:
      type: object
      required: [workflowId, tenantId, name, version, activatedBy, activatedAt]
      properties:
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        version:
          type: string
        activatedBy:
          type: string
          format: uuid
        activatedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowActivatedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowActivatedPayload'

    WorkflowDeactivatedPayload:
      type: object
      required: [workflowId, tenantId, name, version, reason, deactivatedBy, deactivatedAt]
      properties:
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        version:
          type: string
        reason:
          type: string
        deactivatedBy:
          type: string
          format: uuid
        deactivatedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowDeactivatedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowDeactivatedPayload'

    WorkflowDeletedPayload:
      type: object
      required: [workflowId, tenantId, name, version, deletedBy, deletedAt]
      properties:
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        version:
          type: string
        deletedBy:
          type: string
          format: uuid
        deletedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowDeletedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowDeletedPayload'

    # =========================================================================
    # Workflow Execution Event Payloads
    # =========================================================================
    WorkflowExecutionStartedPayload:
      type: object
      required:
        [
          executionId,
          workflowId,
          tenantId,
          userId,
          workflowName,
          workflowVersion,
          totalSteps,
          inputData,
          estimatedCreditCost,
          startedAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        workflowName:
          type: string
        workflowVersion:
          type: string
        totalSteps:
          type: integer
        inputData:
          type: object
          additionalProperties: true
        estimatedCreditCost:
          type: number
        correlationId:
          type: string
        startedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowExecutionStartedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowExecutionStartedPayload'

    WorkflowExecutionStepCompletedPayload:
      type: object
      required:
        [
          executionId,
          workflowId,
          tenantId,
          userId,
          workflowName,
          stepIndex,
          stepName,
          toolId,
          toolExecutionId,
          stepStatus,
          stepDurationMs,
          currentStepIndex,
          totalSteps,
          completedAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        workflowName:
          type: string
        stepIndex:
          type: integer
        stepName:
          type: string
        toolId:
          type: string
          format: uuid
        toolExecutionId:
          type: string
          format: uuid
        stepStatus:
          type: string
          enum: [SUCCESS, FAILED, SKIPPED]
        stepOutput:
          type: object
          additionalProperties: true
        stepError:
          type: string
        stepDurationMs:
          type: integer
        currentStepIndex:
          type: integer
        totalSteps:
          type: integer
        correlationId:
          type: string
        completedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowExecutionStepCompletedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowExecutionStepCompletedPayload'

    WorkflowExecutionCompletedPayload:
      type: object
      required:
        [
          executionId,
          workflowId,
          tenantId,
          userId,
          workflowName,
          workflowVersion,
          totalSteps,
          completedSteps,
          inputData,
          outputData,
          creditsConsumed,
          durationMs,
          startedAt,
          completedAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        workflowName:
          type: string
        workflowVersion:
          type: string
        totalSteps:
          type: integer
        completedSteps:
          type: integer
        inputData:
          type: object
          additionalProperties: true
        outputData:
          type: object
          additionalProperties: true
        creditsConsumed:
          type: number
        durationMs:
          type: integer
        correlationId:
          type: string
        startedAt:
          type: string
          format: date-time
        completedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowExecutionCompletedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowExecutionCompletedPayload'

    WorkflowExecutionFailedPayload:
      type: object
      required:
        [
          executionId,
          workflowId,
          tenantId,
          userId,
          workflowName,
          workflowVersion,
          totalSteps,
          failedStepIndex,
          failedStepName,
          errorMessage,
          stepStates,
          creditsConsumed,
          durationMs,
          startedAt,
          failedAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        workflowName:
          type: string
        workflowVersion:
          type: string
        totalSteps:
          type: integer
        failedStepIndex:
          type: integer
        failedStepName:
          type: string
        errorMessage:
          type: string
        stepStates:
          type: array
          items:
            $ref: '#/components/schemas/StepExecutionState'
        creditsConsumed:
          type: number
        durationMs:
          type: integer
        correlationId:
          type: string
        startedAt:
          type: string
          format: date-time
        failedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowExecutionFailedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowExecutionFailedPayload'

    WorkflowExecutionPausedPayload:
      type: object
      required:
        [
          executionId,
          workflowId,
          tenantId,
          userId,
          workflowName,
          currentStepIndex,
          totalSteps,
          reason,
          creditsConsumed,
          pausedBy,
          pausedAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        workflowName:
          type: string
        currentStepIndex:
          type: integer
        totalSteps:
          type: integer
        reason:
          type: string
        checkpointData:
          type: object
          additionalProperties: true
        creditsConsumed:
          type: number
        pausedBy:
          type: string
          format: uuid
        pausedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowExecutionPausedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowExecutionPausedPayload'

    WorkflowExecutionResumedPayload:
      type: object
      required:
        [
          executionId,
          workflowId,
          tenantId,
          userId,
          workflowName,
          currentStepIndex,
          totalSteps,
          resumedBy,
          resumedAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        workflowName:
          type: string
        currentStepIndex:
          type: integer
        totalSteps:
          type: integer
        resumedBy:
          type: string
          format: uuid
        resumedAt:
          type: string
          format: date-time

    CloudEvent_WorkflowExecutionResumedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowExecutionResumedPayload'

    WorkflowExecutionCancelledPayload:
      type: object
      required:
        [
          executionId,
          workflowId,
          tenantId,
          userId,
          workflowName,
          currentStepIndex,
          totalSteps,
          reason,
          creditsConsumed,
          durationMs,
          cancelledBy,
          cancelledAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        workflowName:
          type: string
        currentStepIndex:
          type: integer
        totalSteps:
          type: integer
        reason:
          type: string
        creditsConsumed:
          type: number
        durationMs:
          type: integer
        cancelledBy:
          type: string
          format: uuid
        cancelledAt:
          type: string
          format: date-time

    CloudEvent_WorkflowExecutionCancelledPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowExecutionCancelledPayload'

    WorkflowExecutionRolledBackPayload:
      type: object
      required:
        [
          executionId,
          workflowId,
          tenantId,
          userId,
          workflowName,
          rolledBackSteps,
          totalSteps,
          creditsRefunded,
          rolledBackAt,
        ]
      properties:
        executionId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        userId:
          type: string
          format: uuid
        workflowName:
          type: string
        rolledBackSteps:
          type: integer
        totalSteps:
          type: integer
        creditsRefunded:
          type: number
        stepStates:
          type: array
          items:
            $ref: '#/components/schemas/StepExecutionState'
        rolledBackAt:
          type: string
          format: date-time

    CloudEvent_WorkflowExecutionRolledBackPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WorkflowExecutionRolledBackPayload'

    # =========================================================================
    # Budget Event Payloads
    # =========================================================================
    BudgetCreditConsumedPayload:
      type: object
      required:
        [
          budgetId,
          tenantId,
          period,
          budgetLimit,
          currentUsage,
          creditsConsumed,
          usagePercentage,
          remainingCredits,
          executionType,
          consumedAt,
        ]
      properties:
        budgetId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        period:
          $ref: '#/components/schemas/BudgetPeriod'
        budgetLimit:
          type: number
        currentUsage:
          type: number
        creditsConsumed:
          type: number
        usagePercentage:
          type: number
        remainingCredits:
          type: number
        executionId:
          type: string
          format: uuid
        executionType:
          type: string
          enum: [TOOL, WORKFLOW]
        consumedAt:
          type: string
          format: date-time

    CloudEvent_BudgetCreditConsumedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/BudgetCreditConsumedPayload'

    BudgetCreditExceededPayload:
      type: object
      required:
        [
          budgetId,
          tenantId,
          period,
          budgetLimit,
          currentUsage,
          attemptedConsumption,
          overage,
          executionType,
          exceededAt,
        ]
      properties:
        budgetId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        period:
          $ref: '#/components/schemas/BudgetPeriod'
        budgetLimit:
          type: number
        currentUsage:
          type: number
        attemptedConsumption:
          type: number
        overage:
          type: number
        executionId:
          type: string
          format: uuid
        executionType:
          type: string
          enum: [TOOL, WORKFLOW]
        exceededAt:
          type: string
          format: date-time

    CloudEvent_BudgetCreditExceededPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/BudgetCreditExceededPayload'

    BudgetCreditWarningPayload:
      type: object
      required:
        [
          budgetId,
          tenantId,
          period,
          budgetLimit,
          currentUsage,
          usagePercentage,
          remainingCredits,
          alertLevel,
          threshold,
          warningAt,
        ]
      properties:
        budgetId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        period:
          $ref: '#/components/schemas/BudgetPeriod'
        budgetLimit:
          type: number
        currentUsage:
          type: number
        usagePercentage:
          type: number
        remainingCredits:
          type: number
        alertLevel:
          $ref: '#/components/schemas/BudgetAlertLevel'
        threshold:
          type: number
        warningAt:
          type: string
          format: date-time

    CloudEvent_BudgetCreditWarningPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/BudgetCreditWarningPayload'

    BudgetPeriodResetPayload:
      type: object
      required:
        [
          budgetId,
          tenantId,
          period,
          previousPeriodStart,
          previousPeriodEnd,
          previousUsage,
          budgetLimit,
          newPeriodStart,
          newPeriodEnd,
          resetAt,
        ]
      properties:
        budgetId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        period:
          $ref: '#/components/schemas/BudgetPeriod'
        previousPeriodStart:
          type: string
          format: date-time
        previousPeriodEnd:
          type: string
          format: date-time
        previousUsage:
          type: number
        budgetLimit:
          type: number
        newPeriodStart:
          type: string
          format: date-time
        newPeriodEnd:
          type: string
          format: date-time
        resetAt:
          type: string
          format: date-time

    CloudEvent_BudgetPeriodResetPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/BudgetPeriodResetPayload'

    # =========================================================================
    # Approval Event Payloads
    # =========================================================================
    ApprovalRequestedPayload:
      type: object
      required:
        [
          approvalId,
          tenantId,
          targetType,
          targetId,
          requesterId,
          requiredRole,
          reason,
          expiresAt,
          requestedAt,
        ]
      properties:
        approvalId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        targetType:
          $ref: '#/components/schemas/ApprovalTargetType'
        targetId:
          type: string
          format: uuid
        toolId:
          type: string
          format: uuid
        toolName:
          type: string
        workflowId:
          type: string
          format: uuid
        workflowName:
          type: string
        requesterId:
          type: string
          format: uuid
        requiredRole:
          $ref: '#/components/schemas/ApprovalRequirement'
        reason:
          type: string
        estimatedCredits:
          type: number
        riskLevel:
          type: string
        expiresAt:
          type: string
          format: date-time
        requestedAt:
          type: string
          format: date-time

    CloudEvent_ApprovalRequestedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ApprovalRequestedPayload'

    ApprovalApprovedPayload:
      type: object
      required: [approvalId, tenantId, targetType, targetId, requesterId, approverId, approvedAt]
      properties:
        approvalId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        targetType:
          $ref: '#/components/schemas/ApprovalTargetType'
        targetId:
          type: string
          format: uuid
        toolId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        requesterId:
          type: string
          format: uuid
        approverId:
          type: string
          format: uuid
        approvedAt:
          type: string
          format: date-time

    CloudEvent_ApprovalApprovedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ApprovalApprovedPayload'

    ApprovalRejectedPayload:
      type: object
      required:
        [
          approvalId,
          tenantId,
          targetType,
          targetId,
          requesterId,
          approverId,
          rejectionReason,
          rejectedAt,
        ]
      properties:
        approvalId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        targetType:
          $ref: '#/components/schemas/ApprovalTargetType'
        targetId:
          type: string
          format: uuid
        toolId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        requesterId:
          type: string
          format: uuid
        approverId:
          type: string
          format: uuid
        rejectionReason:
          type: string
        rejectedAt:
          type: string
          format: date-time

    CloudEvent_ApprovalRejectedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ApprovalRejectedPayload'

    ApprovalExpiredPayload:
      type: object
      required:
        [approvalId, tenantId, targetType, targetId, requesterId, requestedAt, expiresAt, expiredAt]
      properties:
        approvalId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        targetType:
          $ref: '#/components/schemas/ApprovalTargetType'
        targetId:
          type: string
          format: uuid
        toolId:
          type: string
          format: uuid
        workflowId:
          type: string
          format: uuid
        requesterId:
          type: string
          format: uuid
        requestedAt:
          type: string
          format: date-time
        expiresAt:
          type: string
          format: date-time
        expiredAt:
          type: string
          format: date-time

    CloudEvent_ApprovalExpiredPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/ApprovalExpiredPayload'

    # =========================================================================
    # Remote Server Event Payloads
    # =========================================================================
    RemoteServerRegisteredPayload:
      type: object
      required:
        [
          serverId,
          tenantId,
          name,
          baseUrl,
          protocol,
          authType,
          toolCount,
          isHealthy,
          registeredBy,
          registeredAt,
        ]
      properties:
        serverId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        baseUrl:
          type: string
          format: uri
        protocol:
          type: string
        authType:
          type: string
          enum: [NONE, API_KEY, BEARER_TOKEN, OAUTH2, CUSTOM]
        toolCount:
          type: integer
        isHealthy:
          type: boolean
        registeredBy:
          type: string
          format: uuid
        registeredAt:
          type: string
          format: date-time

    CloudEvent_RemoteServerRegisteredPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/RemoteServerRegisteredPayload'

    RemoteServerHealthChangedPayload:
      type: object
      required: [serverId, tenantId, name, previousHealth, currentHealth, healthCheckUrl, checkedAt]
      properties:
        serverId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        previousHealth:
          type: boolean
        currentHealth:
          type: boolean
        healthCheckUrl:
          type: string
          format: uri
        lastError:
          type: string
        checkedAt:
          type: string
          format: date-time

    CloudEvent_RemoteServerHealthChangedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/RemoteServerHealthChangedPayload'

    RemoteServerDisconnectedPayload:
      type: object
      required: [serverId, tenantId, name, reason, affectedToolCount, disconnectedAt]
      properties:
        serverId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        name:
          type: string
        reason:
          type: string
        affectedToolCount:
          type: integer
        disconnectedAt:
          type: string
          format: date-time

    CloudEvent_RemoteServerDisconnectedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/RemoteServerDisconnectedPayload'

    # =========================================================================
    # Consumed Event Payloads (from other services)
    # =========================================================================
    WalletCreditUpdatedPayload:
      type: object
      required:
        [
          walletId,
          tenantId,
          accountId,
          previousBalance,
          newBalance,
          changeAmount,
          changeType,
          transactionId,
          updatedAt,
        ]
      properties:
        walletId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        accountId:
          type: string
        previousBalance:
          type: number
        newBalance:
          type: number
        changeAmount:
          type: number
        changeType:
          type: string
          enum: [CREDIT, DEBIT, REFUND]
        transactionId:
          type: string
          format: uuid
        updatedAt:
          type: string
          format: date-time

    CloudEvent_WalletCreditUpdatedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/WalletCreditUpdatedPayload'

    AiBrainProcessingCompletedPayload:
      type: object
      required:
        [processingId, tenantId, entityType, entityId, classificationType, result, processedAt]
      properties:
        processingId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        entityType:
          type: string
          enum: [TOOL, WORKFLOW]
        entityId:
          type: string
          format: uuid
        classificationType:
          type: string
          enum: [CATEGORY, SENTIMENT, RISK]
        result:
          type: object
          properties:
            categories:
              type: array
              items:
                type: string
            confidence:
              type: number
            model:
              type: string
            metadata:
              type: object
              additionalProperties: true
        processedAt:
          type: string
          format: date-time

    CloudEvent_AiBrainProcessingCompletedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/AiBrainProcessingCompletedPayload'

    AuthTenantCreatedPayload:
      type: object
      required:
        [tenantId, tenantName, organizationId, planType, maxUsers, features, createdBy, createdAt]
      properties:
        tenantId:
          type: string
          format: uuid
        tenantName:
          type: string
        organizationId:
          type: string
          format: uuid
        planType:
          type: string
        maxUsers:
          type: integer
        features:
          type: array
          items:
            type: string
        createdBy:
          type: string
          format: uuid
        createdAt:
          type: string
          format: date-time

    CloudEvent_AuthTenantCreatedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/AuthTenantCreatedPayload'

    TaxonomyCategoryUpdatedPayload:
      type: object
      required: [categoryId, tenantId, categoryName, categorySlug, updatedBy, updatedAt]
      properties:
        categoryId:
          type: string
          format: uuid
        tenantId:
          type: string
          format: uuid
        categoryName:
          type: string
        categorySlug:
          type: string
        parentCategoryId:
          type: string
          format: uuid
        metadata:
          type: object
          additionalProperties: true
        updatedBy:
          type: string
          format: uuid
        updatedAt:
          type: string
          format: date-time

    CloudEvent_TaxonomyCategoryUpdatedPayload:
      allOf:
        - $ref: '#/components/schemas/CloudEventEnvelope'
        - type: object
          properties:
            data:
              $ref: '#/components/schemas/TaxonomyCategoryUpdatedPayload'
