# Integrations

> Companion packages for Elmish MVU, shared DOM contracts, cross-target JSON wire codecs, and MCP inspection.

Four companion packages connect a Ranvier `Graph`{fsharp} to MVU loops, browser/native DOM hosts,
cross-runtime JSON transports, and Model Context Protocol (MCP) agents.

## Elmish

`Ranvier.Elmish` (`dotnet add package Ranvier.Elmish`;
[API reference](/reference/ranvier-elmish/index.md)) hosts an existing `init`{fsharp} and
`update`{fsharp} inside a `Signal<'Model>`{fsharp} with zero dependency on the `Elmish` NuGet
package.

Views migrate one at a time by reading `Memo<'Field>`{fsharp} selectors instead of re-rendering on
every model change.

```fsharp
open Ranvier
open Ranvier.CE
open Ranvier.Elmish

type Address = { City: string; Zip: string }
type Model = { Count: int; Name: string; Address: Address }
type Msg = Increment | Rename of string | Move of string

let init = { Count = 0; Name = "Ada"; Address = { City = "Bergen"; Zip = "5003" } }

let update msg model =
    match msg with
    | Increment -> { model with Count = model.Count + 1 }
    | Rename name -> { model with Name = name }
    | Move city -> { model with Address = { model.Address with City = city } }

use graph = new Graph ()

graph {
    let app = Mvu.create init update
    let count = app.Select _.Count
    let address = app.Select _.Address
    let city = memo { let! a = address in return a.City }

    effect {
        let! c = count
        printfn "count = %d" c
    }

    app.Dispatch Increment        // prints: count = 1
    app.Dispatch (Rename "Grace") // count selector cuts off -> effect stays quiet
}
```

<div class="rv-map-card">

```fsharp
let model = signal { return {| Count = 0; Name = "Ada" |} }
let count = memo { let! m = model in return m.Count }
let mutable effectRuns = 0
effect {
    let! c = count
    effectRuns <- effectRuns + 1
    printfn "count = %d" c
}

controls [
    button "Increment" (fun () -> model.Value <- {| model.Value with Count = model.Value.Count + 1 |})
    |> describe "The count selector publishes 1 and runs its effect."
    |> expect "The count selector publishes 1 and runs its effect." (fun () -> count.Peek = 1 && effectRuns = 2)
    button "Rename Grace" (fun () -> model.Value <- {| model.Value with Name = "Grace" |})
    |> describe "The model changes, but count remains 1 and its effect stays quiet."
    |> expect "The model changes, but count remains 1 and its effect stays quiet." (fun () -> count.Peek = 1 && effectRuns = 2)
]
```

<div class="rv-map-host" id="rvm-p307abd1cda-c1" data-ranvier-map-page="p307abd1cda" data-ranvier-map-cell="c1"></div>

</div>


- **Commands (`Mvu.withCmd`{fsharp}):** accepts `('Model * (('Msg -> unit) -> unit) list)`{fsharp}
  matching `Cmd<'Msg>`{fsharp}. Commands run in list order after the model write[^mvu-apply].

- **Dispatch:** off-thread `app.Dispatch`{fsharp} marshals automatically via
  `Graph.Dispatch`{fsharp} ([Streams and threading](streams-and-threading.md); under
  `Serialised`{fsharp}, external calls queue for the next drain).

- **Lifetime:** `Mvu`{fsharp} attaches to the enclosing `Owner`{fsharp}; once disposed, late
  command dispatches are silently dropped[^mvu-disposed].

- **Journaling:** pipe `|> Mvu.journal "cart" cartMsgCodec`{fsharp} to record external and
  async-command messages on the graph's
  [input journal](tracing-and-journal.md#deterministic-journal-and-replay).

- **Selector granularity:** every model write re-evaluates observed top-level `app.Select`{fsharp}
  memos ($O(\text{observed selectors})$ — ~48k instructions at 64 fields vs ~607 instructions for
  a per-field `Signal`{fsharp}; see [Instruction counts](../benchmarks/counters.md)). Nest
  selectors over sub-records (`address`{fsharp} → `city`{fsharp}) so unchanged subtrees cut off
  early, or use per-field signals / `editable`{fsharp} handles for high-frequency forms
  ([Editable values and forms](editable-and-forms.md)).

## Reactive DOM

Use `Ranvier.Dom` on native .NET hosts and `Fable.Ranvier.Dom` in Fable browser projects
([API reference](/reference/ranvier-dom/index.md)) to program against one WebKit-derived DOM and
host-service surface (`Document`{fsharp}, `Element`{fsharp}, `EventTarget`{fsharp},
`KeyboardEvent`{fsharp}, `SVGElement`{fsharp}, `CSSStyleDeclaration`{fsharp}).

Bridge host observation services into a `Graph`{fsharp} by seeding a `signal`{fsharp}, dispatching
updates, and releasing subscriptions via `cleanup`{fsharp}:

```fsharp
open Ranvier
open Ranvier.CE
open Ranvier.Dom

let observeInput (graph: Graph) (input: InputStateService) =
    graph {
        let state = signal { return input.Current () }
        let sub =
            input.Subscribe (fun _ ->
                let snap = input.Current ()
                graph.Dispatch (fun () -> state.Value <- snap))
        cleanup { sub.Dispose () }
        return state
    }

let observeReducedMotion (media: MediaQueryService) (changed: bool -> unit) =
    let query = media.Match "(prefers-reduced-motion: reduce)"
    cleanup { query.Dispose () }
    changed query.Matches
    let sub = query.Subscribe changed
    cleanup { sub.Dispose () }
```

`Capabilities.create ()`{fsharp} registers optional host providers (`KnownKeys`{fsharp},
`Observe`{fsharp}) across shared DOM service families:

| Service family | Contracts |
| --- | --- |
| **Input, pointer & viewport** | `InputState`{fsharp}, `PointerInput`{fsharp} (`contacts`{fsharp}, `lock`{fsharp}), `Viewport`{fsharp}, `VisualViewports`{fsharp}, `ViewportScrollService`{fsharp} |
| **Cancellation domains** | `Cancellation.create`{fsharp} (`AbortSignal`{fsharp} controllers, `Timeout`{fsharp}, `Any`{fsharp}, `.NET` `CancellationToken`{fsharp} bridges) |
| **Styles & geometry** | `CssQueryService`{fsharp}, `ComputedStyleService`{fsharp}, `StyleSheetService`{fsharp}, `CustomPropertyService`{fsharp}, `StyleValueService`{fsharp}, `StyleMapService`{fsharp}, `GeometryService`{fsharp}, `TransformValueService`{fsharp}, `Coordinates`{fsharp}, `SvgPaths`{fsharp} |
| **Observers & diagnostics** | `ResizeObservation`{fsharp}, `IntersectionObservation`{fsharp}, `MutationObservation`{fsharp}, `DiagnosticsService`{fsharp} (`MatchedRules`{fsharp}, `Cascade`{fsharp}, `BoxModel`{fsharp}, `RenderTree`{fsharp}) |
| **Events, resources & canvas** | `EventService`{fsharp}, `FormDataService`{fsharp}, `FormSubmissionService`{fsharp}, `ResourceService`{fsharp}, `FontSet`{fsharp}, `BinaryValueService`{fsharp}, `BlobUrlService`{fsharp}, `CanvasContextService`{fsharp}, `ImageDataService`{fsharp}, `CanvasExportService`{fsharp}, `SnapshotService`{fsharp} |
| **Scheduling, motion & platform** | `FrameScheduler`{fsharp} (`ManualFrameScheduler`{fsharp}), `IdleScheduler`{fsharp}, `TimingService`{fsharp}, `AnimationService`{fsharp}, `TimelineService`{fsharp}, `ViewTransitionService`{fsharp}, `ScreenService`{fsharp}, `MediaCapabilitiesService`{fsharp}, `LocaleService`{fsharp}, `TextSegmenter`{fsharp}, `HighlightService`{fsharp}, `UrlService`{fsharp}, `CryptoService`{fsharp}, `WakeLockService`{fsharp}, `NotificationService`{fsharp}, `AppBadgeService`{fsharp} |

## Wire transport

`Ranvier.Wire` (`dotnet add package Ranvier.Wire`;
[API reference](/reference/ranvier-wire/index.md)) shares deterministic JSON codecs across .NET
(`System.Text.Json`) and Fable (JavaScript) using vendored `Ranvier.Wire.Thoth.Json.Core`{fsharp}
combinators wrapped in `WireCodec<'T>`{fsharp}:

```fsharp
open Ranvier.Wire
open Ranvier.Wire.Thoth.Json.Core

type Price = { Currency: string; Amount: decimal }

let priceCodec: Codec<Price> =
    objectCodec {
        let! currency = Codec.field "currency" _.Currency Codec.string
        and! amount = Codec.field "amount" _.Amount Codecs.decimal
        return { Currency = currency; Amount = amount }
    }

let wire = WireCodec.ofCodecWith { WireLimits.Default with MaxDepth = 32 } priceCodec
let json = wire.Encode { Currency = "AUD"; Amount = 1.10m } // amount encoded as "1.10"
let decoded: Result<Price, WireError> = wire.Decode json
```

| Capability | Codecs & options |
| --- | --- |
| **Cross-runtime scalars** | `Codecs.decimal`{fsharp} (scale-preserving string), `Codecs.bigint`{fsharp} (bounded by `MaxBigIntDigits`{fsharp}), `Codec.int64`{fsharp} / `uint64`{fsharp} (decimal string surviving JS `Number`), `Codecs.dateTimeOffset`{fsharp}, `Codec.string`{fsharp} / `char`{fsharp} (rejects lone UTF-16 surrogates) |
| **Unions, collections & recursion** | `variantCodec`{fsharp} + `Codec.case`{fsharp}, `variantCodecWithTag`{fsharp}, `variantCodecTuple`{fsharp}, `Codec.list`{fsharp}, `array`{fsharp}, `dict`{fsharp}, `lossyOption`{fsharp}, `losslessOption`{fsharp}, `Codec.lazily`{fsharp}, `Codec.fix`{fsharp} |
| **Input bounds & journal bridge** | `WireLimits`{fsharp} (`MaxDepth`{fsharp}, `MaxItems`{fsharp}, `MaxBigIntDigits`{fsharp}) classifies untrusted input errors as `WireError.Syntax`{fsharp}, `Limit`{fsharp}, or `Shape`{fsharp}; adapt to [journal codecs](tracing-and-journal.md#deterministic-journal-and-replay) via `wire.Encode`{fsharp} / `wire.Decode`{fsharp} |

## Model Context Protocol

:::info Experimental tooling (`Ranvier.Mcp`)
`Ranvier.Mcp` is a source/tooling spike ([API reference](/reference/ranvier-mcp/index.md),
runnable cart at
[`examples/Ranvier.Mcp.Sample`](https://github.com/ranvier-org/Ranvier/tree/master/examples/Ranvier.Mcp.Sample));
its tool names and schemas may evolve.
:::

`Ranvier.Mcp` exposes named snapshots, authorised MVU messages, and traced provenance queries from
a running process to MCP clients without arbitrary code execution.

`GraphHost.Start setup`{fsharp} runs a dedicated `Guarded`{fsharp} graph thread whose inbox drains
automatically on `host.Invoke`{fsharp} or `Exposure`{fsharp} calls:

```fsharp
type Msg = Add of int
type App = { Mvu: Mvu<int, Msg>; Exposure: Exposure; Adapter: McpAdapter }

let decoders: (string * MessageDecoder<Msg>) list =
    [ "add", fun args -> Result.Ok (Add (args.GetProperty("amount").GetInt32 ())) ]

use host =
    GraphHost.Start (fun _ ->
        let mvu = Mvu.create 0 (fun (Add n) count -> count + n)
        let count = mvu.Select id
        let exposure = Exposure ()
        exposure |> Expose.value "count" (fun (n: int) -> JsonValue.Create n :> JsonNode) (fun () -> count.Value)
        exposure |> Expose.messages mvu decoders
        exposure |> Expose.node "count" count
        exposure.Start ()
        { Mvu = mvu; Exposure = exposure; Adapter = new McpAdapter (exposure) })
```

| Surface | Exposed items |
| --- | --- |
| **In-process `Exposure`{fsharp}** | Register `Expose.value`{fsharp}, `Expose.messages`{fsharp}, `Expose.messageShapes`{fsharp}, and `Expose.node`{fsharp} before `Start ()`{fsharp}; call thread-safe `Dispatch`{fsharp} and `WaitVersion`{fsharp} |
| **MCP resources & core tools** | Resources `ranvier://state` and `ranvier://state/{name}` (with `resources/subscribe`); tools `snapshot`, `dispatch` (single or batch step diffs), and `wait_version` |
| **Traced MCP tools (`RANVIER_TRACE`)** | `explain` (`{node, messages}` → value, source line, `why`, `whyNot`, `stale:`, `unread:`, `cutoff:`), `graph`, and `node` (`around` 0–2 hops); configured via `McpAdapterOptions`{fsharp} |
| **Dev & CI scripts** | `dotnet fsi --quiet --exec tools/mcp-supervise.fsx <app.dll>` (hot assembly reload + history replay) and `tools/mcp-call.fsx` (stateless single-command CLI) |

[^mvu-apply]: [`mvu_apply_writes_before_commands`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Extensions.html#mvu_apply_writes_before_commands), [`mvu_apply_spec`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Heap.Extensions.html#mvu_apply_spec).
[^mvu-disposed]: [`mvu_disposed_drops_dispatch`](https://ranvier-org.github.io/Ranvier/proofs/Ranvier.Pure.Extensions.html#mvu_disposed_drops_dispatch).
