Skip to content

Request Lifecycle

What happens when you call invoke("notes.create", title="Hello")?

sequenceDiagram
    participant Client
    participant Transport as Transport<br/>(MCP / HTTP)
    participant Runtime as Runtime<br/>(invoke)
    participant Policy as Cedar<br/>Policy
    participant Cost as Cost<br/>Envelope
    participant Handler as Capability<br/>Handler
    participant KG as ctx.kg<br/>(Store)
    participant Prov as PROV-O<br/>Writer

    Client->>Transport: tools/call or POST /invoke
    Transport->>Runtime: invoke("notes.create", title="Hello")

    rect rgb(124, 77, 255, 0.08)
        Note over Runtime,Policy: 🧠 Brain phase
        Runtime->>Runtime: Lookup capability handler
        Runtime->>Runtime: Validate arguments
        Runtime->>Policy: Evaluate Cedar policy
        Policy-->>Runtime: permit / deny
        Runtime->>Cost: Open cost envelope
    end

    rect rgb(255, 145, 0, 0.08)
        Note over Runtime,Prov: 🤚 Hand phase
        Runtime->>Handler: Call handler(ctx, title="Hello")
        Handler->>KG: ctx.kg.add(note)
        KG->>Prov: Record provenance
        Handler-->>Runtime: {"id": "..."}
    end

    Runtime->>Cost: Close envelope
    Runtime-->>Transport: Result + cost + prov IRI
    Transport-->>Client: Response

Phase Details

1. Transport Receives Request

MCP stdio, MCP SSE, or HTTP/FastAPI. The transport layer normalizes the request into an invoke() call. No business logic here.

2. 🧠 Brain Phase — Planning and Validation

The runtime performs four checks before any work happens:

  1. Lookup — find the @capability handler by ID
  2. Validate — check argument types against the handler's signature
  3. Policy — evaluate Cedar policies for this principal + action + resource
  4. Budget — open a CostScope with the configured limits

If any check fails, the request is rejected before the handler runs. Middleware (@before) hooks execute here too.

3. 🤚 Hand Phase — Execution

The handler function runs. It has access to ctx — the capability context that provides:

  • ctx.kg — the knowledge graph (add, query, match, traverse)
  • ctx.llm — the LLM client (if configured)
  • ctx.principal — the authenticated caller
  • ctx.cost — the current cost scope

Every ctx.kg.add() call triggers SHACL validation (if shapes are loaded) and provenance recording. Every LLM call is cost-tracked.

4. Response

The result, accumulated cost, and provenance IRI are returned through the transport layer. Middleware (@after) hooks execute here.

Middleware Insertion Points

graph LR
    B["@before"] --> H["Handler"] --> A["@after"]
    H -.->|error| E["@on_error"]
    AR["@around"] -.->|wraps| H

    style B fill:#7c4dff20,stroke:#7c4dff
    style A fill:#7c4dff20,stroke:#7c4dff
    style E fill:#ff525220,stroke:#ff5252
    style AR fill:#ffd74020,stroke:#ffd740

Middleware targets capabilities by name or glob pattern (notes.*, *). See the Middleware Guide.