Skip to main content
Glama
Industrial-AIops

Industrial-AIops

Industrial-AIOps

English · 中文

Ask an AI agent why the line stopped — and get an answer that cites its evidence.

A vendor-neutral, read-first data tap for the factory floor. It speaks 15 field protocols, correlates what it reads across them, and hands your agent an evidence-cited verdict instead of a guess. Every call is audited, and no reading ever phones home.

pip install "iaiops[opcua]"      # pick your protocol — or [all]
iaiops init                      # write ~/.iaiops/config.yaml
iaiops doctor                    # check the setup before you trust it

Prefer a container? The published image is cosign-signed and runs non-root. It speaks MCP over stdio, so keep stdin open and mount a volume for the audit store:

cosign verify --key deploy/margo/cosign.pub ghcr.io/industrial-aiops/iaiops:0.36.0-factory
docker run -i --rm -v iaiops-state:/home/iaiops/.iaiops \
  ghcr.io/industrial-aiops/iaiops:0.36.0-factory

For a hardened or air-gapped deployment (read-only rootfs, cap_drop: ALL, no-new-privileges, optional on-box LLM) use deploy/margo/compose.yaml and deploy/airgap/. The analysis engine needs no GPU and no model API — it is deterministic; an LLM is optional and only phrases the verdict.

MCP directory overview

Industrial-AIOps connects AI agents and command-line workflows to industrial data. Use it to inventory configured assets, collect bounded samples, inspect alarms and data quality, calculate OEE from declared tag semantics, and investigate downtime with evidence from collected history. Protocol support includes OPC UA, Modbus, Siemens S7, MQTT/Sparkplug B and BACnet; coverage and verification vary by connector.

MCP and CLI share the same governance and audit engine. Analysis is deterministic; a language model is optional. Select an explicit MCP profile such as factory or building; the base server does not start without a selection. Device writes, where supported, have additional safeguards. No tool deploys PLC logic. See Glama setup and listing text for container and directory settings.

Related MCP server: AetherEdge

What you get

Reads

OPC-UA (+ Historical Access, tag auto-discovery) · Modbus TCP/RTU · S7comm · Mitsubishi MC · Omron FINS · MTConnect · MQTT/Sparkplug B · EtherNet/IP · EtherCAT · PROFINET · SECS/GEM · HART-IP · BACnet/IP · IO-Link · serial ASCII instruments (RS-232/485, serial device servers) — plus read-only REST layers for BAS supervisors (Metasys / Niagara) and Ignition Gateway

Figures out

downtime root cause (the flagship copilot), alarm floods (ISA-18.2), broken dataflows, data trustworthiness, OEE, asset inventory, legacy PLC program explainer (ST/AWL/L5X)

Governs

audit · budget · risk-tier · undo — on every call, through one engine, from both MCP and CLI

Stays yours

no telemetry or phone-home by default. Six tools can send data off-box by design (stream_publish, stream_publish_event, uns_publish, historian_push, mqtt_publish, rca_narrate) — IAIOPS_NO_EGRESS=1 withholds all six for an air-gapped posture. Since 0.34.0, an opt-in Margo option exports only process health and audit counts to an explicitly configured local/private OTLP collector; it is also blocked by IAIOPS_NO_EGRESS=1.

Eleven editions ship in this package — ten per industry (fab · factory · process · building · water · warehouse · clinical · pharma · renewables · plcnext), each adding its own read-only advisory checks, and one cross-protocol: sensor (connect, decode and read a sensor; IAIOPS_MCP=sensor). Substation / utility telecontrol (IEC-104 · DNP3 · IEC-61850) ships separately as iaiops-energy.

Your first five minutes

Four commands. Only one of them touches a device: doctor probes each configured endpoint (iaiops doctor --skip-probe contacts nothing).

pip install "iaiops[modbus]"     # pick the protocol you actually have, or [all]
iaiops onboard status            # ← run this first. Contacts NOTHING.
iaiops doctor                    # config, secrets, reachability — and the version
iaiops readiness                 # every scenario, and what each gap needs

onboard status answers the smaller questions you have first: which journey is this site on — reading its devices directly, or subscribing to a UNS broker its data already flows through — which step of it are you on, and what is the one command that advances it? It is derived from your store and config.yaml every time. The one thing it keeps is a namespace audit verdict, and that counts only for the broker and topic filter it was taken on and always shows its age — so edit config.yaml by hand and the answer stays true.

0.35.0 reference scenario: iaiops diagnostic-card adds a window-specific HTML readiness snapshot and portable evidence ZIP for a synthetic conveyor on one Sandbox platform. Run the two cases; dated candidate trial. Replay sufficiency never establishes live readiness or a physical root cause.

readiness reads your config and local store and answers one question: which scenarios can this site run today, and what does each gap need? Every gap comes with the command that closes it, ranked by how much it unlocks. No agent, no cloud, no account, and nothing on the wire.

Then the path, in the order that matters — survey what is there, take a bounded sample, and only then explain it:

contacts a device?

Survey

iaiops scan plan → iaiops scan run

preview sends nothing; the run itemises every packet class it sent

Configure

iaiops onboard draft → you merge it into config.yaml

no — it reads the stored scan, and writes nothing

Tap

iaiops collect run line1 --duration 7d

yes — and it reports what it saw and what it missed

Declare

iaiops tags export → a person fills in role → iaiops tags apply --by <you>

no — the role column comes out empty on purpose

Explain

iaiops oee measure --since … --until … · iaiops investigate open · iaiops diag rca

no — all over collected history

See the whole thing run against a real device in about two minutes, including a genuine mid-run outage, with ./demo/oee-line/run_demo.sh — no hardware, no configuration, nothing written outside a temporary directory. demo/oee-line/ explains what each step is for and what the numbers do and do not claim.

Why read-first

OT is exactly where you want an agent on a tight leash. The read paths are the product; the few write paths are OT-dangerous, off by default, and gated by MOC discipline — dry-run, one-shot approval, undo capture, hash-chained audit.

Proving the analysis needs no model

The analysis layers cannot reach a language model. That is a guard, not a slogan: tests/test_brain_is_llm_free.py scans eight packages — brain, discovery, runtime, readiness, collect, knowledge, retain, connectors — for any import that could reach one, and an empty result is the guarantee. A model is used in exactly two places, and neither is load-bearing: rca_narrate rephrases a verdict that was already computed and already cited, and an agent front-end decides which tool to call. Remove both and the numbers are the same numbers.

That guard is static — it proves nothing can call a model. For a validation team the sentence they are asked to accept is the executed one, so it is executed:

iaiops verify determinism --out determinism-record.json

A pinned in-repo dataset goes through availability, production counts, the Six Big Losses, ISA-18.2 alarm load, control charts, the conservative baseline and the RCA copilot. Each result is canonically encoded and digested; the suite runs twice in this process and once in each of two fresh interpreters started at different PYTHONHASHSEED values — the arm that catches a set or dict iteration order reaching a result, which a single run never can. The socket API raises throughout, so a computation that reached for a device or a hostname fails here instead of quietly working on a machine that happened to be online. Afterwards the run is asked what it pulled in: a model library that was already loaded (an MCP server holds iaiops.core.llm for the opt-in narration tool) is recorded, not judged — only what the suite itself imported can condemn it.

The record separates result (identical every run — the part to sign) from context (when and where this run happened). Two good runs are not byte-identical records, and someone will diff them, so the halves are named rather than mixed.

This is the form the claim has to take to be usable: not "our model is accurate", which is not evidence in a GxP context, but a test case someone can write into an IQ/OQ protocol — remove the model, block the network, re-run the standard dataset, compare the hash — execute, and sign. verify_determinism is the same check from the MCP side; iaiops verify suite lists what it covers without running it.

How far it's actually been verified

Short version: verified against real protocol libraries, containers and in-process servers — not yet against real plant gear. We grade evidence rather than saying "tested", because a real container round-trip and a synthetic fixture are not the same claim.

Rung

Who judges our frames

Protocols at this rung today

2a — real wire to a third-party server

somebody else's implementation of the spec

OPC-UA (Microsoft opc-plc; certificate trust enforced both ways) · Modbus TCP (pymodbus) · Modbus RTU (pymodbus over a socat PTY) · MQTT / Sparkplug B (a real mosquitto broker) · BACnet/IP (bacpypes3, two IPs on one subnet) · MTConnect (the Institute's own cppagent) · SECS/GEM (secsgem equipment side) · EtherNet/IP (identification)

2b — real wire to a server we wrote from the spec

the third-party client parses our frames

S7comm (pyS7) · Mitsubishi MC (pymcprotocol) · EtherNet/IP (tag layer — pycomm3, all three driver routes) · PROFINET-DCP

2c — real wire, but both ends are ours

nobody independent

Omron FINS · IO-Link · HART-IP (codec itself at rung 1, against hart-protocol) · serial ASCII (our own weighing simulator)

mock only — protocol logic exercised, nothing on the wire

—

EtherCAT · BAS (Metasys / Niagara) · Ignition gateway

3 — real physical / vendor device

the device

zero, for every protocol

Each row's detail — and, per protocol, what is still not covered — is in docs/VERIFICATION-RECORD.md. That file is the record; this table is its summary, and a test fails if the two disagree.

Per-protocol evidence — including what each test does not cover — is in docs/VERIFICATION-RECORD.md, one row per protocol, naming the test behind each claim. Every 待核实 is hardware-gated, not forgotten — each one names the equipment that would settle it.

🧪 测试与共创 / Beta testing & co-creation

我们在找现场测试伙伴。 软件里能验证的我们都验证了(真实 in-process 服务器、真实协议库、Docker 容器 loopback)——剩下的 待核实 清单只有真设备能回答:物理 Modbus-RTU(RS-485)、EtherCAT 从站、HART 网关、在线 BACnet 楼宇设备、在线 Metasys/Niagara BAS 控制器、在线 Ignition 网关、国产 PLC(汇川/信捷)、真机 PLCnext、真实变电站 RTU/IED、欧姆龙 FINS 真机、IO-Link 主站。如果你是 OT 工程师、系统集成商或工厂团队,手上有任何这类设备:装上 iaiops,对你的设备跑一遍 iaiops doctor,把结果告诉我们。经你验证的设备会署名写进支持矩阵;现场反馈的问题我们优先分诊;功能可以通过 GitHub Issues/Discussions 直接共创。

We're looking for field-testing partners. Everything software-verifiable has been verified; what's left on the honest 待核实 list only real equipment can answer — physical Modbus-RTU (RS-485), EtherCAT slaves, HART gateways, live BACnet HVAC, live Metasys/Niagara BAS controllers, live Ignition gateway, domestic PLCs (Inovance/Xinje), live PLCnext, substation RTUs/IEDs, live Omron FINS PLCs, IO-Link masters. If you're an OT engineer, integrator, or factory team with access to any of these: install iaiops, run iaiops doctor against your gear, and tell us what happened. Verified-equipment reports get credited in the support matrix, field-reported issues get fast triage, and features are co-designed in the open via GitHub Issues/Discussions.

👉 参与入口 | Start here: open an issue with the protocol and device model in the title, or email zhouwei008@gmail.com. Either reaches a person, and a report gets answered against the current release.


Consolidated capability matrix

Protocol

Tool

Operation

R/W

risk_tier

Returns (key fields)

OPC-UA

opcua_server_info

server status

R

low

state, product_name, namespaces

OPC-UA

opcua_browse

browse node tree

R

low

[{node_id, browse_name, depth}]

OPC-UA

opcua_read_node

read one node

R

low

value, datatype, source_timestamp, good

OPC-UA

opcua_read_many

batch read

R

low

[{node_id, value, ...}]

OPC-UA

opcua_subscribe_sample

bounded sample

R

low

{collected, samples[]}

OPC-UA

opcua_read_alarms

alarm surfacing

R

low

{active_alarms[], active_count}

OPC-UA

opcua_read_history

Historical Access (HDA)

R

low

{supported, count, values[]}

OPC-UA

opcua_diagnose_connection

connection triage

R

low

{verdict, checks[]}

OPC-UA

opcua_discover_tags

tag auto-discovery → semantic asset model

R

low

{tag_count, assets[], naming_report}

OPC-UA

opcua_health_summary

threshold classify (was health_summary¹)

R

low

{overall, counts, offenders[]}

OPC-UA

opcua_anomaly_scan

stddev outliers (was anomaly_scan¹)

R

low

{mean, stddev, outliers[]}

Modbus

modbus_read_holding

FC03

R

low

{raw_registers, decoded[]}

Modbus

modbus_read_input

FC04

R

low

{raw_registers, decoded[]}

Modbus

modbus_read_coils

FC01

R

low

{bits[]}

Modbus

modbus_read_discrete

FC02

R

low

{bits[]}

Modbus

modbus_detect_byte_order

byte/word-order auto-detect

R

low

{best_order, candidates[]}

Modbus

modbus_list_templates

vendor register templates

R

low

{templates[]}

Modbus

modbus_apply_template

decode block via template

R

low

{values:{name: engineering_value}}

Modbus

modbus_health_summary

threshold classify

R

low

{overall, counts, offenders[]}

S7comm

s7_cpu_info

CPU id + run/stop

R

low

{cpu_status, cpu_info}

S7comm

s7_read_area

read DB/M/I/Q

R

low

{items:[{address, value}]}

S7comm

s7_read_db

read data block

R

low

{items:[{address, value}]}

S7comm

s7_read_many

batch addresses

R

low

{items:[{address, value}]}

S7comm

s7_write_db

write data block

W

high/MOC

{before, written, _undo_id}

Mitsubishi MC

mc_cpu_status

CPU type

R

low

{cpu_type, cpu_code}

Mitsubishi MC

mc_read_words

word devices

R

low

{words[]}

Mitsubishi MC

mc_read_bits

bit devices

R

low

{bits[]}

Mitsubishi MC

mc_read_many

random read

R

low

{words[], dwords[]}

Mitsubishi MC

mc_write_words

write words

W

high/MOC

{before, written, _undo_id}

Omron FINS

fins_cpu_info

controller data read (0501)

R

low

{controller_model, controller_version}

Omron FINS

fins_cpu_status

controller status (0601)

R

low

{run_mode, status}

Omron FINS

fins_read_words

memory-area word read (DM/CIO/W/H/A/EM)

R

low

{words[]}

Omron FINS

fins_read_bits

memory-area bit read

R

low

{bits[]}

Omron FINS

fins_read_many

batch reads

R

low

{items[]}

Omron FINS

fins_write_words

memory-area write

W

high/MOC

{before, written, _undo_id}

MTConnect

mtconnect_probe

device model

R

low

{devices:[{components:[{data_items}]}]}

MTConnect

mtconnect_current

latest values

R

low

{observations[]}

MTConnect

mtconnect_sample

bounded stream

R

low

{observations[]}

MTConnect

mtconnect_assets

assets

R

low

{assets[]}

MTConnect

mtconnect_oee_snapshot

OEE inputs

R

low

{availability, execution, verdict}

MQTT/Sparkplug

mqtt_read_topic

bounded read

R

low

{messages:[{topic, payload}]}

MQTT/Sparkplug

sparkplug_subscribe_sample

bounded SpB sample (full decode)

R

low

{samples:[{sparkplug, payload:{metrics[]}}], seq_gap_count}

MQTT/Sparkplug

sparkplug_decode_payload

decode raw SpB payload

R

low

{metrics:[{name, alias, datatype, value, is_historical}]}

MQTT/Sparkplug

sparkplug_node_list

node discovery + state

R

low

{nodes:[{group_id, edge_node_id, online, devices}], primary_hosts[]}

MQTT/Sparkplug

uns_browse

topic-tree browse

R

low

{topics[], tree{}}

MQTT/Sparkplug

uns_topic_audit

UNS naming + sprawl governance

R

low

{verdict, sprawl_findings, findings{casing_collisions[], scattered_leaves[], …}}

MQTT/Sparkplug

uns_schema_drift

Sparkplug schema-drift (baseline vs current)

R

low

{verdict (none/additive/breaking), node_changes[]}

MQTT/Sparkplug

uns_live_audit

live UNS audit (bounded broker sample)

R

low

{verdict, findings{}}

MQTT/Sparkplug

sparkplug_live_schema

live NBIRTH schema snapshot

R

low

{nodes[], metrics[]}

MQTT/Sparkplug

sparkplug_point_draft

observed BIRTH metrics → unconfirmed point refs

R

low

{candidate_tags[], complete:false}

MQTT/Sparkplug

uns_live_drift

live drift vs stored baseline

R

low

{verdict, node_changes[]}

MQTT/Sparkplug

mqtt_publish

publish/command

W

high/MOC

{published_bytes, applied}

EtherNet/IP

eip_controller_info

Logix controller id

R

low

{controller:{vendor, product_name, revision, serial}}

EtherNet/IP

eip_list_tags

tag discovery

R

low

{tag_count, tags:[{name, data_type, structure}]}

EtherNet/IP

eip_read_tag

read one tag/array

R

low

{tag, value, type, good}

EtherNet/IP

eip_read_many

batch read

R

low

{items:[{tag, value, type}]}

EtherNet/IP

eip_write_tag

write tag

W

high/MOC

{before, written, _undo_id}

Diagnostics

diagnose_dataflow

localize no-data

R

low

{verdict, diagnosis, hops[]}

Diagnostics

alarm_bad_actors

ISA-18.2 flood

R

low

{flood_verdict, top_offenders[]}

Diagnostics

tag_health

offender ranking

R

low

{overall, offenders[]}

Diagnostics

historian_health

gap/flatline

R

low

{verdict, gaps[]}

Diagnostics

subscription_health

sequenced-feed loss/reorder/overload

R

low

{verdict, missed_count, overloaded_channels[]}

Diagnostics

downtime_root_cause

AI downtime RCA copilot (cited, advisory)

R

low

{verdict, primary_cause, hypotheses:[{cause, confidence, evidence[]}]}

Diagnostics

downtime_root_cause_live

RCA copilot that gathers its own live evidence

R

low

{…downtime_root_cause…, collected_evidence}

Diagnostics

learn_cause_weights

learn per-site RCA cause weights from labeled incidents

R

low

{cause_weights{}, rationale}

Diagnostics

data_quality_scorecard

fleet data-trust rollup

R

low

{fleet_score, fleet_status, issue_breakdown, worst_tags[], endpoints[]}

Diagnostics

data_quality_fleet_rollup

cross-endpoint fleet view

R

low

{fleet_score, endpoints[]}

Diagnostics

heartbeat_health

heartbeat/watchdog liveness

R

low

{alive, distinct_transitions, longest_stall_s, reason}

Alarm (ISA-18.2)

alarm_flood_analysis

flood episodes / chattering / stale / summary

R

low

{episodes[], chattering[], stale[], summary{}}

Alarm (ISA-18.2)

alarm_rationalization_worksheet

CSV-exportable rationalization rows

R

low

{rows[], csv_path?}

Baseline

baseline_learn

conservative change-log baseline (refuses thin history)

R

low

{band{p1,p99,median,mad} | insufficient_data}

Baseline

baseline_check

silent-by-default violation check

R

low

{status, violations[] (cited)}

Baseline

baseline_record_change

record operator change (restarts learning)

R

low

{recorded, change_point}

Baseline

baseline_status

no_baseline / learning / ok / violation

R

low

{status, window}

Historian

historian_query

read history back out of sqlite/TDengine/IoTDB

R

low

{rows[], truncated}

Historian

historian_coverage

per-tag row counts + first/last ts

R

low

{tags:[{tag, rows, first, last}]}

PLC program

plc_program_outline

structure of exported ST/AWL/L5X program

R

low

{blocks[], call_graph, timers[]}

PLC program

plc_program_xref

symbol/address cross-reference (cited lines)

R

low

{sites:[{kind, source_file, line, quote}]}

PLC program

plc_program_xref_config

program addresses ↔ one endpoint's configured points, exact address only (never by name); optional live read of matched points

R

low

{comparable, matched, in_export_not_configured, configured_not_in_export, unmatchable}

PLC program

plc_program_section

one named block's source (≤200 lines)

R

low

{text, source_file}

Export

export_data

export local store → CSV/SQLite/Parquet

R

low

{path, row_count, preview[]}

Analytics

oee_compute

OEE = A×P×Q

R

low

{availability, performance, quality, oee, oee_pct}

Analytics

downtime_events

stoppage detect + categorize

R

low

{event_count, total_downtime_s, by_category, events[]}

Analytics

oee_multidim

OEE machine×part×shift

R

low

{matrix[], worst_performers[], mean_oee}

Analytics

asset_inventory

active fingerprint

R

low

{assets:[{protocol, vendor, model, firmware, reachable}]}

Analytics

cross_protocol_asset_model

merge discovered tags into one asset model

R

low

{assets[], tag_count}

Analytics

adopt_alias_map / diff_alias_map

tag alias-map adopt/diff

R

low

{aliases{}, changes[]}

Analytics

monitor_changes

bounded change-of-value

R

low

{change_count, changes:[{value, previous, wall_clock}]}

EtherCAT

ethercat_master_state

master/WKC + slave count

R

low

{master_state, expected_working_counter, slaves_found, slaves_expected}

EtherCAT

ethercat_slaves

bus scan

R

low

{slave_count, slaves:[{index, name, vendor_id, product_code, state}]}

EtherCAT

ethercat_slave_info

slave detail

R

low

{sync_managers[], fmmus[], object_dictionary[], input_bytes}

EtherCAT

ethercat_read_sdo

CoE SDO upload

R

low

{index, byte_length, hex, as_uint}

EtherCAT

ethercat_read_pdo

input PDO snapshot

R

low

{working_counter, input_hex, input_byte_length}

EtherCAT

ethercat_write_sdo

CoE SDO download

W

high/MOC

{before, written, applied}

EtherCAT

ethercat_set_state

AL-state transition

W

high/MOC

{before, requested, reached, applied}

PROFINET

profinet_discover

DCP IdentifyAll (segment-wide)

R

low

{station_count, stations:[{name_of_station, mac, ip, vendor_id, device_roles[]}]}

PROFINET

profinet_identify_station

identify by name-of-station

R

low

{found, name_of_station, mac, ip, device_family}

PROFINET

profinet_station_params

targeted DCP Get (by MAC)

R

low

{found, name_of_station, ip, netmask, gateway}

PROFINET

profinet_asset_inventory

DCP asset register

R

low

{asset_count, io_controller_count, assets[]}

PROFINET

profinet_dcp_set

DCP Set (station name / IP suite)

W

high/MOC

{before, applied, _undo_id}

SECS/GEM

secsgem_equipment_status

GEM link + identity (S1F1/F2)

R

low

{communication_state, are_you_there}

SECS/GEM

secsgem_list_status_variables

SVID namelist (S1F11/F12)

R

low

{count, status_variables[]}

SECS/GEM

secsgem_read_status_variables

SVID values (S1F3/F4)

R

low

{svids, values[]}

SECS/GEM

secsgem_list_equipment_constants

ECID namelist (S2F29/F30)

R

low

{count, equipment_constants[]}

SECS/GEM

secsgem_read_equipment_constants

ECID values (S2F13/F14)

R

low

{ecids, values[]}

SECS/GEM

secsgem_list_alarms

alarm list (S5F5/F6)

R

low

{count, alarms[]}

SECS/GEM

secsgem_list_process_programs

PPID directory (S7F19/F20)

R

low

{count, process_programs[]}

BACnet (building)

bacnet_discover

Who-Is device discovery

R

low

{device_count, devices:[{device_id, address}]}

BACnet (building)

bacnet_object_list

a device's objects

R

low

{object_count, objects:[{object_type, instance}]}

BACnet (building)

bacnet_read_property

one object property

R

low

{object_type, instance, property, value}

BACnet (building)

bacnet_read_points

all present-values (HVAC snapshot)

R

low

{point_count, points:[{object_type, instance, present_value}]}

BACnet (building)

bacnet_cov_subscribe

bounded COV capture (always unsubscribes)

R

low

{notifications[], terminated_reason}

BACnet (building)

bacnet_read_trend_log

TrendLog readRange (bounded)

R

low

{records:[{timestamp, value}]}

BACnet (building)

bacnet_write_property

present-value write (priority)

W

high/MOC

{before, written, _undo_id}

HART-IP (process)

hart_device_identity

cmd 0 identity

R

low

{manufacturer, device_type, revision}

HART-IP (process)

hart_primary_variable

cmd 1 PV

R

low

{value, unit}

HART-IP (process)

hart_dynamic_variables

cmd 3 PV/SV/TV/QV + loop current

R

low

{variables[], loop_current}

HART-IP (process)

hart_burst_sample

bounded burst-variable sampling

R

low

{samples[]}

IO-Link

iolink_master_info

master identity

R

low

{vendor, product, serial}

IO-Link

iolink_ports

≤32-port sweep (mode/status/device id)

R

low

{ports[]}

IO-Link

iolink_device_info

per-port device identity

R

low

{vendor_id, device_id, product_name}

IO-Link

iolink_read_pdin

process-data-in (raw hex + bytes)

R

low

{hex, bytes[]}

IO-Link

iolink_read_isdu

ISDU acyclic parameter read

R

low

{index, subindex, value}

IO-Link

iolink_scan

master + all connected devices

R

low

{master{}, devices[]}

Serial ASCII

serial_sniff

raw lines from a serial instrument (sends nothing)

R

low

{endpoint, seconds, lines[], note}

Sensor (IAIOPS_MCP=sensor)

sensor_import_iodd

draft a profile from an IODD (待核实; returns text, writes nothing; reads only under the agent read roots — see Safety & governance)

R

low

{draft, profile_id, device_name, notes[]}

Sensor (IAIOPS_MCP=sensor)

sensor_profile_check

validate a profile file, list its channels (reads only under the agent read roots)

R

low

{id, protocol, verified, channels:[{channel, layout, unit, signal, band}]}

Sensor (IAIOPS_MCP=sensor)

sensor_read_channel

read one point once; reachable / decodable reported separately

R

low

{levels:{reachable, decodable}, value?, unit?, band?, verified?}

Sensor (IAIOPS_MCP=sensor)

sensor_profile_list

list the shipped profile library (every entry 待核实 unless it carries provenance)

R

low

{profiles:[{id, protocol, verified, caveat}]}

Sensor (IAIOPS_MCP=sensor)

sensor_profile_show

one library profile: summary + YAML text (writes nothing)

R

low

{summary, yaml, next}

BAS (Metasys/Niagara)

bas_point_list

supervisory point directory

R

low

{point_count, points:[{id, name, type}]}

BAS (Metasys/Niagara)

bas_point_read

read one supervisory point

R

low

{point, value, unit, status}

BAS (Metasys/Niagara)

bas_alarm_list

active controller alarms

R

low

{alarm_count, alarms:[{id, priority, state}]}

BAS (Metasys/Niagara)

bas_trend_read

trend/history samples (bounded)

R

low

{records:[{timestamp, value}]}

BAS (Metasys/Niagara)

bas_command

supervisory command (default-OFF; life-safety object denylist refuses fire/smoke/egress/pressurization before any I/O)

W

high/MOC

{before, written, _undo_id}

Ignition

ignition_gateway_status

Gateway + module health

R

low

{state, version, modules:[{name, state}]}

Ignition

ignition_tag_browse

tag-tree browse

R

low

{tags[], tree{}}

Ignition

ignition_tag_read

current tag values

R

low

{values:[{path, value, quality, timestamp}]}

Ignition

ignition_alarm_status

active alarms

R

low

{alarm_count, alarms:[{path, priority, state}]}

Ignition

ignition_tag_history

tag-history query (bounded)

R

low

{rows:[{path, timestamp, value}]}

信创 / compliance

compliance_mapping

《工控网络安全防护指南》↔ iaiops

R

low

{pillars[], status_summary, controls:[{pillar, status, gap}]}

信创 / compliance

compliance_frameworks

等保 2.0 + IEC 62443 FR1–6 + GxP crosswalk; framework="nis2"|"cra" = NIS2 Art. 21 / CRA Annex I item by item

R

low

{crosswalk[]} | {items:[{ref, coverage, mechanisms, gap}]}

信创 / compliance

compliance_dengbao_levels

等保 二级 baseline vs 三级 增量

R

low

{pillars:[{l2, l3_delta, status}]}

信创 / compliance

compliance_report

deliverable compliance report (md/html); framework="nis2"|"cra"|"eu" for the English EU self-assessment

R

low

{markdown | out_path}

信创 / compliance

compliance_evidence_bundle

audit-evidence zip (hash-chain verified)

R

low

{bundle_path, manifest}

信创 / historian

historian_push

push telemetry to sqlite/TDengine/IoTDB

R(→historian)

low

{sink, received, written, skipped_non_numeric}

Self

protocols_supported

capability map

R

low

{protocols[], diagnostics[], analytics[]}

(The energy protocols — IEC-104 / DNP3 / IEC-61850 — moved to iaiops-energy in 0.8.0; their tool matrix lives in that repo.)

206 governed tools = 189 read + 4 that change nothing on a device but send data off-box (stream_publish, stream_publish_event, uns_publish, rca_narrate) + 10 MOC-gated device writes + historian_push (a write, to a historian rather than to a device: [WRITE][risk=low]) + the 2 deprecated aliases below. The device writes are (s7_write_db, mc_write_words, fins_write_words, mqtt_publish, eip_write_tag, ethercat_write_sdo, ethercat_set_state, profinet_dcp_set, bacnet_write_property, bas_command). The read side now includes two vendor-REST read-only layers above the field protocols — a BAS controller layer (Metasys/Niagara, building edition) and an Ignition Gateway MES/SCADA layer (factory edition). ¹ The 2 deprecated aliases are the two deprecated brain aliases health_summary / anomaly_scan, renamed to opcua_health_summary / opcua_anomaly_scan in 0.10.0 — the deprecated aliases are still registered and will be removed in a future release (target: 1.0.0). Read-only per-edition tools load ONLY under their edition (see per-edition tool modules below), so a bare protocol / single-edition surface is smaller than this line-wide total. The table above is representative, not exhaustive; run protocols_supported() (or iaiops protocols) for the live map.


Per-protocol reference

OPC-UA

  • Versions/variants: binary opc.tcp:// via asyncua (sync facade). Security: anonymous + username/password, plus application-certificate message security (Sign / SignAndEncrypt) — set client_cert + client_key (+ optional server_cert) and the client opens a signed/encrypted secure channel (no cert ⇒ the anonymous / username path is unchanged). Validated end-to-end against an in-process asyncua server (tests/test_opcua_security.py) for Basic256Sha256 in both Sign and SignAndEncrypt modes: server_cert pinning and client-side server-cert auto-discovery are exercised, and the test asserts the negotiated policy URI + message-security mode on the live encrypted channel (plus a negative test that anonymous is refused by a secure-only server).

  • Connection params: endpoint_url, username (password encrypted), security_mode, security_policy; for cert security client_cert / client_key / optional server_cert (PEM or DER paths; aliases certfile / keyfile).

  • Alarms & Conditions: opcua_alarm_events — bounded event subscription + ConditionRefresh, events carry the server's own timestamps (verified against an in-process asyncua server; third-party A&C servers 待核实). Untimed fallback: opcua_read_alarms browses alarm-like boolean nodes.

  • Not supported / planned (待核实): cert-security interop with third-party / vendor servers (KEPServerEX / Prosys / Siemens / real PLCs), the other policies (Aes128Sha256RsaOaep / Aes256Sha256RsaPss / Basic128Rsa15 / Basic256), strict server-side certificate-trust enforcement, and cert-based user identity (X509 identity token, distinct from channel security).

Modbus-TCP / Modbus-RTU

  • Versions/variants: Modbus-TCP and Modbus-RTU (serial RS-485/232) via pymodbus (+ pyserial). Read function codes FC01 (coils), FC02 (discrete), FC03 (holding), FC04 (input). Write FCs (FC05/06/15/16) = not implemented (read-only).

  • Connection params: TCP — host, port (502), unit_id. RTU — transport: rtu, serial_port (e.g. /dev/ttyUSB0), baudrate, unit_id. Registers are untyped 16-bit words → decode hint (uint16/int16/uint32/int32/float32/raw); modbus_detect_byte_order auto-detects the byte/word order (AB/BA · ABCD/DCBA/BADC/CDAB) from hint values — pure logic, no extra device load.

  • Typed points for collection (HLD §16): a collected/monitored ref can name its table, type, word order and scale — ir:0:float32:CDAB, hr:12:int16*0.1 (grammar <hr|ir>:<addr>[:<type>[:<order>]][*<scale>]; a 32-bit type must state its order). With sensor_profile: <file> on the endpoint, ch:<name> reads a channel of that profile (sentinels → gaps, declared range enforced). A bare address keeps its old meaning (one holding register, uint16) and readiness reports it as untyped. Switching sensors (NPN / PNP / dry contact) on a DI module read as di:<addr>:<high|low> (FC02) or co:<addr>:<high|low> (FC01): the active level is required (a normally-closed switch reads 0 when actuated), the value is 1 = actuated, and readiness reports a count_source gap when a switching point is declared as the production counter (polling misses short pulses) — checked on Modbus refs only; PLC bits are not yet checked. A shipped profile library (iaiops sensor list | show, MCP sensor_profile_list | show) holds community register maps for common energy meters and PV inverters, each derived from the Modbus template of the same device and carrying its caveat — every entry 待核实; CI checks each entry against its template channel by channel, in both directions. Copy one (show <id> --out <file>), check a reading against the device's display, then bind the copy.

  • Vendor register templates (modbus_list_templates / modbus_apply_template): named register maps decoding a block into engineering values — energy meters (Eastron SDM630, Schneider PM5xxx, Carlo Gavazzi EM24), PV inverters (Huawei SUN2000, Growatt), Phoenix PLCnext process data, and water-industry templates (E+H Promag, Hach SC controller, generic dosing pump). Each template carries an explicit 待核实 caveat — no invented "verified" addresses.

  • Coverage: many domestic 国产 PLCs (汇川 Inovance / 信捷 Xinje / 和利时 Hollysys / 台达 Delta) and any Modbus vendor. RTU framing is live-verified over a real serial link (socat PTY + pymodbus RTU server); specific physical RS-485 devices stay 待核实.

S7comm (Siemens + 仿西门子 国产)

  • Versions/variants: pyS7 (pure-Python, ISO-on-TCP / RFC1006 — no native libsnap7). S7-300/400/1200/1500 and compatible clones. Memory areas DB / M (merker) / I / Q. No protocol auth (CPU gates via "Permit access with PUT/GET").

  • Connection params: host, port (102), rack, slot (0/1 for 1200/1500; 0/2 common for 300/400).

  • Write: s7_write_db = high risk_tier, MOC, dry-run default, captures BEFORE value + undo.

  • Not supported / planned: optimized/symbolic DB access on 1500 with "optimized block access" can require absolute-addressing config on the CPU.

Mitsubishi MC

  • Versions/variants: pymcprotocol — MC 3E frame (binary) only. 1E / 4E frames = not supported. PLC types Q / L / QnA / iQ-R / iQ-L. Devices: D/W/R (word), M/X/Y/B (bit).

  • Connection params: host, port (5007 default; set to the module's open MC port), plctype.

  • Write: mc_write_words = high/MOC/dry-run default, captures BEFORE + undo.

Omron FINS (CS/CJ/CP/NX-via-FINS)

  • Versions/variants: in-repo, stdlib-only FINS client (no third-party dependency — the iaiops[fins] extra pins nothing): 10-byte FINS header framing, FINS/UDP (default port 9600) and FINS/TCP (node-address handshake per Omron W342), SID matching, bounded response parsing, end-code table per W227/W342. Commands: 0101 memory-area read (words/bits over DM/CIO/W/H/A/EM), 0102 write, 0501 controller data read, 0601 controller status.

  • Connection params: host, port (9600), transport (udp default / tcp), FINS network/node/unit addressing.

  • Write: fins_write_words = high/MOC/dry-run default, captures BEFORE + undo; CLI double-confirm on --apply.

  • Validation: verified against an in-repo mock FINS UDP/TCP responder (tests/test_fins.py); live Omron PLC behaviour and banked-EM access stay 待核实.

  • Versions/variants: sensor-level visibility via the IO-Link master's HTTP/JSON interface (IO-Link consortium "JSON Integration"), both dialects selectable per endpoint via flavor: — iotcore (ifm IoT-Core POST envelope, default) and rest (plain-REST GET, Balluff/Turck-style). Reads: master identity, bounded ≤32-port sweep, per-port device identity, process-data-in (raw hex + bytes), ISDU acyclic parameter read. NO write tools. Bounded/size-capped HTTP (256 KiB response cap), schema-checked JSON with teaching errors. Reuses the MTConnect HTTP pin (iaiops[iolink] → requests).

  • Connection params: master host/URL, flavor, timeout_s. protocol: iolink.

  • Collection (HLD §16): port_profiles: {<port>: <profile.yaml>} binds a sensor profile per port; port<N>/<channel> refs are then collectable (collect, monitor). A port without a profile is not decoded — refused, never guessed. If the profile carries match: {vendor_id, device_id}, the device on the port is checked before decoding (cached 5 s per master and port, dropped on any failed read). With pd_bits, a process-data image of another length is refused. iaiops sensor import-iodd <iodd.xml> drafts a profile from the vendor's IODD (verified: 待核实, unit codes left unmapped, unrepresentable items listed); iaiops sensor check validates one.

  • Validation: in-process mock master in both flavors (tests/test_iolink.py); profile decoding against a hand-written IODD-shaped fixture (tests/fixtures/iodd/). Live master datapoint paths, identity encodings and real vendor IODDs stay 待核实.

Serial ASCII instruments (scales, analysers, barcode readers, legacy meters — read-only)

  • Versions/variants: instruments that send one text line per reading over RS-232 / RS-485 / RS-422 / USB virtual COM (pyserial>=3.5, extra iaiops[serial], included in iaiops[sensor]) or through a serial device server's raw TCP socket. Decoding is a sensor profile (protocol: serial): framing (terminator, encoding, max line), mode: listen | poll (+ the ONE query poll may send), and per channel a regex that must match the whole line with a value group, status codes (ok / named invalid → gaps) and the unit fixed and/or from the line.

  • Safety rules: the port is opened exclusively — a port another program holds is refused, never taken (an advisory lock: a program that opened it without locking cannot be detected, 待核实 per OS). Poll needs bus: dedicated on the endpoint (shared = an RS-485 bus that already has a master: listen only); tare / zero / calibrate are not reads and do not belong in query. Listen needs stale_after_s (no line within it = a gap, never the last value). Collection requires a fixed unit per channel.

  • Tools: serial_sniff / iaiops serial sniff (raw lines, sends nothing); decoded reads via sensor_read_channel / iaiops sensor read; collection via iaiops collect run.

  • Validation: a pty pair through the real pyserial path, a local TCP device-server path, and a lab LAN walkthrough against our own weighing simulator (rung 2c — no third-party instrument). No serial profile ships — you write one per instrument (iaiops serial sniff shows the raw lines), and its line format stays 待核实 until checked against the real device.

HART-IP (process instrumentation — read-only)

  • Versions/variants: HART universal commands over HART-IP UDP (default, port 5094) or TCP (transport: tcp, length-delimited framing) via an in-tree transport; the HART command codec is verified vs hart-protocol. Tools: hart_device_identity (cmd 0), hart_primary_variable (cmd 1), hart_dynamic_variables (cmd 3, PV/SV/TV/QV + loop current), hart_burst_sample (bounded sampling of burst-published variables). No write / device-specific commands exposed (OT-dangerous on live instruments).

  • Connection params: host (HART-IP server/gateway), port (5094), transport (udp default / tcp).

  • Validation: TCP transport loopback-verified (in-process HART-IP server, real long-frame ACK through the real codec path); live gateway behaviour and a true unsolicited burst subscription stay 待核实.

MTConnect (ALL CNC machine tools)

  • Versions/variants: agent REST + XML (requests + xml.etree), namespace-agnostic (parses MTConnect 1.x Devices/Streams/Assets schemas). Endpoints: /probe, /current, /sample, /assets. Read-only by specification. XML parsing is hardened (DTD/entity declarations rejected — XXE/billion-laughs defense).

  • Connection params: agent_url (e.g. http://host:5000).

  • Not supported / planned: MTConnect streaming (long-poll interval=); only bounded count= samples.

MQTT / Sparkplug B / UNS

  • Versions/variants: paho-mqtt — MQTT 3.1.1 & 5. Sparkplug B topic convention spBv1.0/{group}/{type}/{edge}/[device] (NBIRTH/DBIRTH/NDATA/DDATA/NDEATH/DDEATH/STATE). TLS + username/password supported.

  • Full Sparkplug B decode (no optional extra): payloads are protobuf-decoded with a vendored, byte-for-byte copy of the official Eclipse Tahu sparkplug_b.proto generated module (depends only on protobuf). Per metric you get name, alias (resolved to its name via the BIRTH model), datatype (Int8…Int64/UInt…/Float/Double/Boolean/String/DateTime/Text/UUID/DataSet/Bytes/File/Template/PropertySet…), value, timestamp, and the is_historical / is_null flags. A birth/death + seq model tracks node/device online state (NBIRTH/DBIRTH ↔ NDEATH/DDEATH), builds the alias→name map from BIRTH, applies NDATA/DDATA by alias, and flags seq gaps / out-of-order. Primary-host awareness: STATE/<host_id> topics surface in sparkplug_node_list. sparkplug_decode_payload decodes a single raw payload (base64/hex) offline.

  • A data SOURCE, not just a bus (new): MQTT/Sparkplug is collectable — iaiops collect run holds ONE subscription open for the run and samples from its last-value cache, so a plant whose data is already unified into a UNS can be tapped without touching a PLC. Refusals are the feature. MQTT is pushed, and the obvious cache answers with the last value forever after a publisher dies — availability then reads 100% on a stopped line, in every subscriber at once. So a point is a reading only when it has been seen at all (never-published is not zero), is fresher than stale_after_s, and — for Sparkplug — its node has not sent NDEATH/DDEATH. Anything else raises OTNoReadingError, which the collector records as a gap (collection was blind), never as downtime.

  • stale_after_s is REQUIRED to collect, and deliberately has no default: a value that stopped updating and one that is simply constant are identical on the wire, so only the site knows how often a point is published. Guessing it here would put a guess underneath every availability figure. Same discipline as running_when on a run_state tag.

  • The two guarantees are not equal, and the endpoint is told which it has: Sparkplug gives staleness and death (the broker publishes the node's Last Will); plain MQTT has no death signal at all, so only staleness is available there and a quiet topic is indistinguishable from a dead publisher.

  • Refs: a plain-MQTT ref is the topic itself; a Sparkplug ref is group/edge[/device]:metric — exactly the node id mqtt live-schema reports, so its output is usable as config refs without translation. Payloads decode as a bare scalar or a {"value": …} / {"v": …} JSON envelope; an unknown envelope is not guessed at by picking its only number.

  • Connection params: host/broker, port (1883 / 8883 TLS), topic, use_tls, username (password encrypted), stale_after_s (required for collection).

  • Validation: verified end-to-end against a real eclipse-mosquitto:2 broker through the full paho loop (tests/test_uns_tap_live.py, opt-in) — publish → read → publisher stops → the run records a gap instead of repeating the cache. Also exercised across a real network on three separate hosts (broker, edge node, reader) against a spec-correct Sparkplug node — alias-only NDATA, periodic re-BIRTH, and a genuine broker-issued Last Will after the publisher was kill -9'd on another machine (refusal in ~2s with stale_after_s deliberately set to 60, so only the death signal could have caused it). 待核实: the edge node is still our own implementation, not a commercial EoN (Ignition / Litmus / HighByte), and not a commercial broker (HiveMQ / EMQX).

  • Command: mqtt_publish = high/MOC/dry-run default. A transient publish has no automatic inverse (delivered is delivered); a retained one overwrites durable broker state, so it captures the prior retained payload and records an inverse.

EtherNet/IP (Rockwell / Allen-Bradley)

  • Supported: ControlLogix / CompactLogix (and GuardLogix) via CIP / EtherNet-IP using pycomm3 (pure-Python — no native deps). Tag-based, symbolic access: read/write tags by name (Conveyor.Speed, Array[3], Program:Main.X) and discover the controller's tag list at runtime (eip_list_tags, the headline feature). eip_controller_info reads the controller identity.

  • Connection params: host, slot (0 for CompactLogix; the CPU slot for a ControlLogix chassis), port (44818). protocol: ethernetip (alias eip).

  • Write: eip_write_tag = high risk_tier, MOC, dry-run default, captures BEFORE value + undo.

  • Also supported (mocked drivers only — real hardware 待核实): PLC-5 / SLC-500 / MicroLogix via PCCC data-table addressing, and Micro800.

EtherCAT (pysoem / SOEM fieldbus master)

  • Supported: a real EtherCAT master via pysoem (the Python binding for the SOEM C stack). CoE SDO read (ethercat_read_sdo, acyclic mailbox upload) + SDO write (ethercat_write_sdo, download), input PDO read (ethercat_read_pdo, one bounded cyclic snapshot), bus scan / slave enumeration (ethercat_slaves, ethercat_slave_info — identity, SM/FMMU mapping, object-dictionary summary), master/working-counter state (ethercat_master_state), and AL-state transitions INIT↔PREOP↔SAFEOP↔OP (ethercat_set_state).

  • HARD REQUIREMENTS (no way around them): Linux, root or CAP_NET_RAW, a dedicated NIC cabled to the bus, and real EtherCAT slave hardware. pysoem is an OPTIONAL extra: pip install iaiops[ethercat] — the base package installs and imports without it, and every EtherCAT tool then degrades to a teaching error (never crashes, never imports pysoem at module load).

  • NOT supported: no software simulator exists (unlike OPC-UA / Modbus) — EtherCAT is hardware-only and not testable in mock-only CI; macOS is unsupported. EoE / FoE / SoE mailbox protocols and full PDO-mapping decode/expansion = roadmap.

  • Connection params: nic (the dedicated interface name, e.g. eth1; alias interface), optional expected_slaves (a sanity check vs the bus scan). protocol: ethercat.

  • Operations matrix:

    Tool

    Op

    R/W

    risk

    Capture/notes

    ethercat_master_state

    master + WKC state, slave count

    R

    low

    expected vs found

    ethercat_slaves

    bus scan / enumerate

    R

    low

    index/vendor/product/rev/addr/AL-state

    ethercat_slave_info

    one-slave detail

    R

    low

    SM/FMMU + OD summary

    ethercat_read_sdo

    CoE SDO upload

    R

    low

    hex + uint interpretation

    ethercat_read_pdo

    input PDO snapshot

    R

    low

    single cycle, never loops

    ethercat_write_sdo

    CoE SDO download

    W

    high/MOC

    before-value (SDO read-back) + undo

    ethercat_set_state

    AL-state transition

    W

    high/MOC

    before-state + undo; can start/stop motion

  • Write/state safety: ethercat_write_sdo (hex little-endian bytes) and ethercat_set_state are high risk_tier, MOC, dry-run by default, capture the BEFORE value/state for undo, and need a CLI double-confirm. Changing EtherCAT state can START or STOP machine motion — treat with extreme care. 未经授权勿对生产控制系统写入.

PROFINET (DCP discovery / identify + gated DCP Set)

  • Supported: layer-2 PROFINET-DCP via pnio-dcp — profinet_discover (DCP IdentifyAll: one broadcast surfaces every station on the segment — name-of-station, MAC, IP, vendor/device id, role — closer to passive discovery than a per-device fingerprint), profinet_identify_station (by name-of-station), profinet_station_params (targeted DCP Get by MAC → name + IP suite), and profinet_asset_inventory (a register with IO-controller vs IO-device role decoding).

  • Write: profinet_dcp_set re-addresses one station (name-of-station and/or IP suite, by MAC) — high risk_tier, MOC, dry-run default, captures the BEFORE addressing + undo descriptor. Re-addressing a live station can disrupt its IO connection.

  • Scope (deliberate): no RT cyclic process data (that needs an IO-controller/IO-device stack and hard real-time — out of scope and unsafe to tap); the blink / factory-reset DCP services stay unexposed.

  • HARD REQUIREMENTS: raw-socket access (root / admin / CAP_NET_RAW) on the NIC on the PROFINET subnet. pnio-dcp is an OPTIONAL extra: pip install iaiops[profinet] — the base package installs/imports without it, and every tool then degrades to a teaching error.

  • Connection params: host — THIS machine's IP on the PROFINET subnet (the DCP broadcast goes out on it). protocol: profinet.

  • Preview caveat: validated against a mocked pnio-dcp DCP — not verified against live PROFINET devices yet.

Energy edition (electrical substation / utility telecontrol) → iaiops-energy

The energy vertical — IEC 60870-5-104 / DNP3 / IEC 61850 MMS read-only monitoring for substation RTUs/IEDs — moved to its own package in 0.8.0: iaiops-energy (pip install iaiops-energy), built on iaiops.core (shared governance / brain / runtime). Its protocol reference, support matrix, and validation status live in that repo.

Building edition (facility / HVAC / 厂务)

The building vertical adds BACnet/IP (ASHRAE 135) — the dominant building-automation protocol for HVAC, lighting, metering, and facility plant. Install with pip install iaiops[building] and expose with IAIOPS_MCP=building (bundle: bacnet + modbus + opcua + iolink).

  • BACnet/IP (BAC0 over bacpypes3): bacnet_discover (Who-Is device discovery), bacnet_object_list (a device's objects), bacnet_read_property (one object property), bacnet_read_points (present-value of all analog/binary/multistate points — the HVAC snapshot), bacnet_cov_subscribe (bounded change-of-value capture — capped by count AND wall-clock, always unsubscribes), bacnet_read_trend_log (TrendLog buffered records via one bounded readRange). Config: host = THIS machine's BACnet/IP interface (ip or ip/mask) / port (47808).

  • Write: bacnet_write_property (present-value at a BACnet priority 1..16, or relinquish) = high risk_tier, MOC, dry-run default, BEFORE-value read-back + undo. Overriding a live building-control point can move real HVAC/plant.

  • Validation: the read path is verified against a real bacpypes3 virtual BACnet/IP device through the actual async BAC0 stack (tests/test_bacnet_live.py); COV / trend-log / writes on live HVAC gear stay 待核实.

Water treatment edition (水处理)

IAIOPS_MCP=water (or iaiops-mcp-water, pip install iaiops[water]) exposes modbus + opcua + hart + the brain — the protocol set waterworks / wastewater plants actually run. Adds water-domain tag semantics (溶解氧 DO / ORP / 余氯 chlorine / 氨氮 ammonia / TSS/MLSS / 跨膜压差 TMP / UV / 加药 dosing / 曝气 aeration) and water-industry Modbus templates (E+H Promag, Hach SC controller, generic dosing pump — all with explicit 待核实 caveats).

Warehouse / intralogistics edition (仓储 / 物料搬运)

IAIOPS_MCP=warehouse (or iaiops-mcp-warehouse, pip install iaiops[warehouse]) exposes eip + profinet + modbus + opcua + sparkplug + the brain — conveyor & sorter drives over EtherNet/IP (Rockwell) and Profinet (Siemens), VFD / energy meters over Modbus (conveyor_vfd / agv_battery templates), WMS/WCS gateways over OPC-UA, and AMR/IoT telemetry over MQTT-Sparkplug. Edition tools (read-only, advisory): line_bottleneck (Theory-of-Constraints throughput bottleneck across stations) + sortation_health. PdM (pdm_forecast), downtime_triage and OEE are reused as-is.

Clinical-facility edition (医疗设施)

IAIOPS_MCP=clinical (or iaiops-mcp-clinical, pip install iaiops[clinical]) exposes bacnet + modbus + opcua + the brain — hospital facilities as a distinct patient-safety vertical over the building brain. Edition tools (read-only, advisory): isolation_room_check (负压/正压 isolation-room pressurization), medical_gas_check (medical-gas alarm-panel safety), or_environment_check (OR temperature / humidity / pressure envelope). BACnet BMS + Modbus gas-alarm panels + OPC-UA plant SCADA.

Pharmaceutical-manufacturing edition (制药)

IAIOPS_MCP=pharma (or iaiops-mcp-pharma, pip install iaiops[pharma]) exposes bacnet + modbus + hart + opcua + the brain. No new protocol — that is the point: no field protocol is specific to pharma. Cleanrooms run BACnet, purified-water systems run Modbus and HART, filling and lyophilization run S7, DCS and bioreactors run OPC-UA, and all of it was already here. What pharma needed was semantics: the water edition's indicators are municipal (DO, ORP, chlorine, turbidity) and the clinical edition grades one room's pressure, where Annex 1 inspects the cascade.

Edition tools (read-only, advisory): cleanroom_pressure_cascade (EU GMP Annex 1, door by door — adjacency is declared, never inferred from a room list), cleanroom_particle_check, pharma_water_check (USP <645> stage-1 procedure: the non-temperature-compensated reading, the measured temperature rounded down to the tabulated step, and exceeding stage 1 reported as proceed to Stage 2 rather than as a failure).

No compendial limit tables are shipped. The particle limits, the stage-1 conductivity table and the TOC limit belong to the site's qualified specification at its compendial revision. A transcription nobody in this repository can verify would end up deciding whether a batch environment passed — and the error that hurts is the flattering one, since a limit set too loose reads as "in specification". Limits are passed in and cited back; anything not declared is reported no_limit / not_graded and named, never counted as passing. Known gaps are listed in the edition's skill: no PI historian connector, S7 without hardware verification, and LIMS / QMS deliberately out of scope — they run REST and databases, not field protocols.

Renewables edition (光伏 / 风电)

IAIOPS_MCP=renewables (or iaiops-mcp-renewables, pip install iaiops[renewables]) exposes modbus + opcua + sparkplug + the brain — PV inverters (SUN2000 / Growatt templates) + wind-turbine controllers over Modbus, OPC-UA plant SCADA, and MQTT-Sparkplug telemetry. Edition tool (read-only, advisory): pv_performance (PV string performance vs expectation). Device-level monitoring + PdM via baseline / RCA.

Half-hourly electricity metering (supplier HH files — building & renewables editions)

A supplier's half-hourly (HH) electricity file, read and explained — the data every UK non-domestic meter produces as market-wide half-hourly settlement completes. No device is contacted; the input is a file. iaiops meter check FILE says what the file contains (wide layout: date + 46–50 half-hour columns; long layout: timestamp + kWh) and what was rejected; iaiops meter profile FILE [--hours 'mon-fri 08:00-18:00'] [--holiday YYYY-MM-DD] [--tariff tariff.yaml] [--report out.html] reports overnight base load, out-of-hours use against the declared operating hours, peak demand, complete-day working vs closed averages, load factor, a weekday × time heatmap and — with a tariff — cost by time band and an upper bound for moving use out of the dearest band. MCP (building + renewables editions): meter_hh_check, meter_load_profile (same engine; the HTML report is CLI-only). Demo: demo/metering/.

  • What it refuses to do: a blank cell is missing, never zero; totals are measured only, never scaled up over gaps; dates are UK day-first only (01/13/2026 is rejected, not reread); a file with no actual/estimated flag reports read type unknown, not "actual"; out-of-hours use above base load is labelled an indication, not a saving.

  • Clock days: the UK clock (GMT/BST) is computed from its rule — no tzdata needed — so the 46- and 50-period clock-change days are read correctly.

  • Not built in: DNO DUoS red/amber/green times (they vary by region — pass them in a tariff; demo/metering/tariff_example.yaml is illustrative only), VAT, CCL, kVA capacity and reactive charges (listed as excluded on every cost). Validation: synthetic files and the unit suite only — no real supplier file has been run through it yet (待核实).

PLCnext packaging edition (Phoenix Contact vPLC)

IAIOPS_MCP=plcnext (or iaiops-mcp-plcnext, pip install iaiops[plcnext]) exposes opcua + modbus + the brain — the Phoenix Contact PLCnext virtualized PLC reached over its built-in OPC-UA server (opc.tcp 4840, Arp.Plc.Eclr address space) + Modbus-TCP process-data server; no new connector. Route-verified in-process; live PLCnext hardware reads stay 待核实 (see How far it's actually been verified).

信创 / China entry (offline · 国产 TSDB · compliance)

For 自主可控 / 信创 deployments — see docs/CHINA.md for the full guide.

  • Air-gapped install: pure-Python core + per-protocol optional extras → install from a local wheelhouse with pip install --no-index --find-links ./wheelhouse "iaiops[...]"; secrets stay local (encrypted store), no cloud KMS.

  • National TSDB historian sink (historian_push, CLI iaiops historian push): write collected telemetry to TDengine (iaiops[tdengine]) or Apache IoTDB (iaiops[iotdb]) — domestic, controllable; we don't build our own store or bind InfluxDB. Data egress to the operator's own historian, not a control write.

  • Compliance mapping (compliance_mapping, CLI iaiops compliance): an honest 《工控系统网络安全防护指南》 ↔ iaiops self-assessment across 分区隔离 / 可审计 / 双向认证 / 最小权限 / 数据保护 / 自主可控, with per-control status (addressed / partial / 待核实) and the named gap.

  • 国产 PLC: 汇川 / 台达 / 信捷 over the existing Modbus-TCP / S7 connectors.

  • ⚠️ 待核实: 国产 OS (麒麟/统信) · 芯 (鲲鹏/海光) · PLC validation and the TSDB write paths are documented but not yet hardware-verified — see the validation matrix in docs/CHINA.md.

OEE / downtime analytics (cross-protocol, read-only)

  • oee_compute — OEE = Availability × Performance × Quality from production inputs (planned time, run time, ideal cycle, total/good counts). Each factor is reported raw + clamped to [0,1]; a capped performance >1.0 flags an optimistic ideal cycle.

  • downtime_events — auto-detects running→stopped transitions in a {timestamp, state} series and produces stoppage events with durations, categorized (changeover / material / mechanical / quality / break / unknown, by keyword heuristics or a {state: category} override).

  • oee_multidim — aggregates OEE across machine × part × shift (or any dimensions) from labelled records → the matrix + worst performers.

  • Operate over provided/collected inputs (fully testable without a plant). mtconnect_oee_snapshot surfaces the live MTConnect availability/execution inputs that feed these.

Active asset inventory / fingerprint (read-only)

  • asset_inventory — for each configured (or named) endpoint, actively connects with our own protocol client and reads its identity call (S7 s7_cpu_info, EtherNet/IP eip_controller_info, OPC-UA server build info, Modbus Device Identification FC43/0x2B, Mitsubishi CPU type, MTConnect device model), aggregating vendor / model / firmware / serial / reachable / last_seen into an asset register.

  • Honest scope (IEC 62443-flavored): this is ACTIVE fingerprinting via our client connections, NOT passive SPAN/tap discovery — it only finds devices we are configured to reach and adds light load to each. Passive, traffic-mirroring discovery is roadmap.

OPC-UA Historical Access (HDA)

  • opcua_read_history — reads stored historical values for a node over a [start,end] ISO-8601 window via the server's HistoryRead service (asyncua read_raw_history), bounded by max_points (≤2000). Returns {supported:false, note} gracefully when the server does not historize the node (no crash). Read-only.

Change-of-value (CoV) monitor

  • monitor_changes — bounded deadband report: polls a point and returns only the value CHANGES (with timestamps), not every sample. Works over OPC-UA / Modbus / S7 / Mitsubishi MC / EtherNet-IP. Never an infinite loop — hard-capped by both duration_s (≤120) and max_changes (≤500). Read-only.

Cross-protocol brain — 0.9/0.10 additions (all read-only)

  • Conservative baseline learning (baseline_learn/check/record_change/status, CLI iaiops baseline …) — a change-log baseline, explicitly NOT black-box anomaly detection: robust p1/p99 + median/MAD band over the local history, refuses thin history (<100 samples or <24h) with an explicit insufficient_data verdict, restarts at recorded operator changes, and is silent by default — a violation needs >3×MAD beyond the band AND ≥3 consecutive samples, and every violation cites its baseline window and offending samples.

  • Historian READ integration (historian_query / historian_coverage, CLI iaiops historian query|coverage) — query history back out of the sqlite/TDengine/IoTDB sinks; an optional per-site historian: config block lets the RCA copilot pull the 2h pre-incident window as one more cited evidence class (strictly additive — without the config, RCA output is byte-identical, test-proven).

  • Legacy PLC program explainer (plc_program_outline/xref/section, CLI iaiops program …) — structural extraction over exported program files (Siemens SCL/ST .scl/.st, AWL/STL .awl, Rockwell Studio 5000 .L5X — never a live PLC upload); every element carries source_file + line (rung for L5X) so the explaining agent must cite real locations. XXE-hardened, ≤5 MB, extension allowlist.

  • ISA-18.2 alarm flood deep-dive (alarm_flood_analysis / alarm_rationalization_worksheet, CLI iaiops diag alarm-flood|alarm-worksheet) — flood episodes (≥10 alarms/10 min), chattering, stale/standing (>24h), percent-time-in-flood vs target, and a CSV-exportable rationalization worksheet; over injected events or a live OPC-UA active-condition scan.

  • Open-format export + metrics bridge — iaiops export csv|sqlite|parquet (from the local SQLite sink; Parquet via iaiops[export]) / MCP export_data; iaiops metrics serve --port 9184 exposes Prometheus /metrics (latest tag values + counters, binds 127.0.0.1 by default) — Grafana recipe in docs/GRAFANA.md.

  • Compliance deliverables — iaiops compliance report (等保 2.0 L2/L3 status + IEC 62443 FR1–6 crosswalk + honest gap list, md/html) and iaiops compliance evidence (audit-evidence zip with hash-chain verification + manifest); MCP compliance_report / compliance_evidence_bundle. Onboarding aids, 非认证.

  • NIS2 / CRA self-assessment — iaiops compliance --framework nis2|cra and iaiops compliance report --framework nis2|cra|eu (MCP: the framework argument on compliance_frameworks / compliance_report; no new tool). NIS2 Art. 21(2)(a)–(j) and CRA Annex I Part I(1), I(2)(a)–(m), II(1)–(8), item by item: product_evidence (code-anchored mechanisms speak to the measure's central requirement — never "the measure is met", and every such row names what is left), partial_evidence (they touch it, but the central requirement is missing), gap, or organisational (product provides no evidence). NIS2 obliges entities, the CRA manufacturers; this is a product self-assessment, not a certification and not legal advice. What it still admits: no MFA or per-user identity (one shared bearer token on the HTTP transport, no TLS of its own), an audit opt-out for successful reads only (writes, denials and failures are always recorded), audit database and collected history unencrypted at rest (iaiops reset removes them but does not shred), no penetration test or fuzzing, and the SBOM, PyPI attestations and advisory process are in place but not yet exercised by a release or a report. Vulnerability handling is in SECURITY.md.

Cross-protocol brain & editions — 0.11/0.12 additions (all read-only)

  • Downtime triage copilot (downtime_triage) — composes alarm cascade + RCA verdict + PdM precursors into one triage and cross-checks whether the first-out alarm agrees with the diagnosed cause; advisory, cite-first (builds on the earlier alarm_cascade first-out reconstruction and pdm_forecast time-to-threshold early-warning).

  • Legacy-PLC maintainability (plc_program_visibility) — a risk/maintainability read over an exported ST/AWL/L5X program (size, block count, xref density, undocumented sections), never a live upload — pairs with the plc_program_outline/xref/section explainer.

  • Program ↔ field point, exact address only (plc_program_xref_config, iaiops program xref-config <file> --endpoint <name> [--live]) — which program address is which configured point: matched / in the export but not configured / configured but not named in this export. Joined only when both sides name the same address in the same address space (Siemens AWL/.scl × s7, L5X × Logix ethernetip); never by name — a label that reads like a symbol is not a match. Any other pair returns the reason it is not comparable and no lists. --live reads matched points only after the L5X and online Logix controller names agree; equal names are limited evidence, not unique identity. AWL/SCL has no CPU identity, so the CLI requires --confirm-export-origin and a CPU in RUN; MCP live reads are refused. A failed read is a gap, never a value. iaiops program doc <file> [--endpoint <name>] --out x.html turns the same export into one self-contained, deterministic HTML document (blocks, variables, I/O list, cross-reference, call graph, change history, field cross-reference) — no LLM, nothing written back into the program.

  • Per-edition tool modules (EDITION_MODULES in mcp_server/profiles.py) — a named edition can carry its own @mcp.tool group that loads only when that edition is selected — never for a bare protocol key and never in the always-on brain, so edition-specific tools stay off other surfaces and don't inflate the base. Every edition tool is read-only, cite-first, advisory:

    • warehouse — line_bottleneck (Theory-of-Constraints throughput bottleneck) + sortation_health

    • clinical — isolation_room_check (负压隔离病房 pressurization) + medical_gas_check + or_environment_check

    • building — economizer_check (AHU economizer FDD) + zone_comfort

    • process — control_loop_health (PID oscillation/offset/saturation) + heat_exchanger_fouling

    • fab — spc_check (SPC control-chart rules) + defect_pareto

    • factory — changeover_analysis (SMED)

    • water — disinfection_ct + water_quality_compliance

    • renewables — pv_performance (PV string performance)

    • sensor (IAIOPS_MCP=sensor / iaiops-mcp-sensor) — sensor_import_iodd + sensor_profile_check + sensor_read_channel + sensor_profile_list + sensor_profile_show (connect, decode and read a sensor; binding a profile stays a person's edit of config.yaml)

  • Agent skills — the repo ships a router skill (skills/iaiops) plus eleven per-edition skills (iaiops-fab / iaiops-factory / iaiops-process / iaiops-building / iaiops-water / iaiops-warehouse / iaiops-clinical / iaiops-pharma / iaiops-renewables / iaiops-plcnext / iaiops-sensor) that route an agent to the right MCP server and document the tool surface.

Deployment & ecosystem fit (edge-native / Margo)

iaiops is designed to ride on a hardened, centrally-managed edge host as a portable, governed edge application — not to own the host or the fleet manager. It maps naturally onto the Margo edge-interoperability roles: the host/device is the immutable edge OS, a compliant orchestrator places workloads by desired-state, and iaiops is the OT-domain application — read-first tap + cross-protocol RCA, exposed as governed MCP tools, with an optional on-box LLM brain for a fully air-gapped diagnostic path (data never leaves the plant).

Honest status: iaiops is a natural Margo edge application but is NOT Margo-compliant yet. Signed OCI images and an rc.3 Application Package are published. The released OCI package passed the official Application Supplier CTT runner on Ubuntu 24.04; independent review found the published 0.33.0 Compose component has the wrong OCI archive format, which the CTT did not test. The 0.34.0 source corrects the publishing format; deployment through a real WFM/device remains 待核实 (see the validation record).

A container + application-description package lives in deploy/margo/ (hardened Dockerfile · Compose · rc.3 descriptor); per-host distribution overlays that reuse it live under deploy/ (one folder per candidate edge host).


Install

Protocol client libraries are optional extras — install only the 1–2 protocols a site actually runs (every protocol library is imported lazily; the base package installs and imports without any of them, and a call to a not-installed protocol returns a teaching error pointing at the right extra):

uv tool install "iaiops[opcua,modbus]"   # just the protocols you need
# or one per site:  pip install "iaiops[s7]"   ·   everything:  pip install "iaiops[all]"
# or a per-industry edition bundle:        pip install "iaiops[fab]"

iaiops init                 # interactive: add endpoints, store passwords encrypted
iaiops doctor               # config + per-protocol connectivity probe (point at simulators)
iaiops protocols            # the capability map

Protocol extras: opcua · modbus · s7 · mc · fins (stdlib — pins nothing) · eip · mtconnect · sparkplug · secsgem · ethercat · profinet · bacnet · hart · iolink · bas (BAS supervisory REST — reuses the mtconnect HTTP pin) · ignition (Ignition Gateway read layer — reuses the mtconnect HTTP pin) · plus tdengine · iotdb · influxdb (historian sinks) · nats (stream egress) · ollama (on-box LLM narration) · export (Parquet) · all (every pip-installable connector).

Adapter belt (docs/ADAPTERS.md): iaiops is a small neutral core (ingress → normalize/govern/RCA → egress) with pluggable, lazily-imported adapters — bind no store/bus/host/model, install only what a site runs. The RCA core is deterministic + cited, not a black box (docs/RCA.md); footprint is small by design (docs/FOOTPRINT.md).

Edition bundles (match the same-named IAIOPS_MCP profiles — install the protocols a vertical runs): fab (secsgem + opcua + s7 + modbus) · factory (the discrete-manufacturing set: opcua + modbus + s7 + mc + fins + eip + mtconnect + sparkplug + ethercat + profinet + iolink + ignition) · process (opcua + modbus + hart) · building (bacnet + modbus + opcua + iolink + bas) · water (modbus + opcua + hart) · warehouse (仓储/物料搬运: eip + profinet + modbus + opcua + sparkplug) · clinical (医疗设施: bacnet + modbus + opcua) · renewables (光伏/风电: modbus + opcua + sparkplug — PV inverters (SUN2000/Growatt) + wind turbines + plant SCADA; device-level monitoring + PdM via baseline/RCA) · pharma (制药: bacnet + modbus + hart + opcua) · plcnext (opcua + modbus) · sensor (cross-protocol: modbus + iolink + sparkplug + serial — connect and decode a sensor). The grid/substation energy bundle (IEC-104/DNP3/61850) ships in iaiops-energy.

Master password

Secrets (per-endpoint passwords, MQTT credentials) are never stored in plaintext — they live in ~/.iaiops/secrets.enc (Fernet + scrypt). Export IAIOPS_MASTER_PASSWORD so the MCP server/CLI can unlock non-interactively:

export IAIOPS_MASTER_PASSWORD='…'

Example ~/.iaiops/config.yaml (one block per protocol)

endpoints:
  - name: line1
    protocol: opcua
    endpoint_url: opc.tcp://plc.lan:4840
    # username: operator           # password stored encrypted via init/secret set
    tags:
      - { ref: "ns=2;i=5", label: temp, warn_high: 70, alarm_high: 90 }
  - name: plc2
    protocol: modbus
    host: 10.0.0.5
    port: 502
    unit_id: 1
  - name: press1
    protocol: s7
    host: 10.0.0.6
    rack: 0
    slot: 1                        # S7-1200/1500
  - name: cell3
    protocol: mc
    host: 10.0.0.7
    port: 5007
    plctype: iQ-R
  - name: meter1
    protocol: modbus                 # Modbus-RTU (serial): set transport + serial_port
    transport: rtu
    serial_port: /dev/ttyUSB0
    baudrate: 9600
    unit_id: 1
  - name: omron1
    protocol: fins                   # Omron FINS (UDP default; transport: tcp for FINS/TCP)
    host: 10.0.0.11
    port: 9600
  - name: xmtr1
    protocol: hart                   # HART-IP gateway (read-only; udp default / transport: tcp)
    host: 10.0.0.20
  - name: iolm1
    protocol: iolink                 # IO-Link master JSON integration (read-only)
    host: 10.0.0.21
    flavor: iotcore                  # ifm IoT-Core (default) | rest (Balluff/Turck-style)
  - name: vmc1
    protocol: mtconnect
    agent_url: http://10.0.0.8:5000
  - name: uns
    protocol: mqtt
    host: broker.lan
    use_tls: true                  # → port 8883
    topic: spBv1.0/#
    # username: edge1              # password stored encrypted
  - name: cell5
    protocol: ethernetip           # alias: eip
    host: 10.0.0.9
    slot: 0                        # 0 for CompactLogix; CPU slot for ControlLogix
  - name: bus1
    protocol: ethercat             # Linux + root/CAP_NET_RAW + pip install iaiops[ethercat]
    nic: eth1                      # dedicated NIC cabled to the EtherCAT bus
    expected_slaves: 8             # optional sanity check vs the bus scan

A key this file does not recognise is refused, not ignored — in an endpoint, in a tag, in historian: and in retention:. A dropped key was indistinguishable from one never written: rolle: good_count declared a production counter as far as the site was concerned, and iaiops readiness then reported the OEE mapping unmet while pointing nowhere near the typo. The error names the key, the accepted set, and the nearest match.

iaiops init walkthrough (per protocol)

$ iaiops init
Step 1 — master password: ********
Step 2 — add an endpoint
  Endpoint name (e.g. line1): press1
  Protocol ('opcua','modbus','s7','mc','mtconnect','mqtt') [opcua]: s7
  S7 PLC host (IP/FQDN): 10.0.0.6
  Port [102]: 102
  Rack (0 for S7-1200/1500) [0]: 0
  Slot (1 for S7-1200/1500, 2 for S7-300/400) [1]: 1
✓ Saved endpoint 'press1'.

(MQTT prompts add TLS/topic/username; MTConnect prompts for agent_url; EtherCAT prompts for the nic + expected_slaves and warns about the Linux/root/NIC/optional-extra requirement; OPC-UA/MQTT prompt for a hidden password stored encrypted.)

Test against a simulator (per protocol)

  • OPC-UA — an asyncua demo server (the test suite runs a real in-process one).

  • Modbus — ModbusPal or a pymodbus server simulator.

  • S7 — a pyS7/snap7 S7 server sim (Snap7 server) on :102.

  • MTConnect — the public MTConnect demo agent, or a local agent.

  • MQTT — a local mosquitto broker (+ a Sparkplug edge for SpB topics).

  • Mitsubishi MC — GX Simulator / an MC 3E server sim.

  • EtherNet/IP — a pycomm3-compatible CIP/Logix simulator (or a spare CompactLogix).

  • Omron FINS — the in-repo mock FINS UDP/TCP responder (tests/test_fins.py) or a spare CP/CJ PLC.

  • IO-Link — the in-process mock master (tests/test_iolink.py, both JSON dialects) or any ifm/Balluff/Turck master on the bench.

  • EtherCAT — no simulator exists (hard-real-time, raw-Ethernet). Validate only on Linux, as root / with CAP_NET_RAW, on a dedicated NIC wired to real slaves (e.g. a Beckhoff EK1100 coupler + EL terminals). iaiops doctor reports a clear "needs Linux/root/NIC/pysoem" status off the bus rather than failing.


Usage

Site survey — find what is on a network you have not been given a list for

Every other command needs an endpoint you already configured. scan answers the question that comes first. It has no full-port mode, no raw sockets, no half-open SYNs, and no write path of any kind; what it may touch is a fixed industrial port allowlist, and how fast is capped by a ceiling the caller cannot raise.

iaiops scan profiles                                   # what each posture does
iaiops scan plan --targets 10.0.0.0/24                 # sends NOTHING — the artifact you get signed
iaiops scan run  --targets 10.0.0.0/24 --site "Line 1" \
                 --approved-by "J. Controls" --ticket CHG-91 \
                 --report survey.html                  # scan → store → one HTML file
iaiops scan list                                       # stored surveys
iaiops scan report --out survey.html                   # re-render the latest

scan plan puts nothing on the wire. It prints every host and port that would be touched, every class of packet that would be sent, the worst-case duration, and the explicit list of what this tool never does — so you can run it against a network before you have permission to scan it, and hand the output to whoever grants that permission. scan run shows the same preview and asks once before it sends anything (--yes to skip).

Postures run from passive (reads the local ARP cache, emits nothing at all) to legacy-safe (reachability only, one host at a time, five connects a second — for 1990s controllers where even a well-formed identify request is a risk). standard and deep refuse to run without a recorded sign-off.

The HTML report is self-contained: no fonts, scripts, styles or images from anywhere, and no network request when opened. Its first section is what the scan touched — per-class emission counts, including requests that failed — followed by the list of things it never does. The device table comes after that.

From a survey to a measured OEE — the path the site actually walks

scan answers what is out there. These answer what can I do with it, and what is the number. Each step is a real command; nothing here is a roadmap item.

iaiops readiness                                    # contacts NOTHING

What this installation can run today, and for each thing it cannot, the specific input that is missing — ranked by how much supplying it would unlock. It touches no device, so you can run it against a site you have not been authorised to probe, which is the site that most needs the answer. It reports gaps; it never fills one in (§9.4/D16 — a guessed production counter yields a plausible-looking OEE, which is worse than an error).

iaiops collect plan line1 --duration 7d --interval-ms 1000   # contacts NOTHING
iaiops collect run  line1 --duration 7d --interval-ms 1000
iaiops collect run  line1 --duration 7d --resume             # after a closed lid
iaiops store status                                          # what the store holds
iaiops store prune --sealed-before 2026-08-01 --apply        # refuses without a seal

A bounded assessment run — capped at 14 days, and the operator must state the end. There is deliberately no run-forever mode: a resident process on an OT network needs change management, a laptop running for a week does not (D21). Every run records the windows it could not see, so a gap is never silently readable as a stoppage.

To get an OEE out of it, three tags have to be declared — which value means running, which register counts parts, and (for Quality) which counts good ones:

endpoints:
  - name: line1
    ideal_cycle_time_s: 0.1
    tags:
      - {ref: "0",  role: run_state,   running_when: [2]}   # 2 = running
      - {ref: "10", role: total_count}
      - {ref: "11", role: good_count}

running_when is declared, never inferred. On the 0=stopped 1=idle 2=running 3=fault status word most PLCs expose, "any non-zero means running" counts three states of four as production.

iaiops oee measure line1 --reported 97               # against the figure the site keeps
iaiops oee measure line1 --since 2026-03-02T06:00:00Z --until 2026-03-09T06:00:00Z
iaiops oee measure line1 --report oee.html --lang zh --site "一号厂区"

Scope the measurement with --since / --until, together. Without them the period is everything the store holds for that endpoint — fine for one assessment run, wrong the moment there are two: the idle weeks between a March run and an August one become one enormous blind span and neither run can be measured.

The window is charged for in full. The parts of it that were never sampled — before the first sample and after the last — count as blind exactly like a gap in the middle, so narrowing the question to the minutes that happen to have data cannot raise your coverage. Ask about a shift you observed two hours of, and the answer is 25% coverage and a refusal, not "100% of what we saw".

Availability measured over the time the collector could see, with blind windows excluded rather than counted as downtime; plus Performance, Quality and the Six Big Losses. Each factor is reported only when its inputs were declared — a partial OEE that names what is missing beats a whole one with a guess inside it.

--report writes one self-contained HTML file — no fonts, scripts, styles or images from anywhere, and no network request when opened, so it works on an air-gapped laptop and survives being forwarded as an attachment. Its first section is what the measurement could see (coverage, blind time, sample cadence), before the number, and it carries the row a sales deck usually leaves out: what had to be declared to produce each figure, and what is still missing.

iaiops case open line1 --min-stop-s 300              # one case per long stoppage
iaiops case list                                     # each carries what someone DID after it
iaiops case causes                                   # the vocabulary a confirmation may use
iaiops case confirm <id> --cause material_starvation --by wei
iaiops case agreement                                # >90% agreement is a WARNING, not a score
iaiops diag learn-weights --site default             # learn a per-site cause profile
iaiops diag rca --input bundle.json --from-case <id> # a person's answer reaches the verdict

The label is a by-product of work already being done: the audit trail already recorded that someone ran a write four minutes after the line stopped, so the case shows it. Confirmation is one choice from a fixed vocabulary, never free text, and a dismissal is a label too. Whether an answer counts as independent is derived from whether the tool had suggested it — the answerer cannot claim it.

The investigation itself — eight steps, and what each one needs

readiness answers which scenarios this site can run. This answers the next question down: if something stopped tomorrow, how far could we actually get?

iaiops investigate plan                              # contacts NOTHING

Eight evidence steps — define the incident, collect the evidence, normalize and check it, compress and rank, correlate the timeline, test the hypotheses, check against known mechanisms, conclude and close. For each one it cannot walk, it says whether that is something you have not supplied (with the command that would) or something this product cannot express at all. Those two send a person to very different places.

iaiops investigate open line1 --start <iso> --end <iso> --asset "Line 1"
iaiops investigate show <id>                         # the state it was left in
iaiops investigate list

The same eight steps over a real past window, persisted so it can be re-read and advanced later. No device is contacted — the window is already over, and its evidence is whatever was collected at the time.

Any of the three writes the forwardable version — one self-contained HTML file that opens on an air-gapped laptop in a plant office:

iaiops investigate plan --report readiness.html --lang zh
iaiops investigate open line1 --start <iso> --end <iso> --report incident.html

Unlike oee measure --report, which refuses to write a file for a refused measurement, this one writes for a blocked investigation on purpose. An OEE report is a number, so a file existing at all claims one was measured. This report's content is how far this got and what each step still needs — which makes the blocked case the one most worth handing over, and for a site nobody has instrumented yet it is the whole deliverable. What it will not do is let a blocked investigation look finished: the headline is always the walk (2 / 8), never a conclusion, and no step's own words appear above it.

Two journeys: reading devices, or subscribing to a UNS broker

Where you start depends on one question the files cannot always answer for you: is this site's data already flowing through an MQTT/UNS broker?

iaiops onboard status                  # derives the journey from config.yaml — or asks
iaiops onboard status --track devices  # no UNS yet: survey, then read PLCs directly
iaiops onboard status --track uns      # already on a broker: connect, audit, subscribe
  • devices — survey → endpoints → a point list per endpoint → what each point MEANS → collect → ask. This is also the journey for a site building a UNS: confirm what a point means before it is published, because publish-once / subscribe-many turns one wrong mapping into the same wrong number in every consumer at once.

  • uns — connect to the broker (stale_after_s is required) → audit the namespace → choose the points → what they MEAN → collect → ask. No scan: a scan never identifies MQTT, so sending a UNS site to one was a dead end. The namespace audit forks this journey into B1, audited clean, and B2, where governance — fixing the naming, and on a Sparkplug namespace watching a schema baseline with iaiops mqtt uns-live-drift — is the work rather than a later step. Plain MQTT has no drift watch: both schema commands read Sparkplug BIRTH messages.

The journey comes from config.yaml: broker endpoints only → uns, device endpoints only → devices. With nothing configured, or both kinds of endpoint, the single step is the question with both answers, and neither is picked for you. B1/B2 comes only from a stored iaiops mqtt uns-live-audit verdict — onboard contacts nothing — so until one exists it says the fork is unknown. Only an audit taken against a naming standard (--root, --min-segments), not cut short by its message cap, listening for at least one publish interval (stale_after_s), and on the broker and topic filter the endpoint uses now can make a site B1; anything less leaves the fork open and says why. Only a sprawling verdict makes it B2: a minor one is a handful of heuristic findings — a Sparkplug STATE topic trips them — so it is reported as findings to review, not as a governance verdict. An audit whose capture saw no topics is not stored: it audited nothing, and "zero findings" must not read as a clean namespace. On the UNS journey the points still go into tags: by hand; nothing turns a broker listing into a draft yet.

From a scan to a config

Everything on the path existed; nothing joined it. A site could scan forty devices and then retype all forty by hand, and nothing anywhere said which of the six commands came next.

iaiops onboard status                 # where am I, and what is the ONE next command
iaiops onboard draft                  # the newest scan → config.yaml endpoints
iaiops onboard draft --out draft.yaml # ...to a file you can review and merge

draft writes nothing into config.yaml — you merge it, exactly as with tags apply. What it emits is constrained on purpose:

  • Only CONFIRMED protocols become endpoints. An open 502 means something is listening, not that it is a Modbus device, and a config that said so would be believed. Those hosts are listed as skipped, with the reason.

  • Every value names the observation that justifies it — and the interesting half is what the scan learned that you would otherwise have hunted for: the S7 slot the CPU actually answered on, the MELSEC CPU's own plctype, whether an OPC-UA server advertises an unsecured endpoint or will need credentials.

  • A field the scan could not settle goes out commented, saying what it is waiting for — never omitted. Omission lets the protocol default apply in silence, which is how a Modbus gateway gets read at unit 1 and shows a confident number for the wrong machine.

  • tags: comes out empty. A scan finds devices; it establishes nothing about what their data means. That step is the next one, below.

  • Absence is not evidence. The draft states what it structurally cannot contain — BACnet/FINS/HART are UDP and never swept; MQTT and the supervisory layers are never identified, by design.

status is derived from the store and config.yaml every time. There is no onboarding state file, so a hand-edited config or a restored backup still gets a true answer rather than a remembered one — and a step that is genuinely done stays done even if you did the steps out of order.

For the point-list step it names the command for your protocol: opcua browse, eip tags, mtconnect probe, iolink ports, mqtt browse, bacnet objects, ethercat slaves, hart dynamic, or modbus templates. Where there genuinely is nothing to ask — an S7 CPU exposes no symbol table on the wire, and MELSEC and Omron memory carry none either — it says so in that protocol's own terms and tells you where the addresses do come from, rather than one sentence covering everything that is not OPC-UA.

Confirming what the point list means

The one thing this product refuses to infer, and until now the only way to supply it was hand-editing role: in a config file — which is exactly what stops working at a hundred rows.

iaiops tags export sheet.csv          # every monitored tag; `role` column EMPTY
# a person fills in role + running_when
iaiops tags apply sheet.csv --by wei  # prints the exact config.yaml edit

The role column comes out empty even next to a tag called GoodPartsCounter. A name is not a declaration; plenty of plants have one that counts something else, and a wrong production counter yields a plausible OEE — worse than an error (D16).

apply emits the patch rather than writing it. config.yaml stays the single source of truth: oee measure reads roles off the config tag objects, so a parallel store would let readiness call the mapping met while oee measure still could not run. A run_state with no running_when is refused here, for the same reason MonitorTag refuses it — "anything non-zero" counts idle and fault as production.

Or tick it through in a page instead of a spreadsheet:

iaiops tags page confirm.html --lang zh

HLD §13.9's App front end, delivered as a file rather than a served app. A localhost server inside an OT box has to answer which address it binds and who authenticates — and since every declaration here requires --by, a page with no identity cannot record who confirmed a tag, which is the one thing this step exists to capture. So the page collects, and the author is supplied at apply.

The page re-implements no refusal. run_state needing running_when, a ref having to be monitored, a role claimed twice — reproducing any of those in JavaScript is how they drift from the ones that actually gate the config, and a page that says "looks fine" while apply refuses is worse than no page. It ships script (it is a form) but makes no network request: it works with the cable out.

There is deliberately no MCP tool for this. An agent filling in the role column is precisely the guess D16 exists to forbid.

Two of the steps need something a person has to state:

iaiops relations declare press oven --by wei         # which asset feeds which
iaiops relations downstream press                    # nearest first

The second axis of root-cause analysis. With time alone, an upstream stoppage produces a string of equally-confident downstream false causes — on a line, downstream co-occurrence is guaranteed whatever the cause. That guarantee is why this is declared and not inferred (D25). Without it the timeline still runs; it degrades to a single asset and says so.

iaiops knowledge mount mechanisms.yaml --by wei      # what is known about this equipment
iaiops knowledge check sensor_fault --protocol modbus

A fault-mechanism library, shaped by ISO 14224: the failure mode (what you saw), the mechanism (what to go and check) and the cause (what to fix) stay separate, because they answer different questions. Entries attach to the seven taxonomy causes; they never add new ones — past roughly forty codes, two operators stop picking the same one.

It may exclude and never confirm. A mechanism that cannot apply to this equipment rules the candidate out, which is the strong move a ranker cannot make:

✗ sensor_fault — excluded
  every mounted mechanism for 'sensor_fault' applies only to hart, opcua — not to modbus

And a cause the library has never heard of reports nothing known — never "no objection". A knowledge base that knows nothing about something has not cleared it.

Program change baseline — has the approved logic moved?

A control program is a controlled document, and the usual way an undocumented change to one gets noticed is that somebody remembers. Record the version you consider approved, then ask a later export whether anything moved:

iaiops program snapshot ~/exports/Line3.scl --name Line3 --label "approved v3.2 / MOC-118"
iaiops program drift    ~/exports/Line3_today.scl --name Line3
# Over MCP the agent reads ~/exports only once the operator lists it:
#   IAIOPS_AGENT_READ_DIRS=~/exports

The snapshot stores the file's SHA-256 plus a per-block structural fingerprint — name/kind/language, declared variables, calls, branch conditions, timers — and deliberately excludes line numbers, comments and block order, so adding one comment at the top of a file does not report the whole program as changed. What is stored on disk is block names, hashes and counts; never a declaration, a source line or a comment, so the baseline store is not a second copy of your program.

Three verdicts, and each word is load-bearing:

Verdict

Means

identical

The same SHA-256. Nothing else earns the word.

logic_changed

The extracted structure differs — reported per block, naming which of variables / calls / branches / timers_counters moved.

changed_outside_extracted_structure

The bytes differ and every block fingerprint matched.

That third one is the honest one. It is usually comments or formatting — but these parsers extract structure, they do not parse a grammar, so a real change inside a construct they do not model looks identical from here. Calling it "documentation only" would be the comfortable reading of evidence that does not support it, so it is not called that: line and comment counts are reported beside it and the verdict still says look. A drift report is a reason to read the diff, never a clearance.

iaiops program history lists what is tracked; iaiops program compare <name> <before> <after> diffs two stored snapshots. Deleting history is iaiops program forget and is CLI-only — an agent should not be one call away from removing change-control evidence. Nothing is pruned automatically. The name (not the path) is the identity, because the export directory changes every time somebody opens the engineering station and the program does not; absent --name the file stem is used and the output says so. No device is touched at any point — this reads a file a person exported.

CLI (read)

iaiops opcua read "ns=2;i=5" -e line1
iaiops modbus holding 0 -e plc2 --count 4 --decode float32
iaiops s7 read-db 1 REAL 4 -e press1 --count 2
iaiops mc words D100 -e cell3 --count 8
iaiops fins words 100 --area DM -e omron1 --count 8   # Omron FINS memory-area read
iaiops hart pv -e xmtr1                            # HART primary variable
iaiops iolink scan -e iolm1                        # IO-Link master + connected devices
iaiops mtconnect oee -e vmc1
iaiops mqtt nodes -e uns --timeout-s 15
iaiops eip tags -e cell5                           # Logix tag discovery
iaiops eip read "Conveyor.Speed" -e cell5
iaiops ethercat slaves -e bus1                     # EtherCAT bus scan (Linux+root)
iaiops ethercat read-sdo 0 4120 --subindex 1 -e bus1   # CoE SDO 0x1018:1
iaiops opcua history "ns=2;i=5" -e line1 --start 2026-06-28T08:00:00Z   # HDA
iaiops opcua monitor "ns=2;i=5" -e line1 --duration-s 20 --deadband 0.5 # CoV
iaiops diag dataflow -e line1 --ref "ns=2;i=5" --freshness-s 30
iaiops analytics oee 28800 25200 2.0 12000 11800   # OEE from five numbers you already have
                                                   # (for a measured one, see `oee measure` above)
iaiops analytics asset -e press1 -e cell5           # active asset register

CLI (write — dry-run by default, double-confirm on --apply)

iaiops s7 write-db 1 INT 0 42 -e press1            # dry-run preview
iaiops s7 write-db 1 INT 0 42 -e press1 --apply    # double-confirm prompt
iaiops mqtt publish factory/line1/cmd '{"setpoint":50}' -e uns --apply
iaiops eip write-tag Setpoint 42 -e cell5 --apply  # Logix tag write (double-confirm)
iaiops fins write-words 100 42 --area DM -e omron1 --apply  # Omron FINS write (double-confirm)
iaiops ethercat write-sdo 0 24698 e8030000 -e bus1 --apply   # CoE SDO 0x607A download
iaiops ethercat set-state PREOP --slave 0 -e bus1 --apply     # AL-state (can stop motion!)

MCP tool calls (JSON args → sample structured return)

s7_read_db:

{ "db": 1, "dtype": "REAL", "start": 4, "endpoint": "press1", "count": 2 }
{ "endpoint": "press1", "area": "DB", "db": 1, "dtype": "REAL", "start": 4,
  "count": 2, "items": [ {"address": "DB1,REAL4", "value": 20.5},
                         {"address": "DB1,REAL8", "value": 4.2} ] }

s7_write_db (dry-run):

{ "db": 1, "dtype": "INT", "start": 0, "value": 42, "endpoint": "press1" }
{ "address": "DB1,INT0", "dry_run": true, "before": 7, "would_write": 42,
  "note": "Dry run — nothing written. Re-run with dry_run=false AND a recorded approver…" }

mtconnect_oee_snapshot:

{ "availability": "AVAILABLE", "execution": "ACTIVE", "controller_mode": "AUTOMATIC",
  "program": "O1234", "available": true, "running": true, "verdict": "running" }

eip_read_tag:

{ "tag": "Conveyor.Speed", "endpoint": "cell5" }
{ "endpoint": "cell5", "tag": "Conveyor.Speed", "value": 1500.0, "type": "REAL",
  "error": "", "good": true }

eip_write_tag (dry-run):

{ "tag": "Setpoint", "value": 42, "endpoint": "cell5" }
{ "endpoint": "cell5", "tag": "Setpoint", "dry_run": true, "before": 7,
  "would_write": 42, "note": "Dry run — nothing written. Re-run with dry_run=false AND a recorded approver…" }

ethercat_read_sdo (CoE SDO upload):

{ "slave": 0, "index": 4120, "subindex": 1, "endpoint": "bus1" }
{ "endpoint": "bus1", "slave": 0, "index": "0x1018", "subindex": 1,
  "byte_length": 4, "hex": "9a020000", "as_uint": 666 }

ethercat_set_state (dry-run; can start/stop motion):

{ "state": "OP", "slave": 0, "endpoint": "bus1" }
{ "endpoint": "bus1", "scope": "slave[0]", "dry_run": true, "before": "SAFEOP",
  "would_request": "OP", "note": "Dry run — no state change. … Changing EtherCAT state can start/stop machine motion." }

sparkplug_decode_payload (full SpB metric decode):

{ "payload": "CAESBwoDYWJjEAE=", "encoding": "base64" }
{ "encoding": "sparkplug_b", "seq": 0, "metric_count": 2, "historical_count": 0,
  "metrics": [ {"name": "Temperature", "alias": 1, "datatype": "Double", "value": 21.5,
                "is_historical": false, "is_null": false} ] }

oee_compute:

{ "planned_time_s": 28800, "run_time_s": 25200, "ideal_cycle_time_s": 2.0,
  "total_count": 12000, "good_count": 11800 }
{ "availability": {"raw": 0.875, "value": 0.875, "capped": false},
  "performance": {"value": 0.952381}, "quality": {"value": 0.983333},
  "oee": 0.819444, "oee_pct": 81.94 }

asset_inventory (active fingerprint):

{ "endpoints": ["press1", "cell5"] }
{ "asset_count": 2, "reachable_count": 2, "method": "active_fingerprint",
  "assets": [ {"endpoint": "press1", "protocol": "s7", "vendor": "Siemens/compatible",
               "model": "CPU 1511-1 PN", "firmware": "2.8", "reachable": true,
               "last_seen": "2026-06-28T10:00:00+00:00"} ] }

Diagnostics (multi-dimensional JSON for an agent to visualize)

diagnose_dataflow(endpoint="line1", ref="ns=2;i=5", freshness_threshold_s=30):

{ "verdict": "comms_ok_value_stale",
  "diagnosis": "Connected with good status, but the value is STALE (age 412s > 30s) — the source/field upstream has stopped updating this point.",
  "recommended_action": "Trace upstream: the device serves the last value fine, so suspect the source/scanner/field signal that should refresh it.",
  "hops": [ {"hop":"connect","protocol":"opcua","ok":true,"detail":"OPC-UA state=0"},
            {"hop":"read_tag","ref":"ns=2;i=5","ok":true,"detail":"5.0"},
            {"hop":"freshness","evaluated":true,"stale":true,"age_seconds":412.0} ] }

alarm_bad_actors(events=[…]):

{ "event_count": 55, "window_minutes": 0.82, "alarms_per_hour": 4024.4,
  "isa_18_2": {"ok_max":6,"manageable_max":12,"flood_min":30},
  "flood_verdict": "flood",
  "priority_distribution": {"high":50,"low":5},
  "pareto_sources_for_80pct": ["FIC101"],
  "top_offenders": [ {"source":"FIC101","count":50,"share_pct":90.9,"chattering":true,"standing":false} ],
  "chattering": ["FIC101"], "standing": [] }

tag_health(tags=[…]):

{ "evaluated": 4, "overall": "alarm", "offender_count": 3,
  "offenders": [ {"ref":"hot","latest":99,"flags":["out_of_range_alarm"],"severity":3},
                 {"ref":"flat","latest":5,"flags":["flatline"],"severity":2},
                 {"ref":"bad","latest":null,"flags":["bad_quality"],"severity":3} ] }

AI downtime root-cause copilot (flagship)

downtime_root_cause correlates whatever evidence you can hand over — alarm events, tag samples, a diagnose_dataflow verdict, a machine-state series — around an incident window and returns an evidence-cited, advisory verdict. Read-first: it proposes a human-approved, MOC-gated, undoable action and executes nothing. Anti-hallucination by design — it cites only signals actually present in the input, weights them by temporal proximity to onset (a cause precedes its effect), and downgrades to insufficient_evidence (with a recommended_next_data list) rather than guessing when evidence is thin.

downtime_root_cause(window={"start":"2026-06-28T10:00:00Z","asset":"line1"}, alarms=[{"source":"M1_DRIVE","timestamp":"2026-06-28T09:59:52Z","message":"motor overload trip"}], tags=[{"ref":"DRV1.Torque","samples":[10,11,99,99],"alarm_high":80}], dataflow={"verdict":"healthy"}):

{ "window": {"start":"2026-06-28 10:00:00+00:00","asset":"line1","duration_s":300.0},
  "verdict": "root_cause_identified",
  "primary_cause": {
    "cause": "mechanical_fault", "confidence": 0.722, "confidence_band": "high",
    "evidence": [
      {"signal":"alarm","ref":"M1_DRIVE","at":"2026-06-28 09:59:52+00:00","lead_time_s":8.0,
       "detail":"motor overload trip","weight":0.4959},
      {"signal":"tag","ref":"DRV1.Torque","detail":"flags=out_of_range_alarm severity=3","weight":0.45} ],
    "recommended_action": "Dispatch maintenance to inspect the faulting unit; if a latch/interlock is set, the reversible step is to clear the fault and reset the latch (MOC-approved, undo captures the prior latch state)." },
  "evidence_summary": {"alarms_supplied":1,"tags_supplied":1,"dataflow_verdict":"healthy","total_evidence_items":2},
  "anti_hallucination": "Advisory only — nothing is executed. Every cited signal is present in the supplied evidence …" }

The same copilot is on the CLI: iaiops diag rca --input bundle.json where the bundle is {window, alarms?, tags?, dataflow?, state_series?}.

Let it gather its own evidence. downtime_root_cause_live (CLI iaiops diag rca-live) takes just an endpoint + window + the refs to look at, then pulls the evidence itself — a cross-protocol diagnose_dataflow probe, a short sampled series per ref (so flatline / bad-quality / anomaly surface via tag_health), and active OPC-UA conditions — before running the same advisory, read-only copilot. The gathered bundle is echoed back under collected_evidence (no hidden inputs):

iaiops diag rca-live -e line1 --start 2026-06-28T10:00:00Z \
  --asset line1 --ref "ns=2;i=5" --ref "ns=2;i=6"

Data-quality watchdog & UNS governance (read-only intelligence)

Two more pure-analysis layers — fully testable without live gear, and they feed the RCA copilot.

  • data_quality_scorecard (CLI iaiops diag dataquality) — a fleet data-TRUST rollup: scores each tag 0-100 on whether its data can be believed — staleness, dead heartbeat (first-class), bad-quality, flatline, gaps, anomaly — then rolls up per endpoint and across the fleet with an issue breakdown and ranked worst offenders. Distinct from process health: it asks "can I trust this number," not "is this number alarming." heartbeat_health (CLI iaiops diag heartbeat) is the standalone watchdog-liveness check (a flatlined heartbeat = dead upstream even when comms look fine).

  • uns_topic_audit (CLI iaiops mqtt uns-audit) — governs a UNS topic tree: naming conformance (allowed roots / min depth) + topic sprawl (casing collisions of the same logical name, leaf metrics scattered under many parents, depth outliers, duplicates) → a clean/minor/sprawling verdict. uns_schema_drift (CLI iaiops mqtt uns-drift) — compares two Sparkplug NBIRTH-style snapshots and classifies the change none / additive / breaking (a metric removed or its datatype changed). Positions the UNS as a governable neutral data source, not just a broker.

MCP server

IAIOPS_MCP=opcua iaiops-mcp   # stdio transport (`iaiops mcp` is equivalent)

Menu — expose only the protocols a site runs. A fab usually runs 1–2 protocols; exposing all 14 floods the model with tools it can't use. Set IAIOPS_MCP to a comma-list of protocols and/or a named profile. There is no default (since 0.10.0): a bare iaiops-mcp prints the selection menu (profiles, protocol keys, tool counts) to stderr and exits 2 instead of silently exposing 100+ tools. The cross-protocol brain (OEE / downtime / diagnostics / asset / analysis) is included by default with every selection.

IAIOPS_MCP=menu         iaiops-mcp   # print the menu (selections + tool counts)
IAIOPS_MCP=opcua,modbus iaiops-mcp   # two protocols + brain
IAIOPS_MCP=fab          iaiops-mcp   # named profile (secsgem+opcua+s7+modbus)
IAIOPS_MCP=opcua        iaiops-mcp   # effectively a single-protocol MCP
IAIOPS_MCP=all          iaiops-mcp   # everything — explicit opt-in only
                                     # (logs a tool-flood warning above 100 tools)

Named entry-point sugar. For the common single-protocol / single-edition case there is a pre-scoped console script per protocol and per named profile — no env var to set. Each is a thin shim over the same server:

iaiops-mcp-opcua     # == IAIOPS_MCP=opcua    iaiops-mcp
iaiops-mcp-modbus    # == IAIOPS_MCP=modbus   iaiops-mcp
iaiops-mcp-fab       # == IAIOPS_MCP=fab      iaiops-mcp  (per-edition)
iaiops-mcp-building  # == IAIOPS_MCP=building iaiops-mcp
iaiops-mcp-brain     # == IAIOPS_MCP=brain    iaiops-mcp  (brain only, 0 protocols)

Multi-process sites — 1 brain MCP + N protocol MCPs. Running several protocol servers side by side (e.g. iaiops-mcp-opcua + iaiops-mcp-modbus) would duplicate the ~30 brain tools in every server. Instead run one dedicated iaiops-mcp-brain and set IAIOPS_MCP_NO_BRAIN=1 on the protocol servers to strip the brain from them — the protocols_supported discovery tool stays exposed everywhere:

iaiops-mcp-brain                          # the one cross-protocol brain server
IAIOPS_MCP_NO_BRAIN=1 iaiops-mcp-opcua    # lean protocol server, no brain
IAIOPS_MCP_NO_BRAIN=1 iaiops-mcp-modbus

Write authorisation is not the tap's job. iaiops does not withhold write tools behind a server switch. Whether a write is allowed is the caller's decision — the agent's judgement or account/permission management — and the tap's job is to make that write accurate, efficient, and un-bypassably audited. Every call, read or write, on either front-end (MCP tool and iaiops CLI), goes through @governed_tool and leaves a row in ~/.iaiops/audit.db (unless the operator sets IAIOPS_AUDIT_OPT_OUT=reads, which skips successful declared reads only). Writes are additionally HIGH risk_tier and MOC-gated (dry-run + double confirmation + undo capture + a recorded approver). protocols_supported reports this posture so the model is told the rules rather than left to infer them.

Since 0.20.3 that promise is held by contract tests over the real tool surface rather than by synthetic stand-ins: every one of the ten high-risk writes is driven end to end and must be denied without an approver with the connector never reached — "it raised" only proves an exception, not that nothing reached the device. Two things those tests exposed on the way in: a call that failed was audited as ok (tools return the canonical {error, hint} envelope rather than raising, so the governance wrapper saw an ordinary return), which also told the pattern circuit breaker "success" on every failure; and the runaway guard, blind to a caller retrying a denial forever, let 500 identical denied writes through a ceiling of 10. Both are fixed and pinned.

Sealed sites — make the data-shipping tools cease to exist. IAIOPS_NO_EGRESS=1 removes every tool whose job is to transmit local or plant data to a destination the caller names, at registration time so a weak or prompt-injected model cannot call what it cannot see:

IAIOPS_NO_EGRESS=1 iaiops-mcp-factory   # 134 tools -> 129; 5 withheld

Withheld: stream_publish, stream_publish_event (NATS message bus), uns_publish (MQTT broker / Unified Namespace), historian_push (external TSDB), mqtt_publish (broker), rca_narrate (POSTs the RCA verdict — plant tags, values and citations — to a caller-supplied model base_url). This is a data-exfiltration / airgap axis, not read/write authorisation: historian_push is risk_level="low" — it changes no plant state — yet it ships telemetry off-box, so this switch withholds it. It gates MCP tools only, and is not a firewall (reads still open sockets to plant devices). protocols_supported reports each posture independently.

Scope, stated plainly — this is not a firewall:

  • It gates MCP tools only. iaiops audit forward (SIEM) is a CLI path no registry gate can reach; block it at the host if the box must be sealed.

  • Reads still open outbound sockets. iaiops is a network tap — it must talk to PLCs, brokers and historians to read anything at all. The gate removes the tools whose purpose is sending data outward, not the network itself.

  • It does not police arguments. A tool is present or absent as a whole; nothing is inspected at call time (that would be the call-time refusal this design rejects). This is why a tool with a caller-supplied destination is withheld even when its default points at localhost — the model picks the argument.

  • Local file writes are not egress: export_data and compliance_evidence_bundle stay exposed. The bytes never leave the box; getting them off it afterwards is a host-level concern.

  • Both switches cover the iaiops-mcp server only (including its per-protocol / per-edition entry-point shims). iaiops-energy-mcp is a separate server in a separate package and does not honour them yet — it mirrors in the base brain/compliance tools, so IAIOPS_NO_EGRESS=1 there still leaves historian_push, rca_narrate, stream_publish and stream_publish_event exposed on iaiops-energy 0.1.6 and earlier. Fixed in iaiops-energy 0.1.7, which pins iaiops>=0.17 for exactly this reason. Said out loud because a switch believed to be on is worse than one known to be absent.

Named profiles: all · brain · fab · factory · process · building · plcnext · water · renewables · warehouse · clinical · pharma · sensor. In an MCP client (e.g. Claude Desktop) set IAIOPS_MCP per server entry — or point the entry straight at the matching iaiops-mcp-<name> script — one entry per site/line, each a lean single- or dual-protocol server.


Safety & governance

  • Authenticated socket. Over HTTP/SSE (IAIOPS_MCP_TRANSPORT=streamable-http|sse) every request must carry Authorization: Bearer <token> once IAIOPS_MCP_TOKEN (or IAIOPS_MCP_TOKEN_FILE) is set, and a bind off loopback without a token refuses to start. The shipped containers (Margo, airgap, Siemens IE, IGEL) therefore need the token injected from the secret store; IAIOPS_ALLOWLIST_IPS is an optional second layer, off by default (never set it to loopback only behind a container port mapping: callers arrive as the bridge gateway). One shared token, not per-user identity; no TLS of its own.

  • Read-first. 191 of the 206 tools are read-only (2 of them the deprecated aliases); 4 more change nothing on a device but send data off-box (stream_publish, stream_publish_event, uns_publish, rca_narrate), and historian_push writes to a historian rather than to a device. The 10 write/command tools (s7_write_db, mc_write_words, fins_write_words, mqtt_publish, eip_write_tag, ethercat_write_sdo, ethercat_set_state, profinet_dcp_set, bacnet_write_property, bas_command) are OT-dangerous: governed at high risk_tier, off by default (dry-run), require a double-confirm in the CLI, and a recorded approver (one-shot iaiops approve tokens; with no risk_tiers configured, high/critical operations default to the dual tier) — MOC discipline. All ten declare an undo (no exemptions since 0.20.3); a successful write captures the BEFORE value/state and registers an inverse descriptor. The inverse honestly reports "none" where none exists — a transient (retain=False) mqtt_publish cannot be unsent, and ethercat_set_state's +ERR/NONE/BOOT are not cleanly re-requestable AL-states. An undo that over-promises is worse than none, because someone will replay it onto live equipment. ethercat_set_state can START or STOP machine motion. 未经授权勿对生产控制系统写入.

  • Read/write authorisation is the caller's, not the tap's. iaiops does not encode "this server may not write" by hiding tools — that decision belongs to the agent's judgement or account/permission management. The tap's guarantee is un-bypassable audit on both front-ends: every call, read or write, via an MCP tool or the iaiops CLI, runs through @governed_tool and leaves a row in ~/.iaiops/audit.db. IAIOPS_AUDIT_OPT_OUT=reads is the one exception, set by the operator: it stops recording successful declared reads; writes, previews, egress, denials, failures and every CLI command are still recorded, and the opt-out leaves a marker row. On iaiops-mcp and the iaiops CLI the row records which front-end the call came through (origin: mcp or cli; empty — unknown, never read as human or agent — on rows written before this field existed and on servers that do not declare it), the MCP client's self-reported name, a per-session id, and, for tools with a preview flag, whether the call was a preview or an apply. Writes are additionally high risk_tier, MOC-gated, and undo-captured (see above). High/critical calls fail closed when the audit DB cannot be written.

  • No-egress mode is enforced at registration. IAIOPS_NO_EGRESS=1 withholds the 6 tools that ship data off-box (stream_publish, stream_publish_event, uns_publish, historian_push, mqtt_publish, rca_narrate), fail-closed, for airgap/sealed-box deployments. This is a data-exfiltration axis, not authorisation — historian_push is low-risk (it changes nothing) yet pushes telemetry to an external TSDB, so this switch withholds it. Which tools count is derived from @governed_tool(egress=True) metadata and guarded by an AST scan in CI, so the next egress tool cannot silently escape the gate.

  • An agent reads files only where the operator put them. There are eight plc_program_* tools; seven accept a host file, while plc_program_history reads the local snapshot store. The 14 MCP paths that READ a host file the agent names — sensor_import_iodd, sensor_profile_check, those seven program tools, device_advisory_check, the db= override of site_readiness / onboarding_status / onboarding_config_draft, and historian_push with sink="sqlite" — resolve the path (~, .., every symlink) and refuse it, unread, unless it lies under $IAIOPS_HOME, the config directory, or a directory listed in IAIOPS_AGENT_READ_DIRS (os.pathsep-separated absolute paths, e.g. ~/exports:~/advisories; set in the server's environment or ~/.iaiops/.env — no tool writes either). An entry that is relative, /, contains the home directory, is owned by another user or is writable by group or others is ignored. The refusal says nothing about the file, not even whether it exists. The CLI reads any path the operator types.

  • An agent writes files only to its own exports directory. The MCP tools that WRITE a file the agent names — export_data, compliance_report, compliance_evidence_bundle, alarm_rationalization_worksheet — resolve the path the same way and refuse it unless it lies under $IAIOPS_HOME/exports or a directory listed in IAIOPS_AGENT_WRITE_DIRS (same rules; an entry that overlaps $IAIOPS_HOME or the config directory is ignored, so the audit, undo and sample stores are never in reach). historian_push(sink="sqlite") additionally refuses the audit / undo stores and any existing database that holds tables other than samples. Before 0.31.0 these writers checked only for ..: export_data(fmt="sqlite", out_path="~/.iaiops/audit.db") replaced the audit database.

  • iaiops writes values, never PLC logic. No tool downloads, uploads, flashes or edits a PLC program — the plc_program_* tools read an exported file. The only state-changing tools are ten MOC-gated value writes (setpoints, tags, registers, properties, a state change), dry-run by default, approver-gated, with the before-value captured for undo. tests/test_no_plc_logic_writes.py fails the day that stops being true.

  • safety: sis — a safety instrumented system is never written. Mark an endpoint safety: sis and every write tool refuses it, previews included, whatever approvals exist (rule safety_sis_no_writes, audited as a denial); reads stay allowed. iaiops is not a safety system and not an IEC 61508 / 61511 tool — a SIS is changed under the plant's own functional-safety management of change.

  • Do not point this at a production control system without authorization. OT networks are safety-critical; even reads add load. Test against a simulator first.

  • All endpoint-returned text is sanitized (prompt-injection defense); secrets are never returned by any tool; MTConnect XML is parsed with DTD/entity declarations refused.

  • Every tool runs through the vendored governance harness: SQLite audit (~/.iaiops/audit.db, SHA-256 hash-chained rows + iaiops audit verify; audit fails closed for high/critical writes), token/call budget + runaway breaker, risk-tier gate (policy engine fails closed on a broken rules.yaml), undo recording. The MCP server refuses to start if any registered tool lacks the governance marker.

Roadmap

Four items that used to sit here had in fact shipped — including two this same README already listed as verified, three sections above. Listing built work as future work is the same defect as claiming unbuilt work, so they are gone: EtherNet/IP PCCC (PLC-5/SLC-500) and Micro800, passive asset discovery (iaiops scan --posture passive, ARP-cache only, emits nothing), OPC-UA certificate security, and MTConnect streaming long-poll.

What is genuinely open:

  • EtherCAT EoE / FoE / SoE mailbox protocols and full PDO-mapping decode (CoE SDO/PDO read+write and AL-state landed in 0.3.0 via the optional pysoem extra).

  • Sparkplug B Template deep expansion (DataSet landed in 0.17.0).

  • Contextual baselines — one normal band per tag today, but an OT normal range moves with shift, product and start-up. Learn per bucket, and refuse a bucket with too few samples rather than falling back to a global band, which would disguise "never seen this regime" as "this regime is normal".

  • Relationship-aware root cause, further — iaiops relations declare already gives RCA a declared line order as a second axis; what is left is using it beyond the timeline (e.g. ranking with it by default).

  • Passive discovery from a SPAN/tap — the ARP-cache posture is built; reading a mirror port is not.

Missing a protocol, device, or feature? 缺功能提 issue/PR 欢迎留言 — open a GitHub issue or PR.

License

MIT © wei

Available Tools

157 tools
adopt_alias_mapA
Read-only

[READ][risk=low][PERSIST] Adopt + persist the canonical alias map for a site.

Writes a local owner-only advisory JSON file (NOT an OT-device write — hence
risk=low); see the persistence note below.

Runs the cross-protocol asset model over ``feeds``, extracts the adopted map
``{canonical_alias: {ref, protocol, asset, name, class}}``, and persists it as
the site's baseline (owner-only JSON under the iaiops home). Re-running
overwrites the baseline. Advisory — the map is a SUGGESTION, never a
server-side rename (OT-dangerous).

Args:
    feeds: Per-protocol tag feeds ``[{protocol, source, asset?, tags:[...]}]``,
        the SAME shape ``cross_protocol_asset_model`` takes.
    site: Site label (a safe file leaf: alphanumeric/_/-). Default 'site'.

Returns dict: {site, path, tag_count, adopted:{alias: {...}}}.

Example: adopt_alias_map(feeds=[{"protocol":"opcua","source":"l1","tags":[...]}],
    site="plant").

Inputs: feeds (required), site.

alarm_bad_actorsA
Read-only

[READ][risk=low] ISA-18.2 alarm-flood analysis over a list of alarm events.

Args:
    events: Alarm/condition events — {source, timestamp (ISO-8601), priority?,
        state? (ACTIVE/RTN/ACK)}.
    window_minutes: Analysis window; omitted → inferred from event timestamps.
    chatter_window_s: A source with >=3 transitions inside this window chatters.
    standing_s: An alarm active longer than this is 'standing/stale' (default 24h).
    top_n: How many top offenders to return.

Returns dict: {event_count, window_minutes, alarms_per_hour,
    isa_18_2:{ok_max:6, manageable_max:12, flood_min:30},
    flood_verdict ('ok'|'manageable'|'over_target'|'flood'),
    priority_distribution, pareto_sources_for_80pct, top_offenders:[{source,
    count, share_pct, chattering, standing}], chattering:[...], standing:[...]}.

Example: alarm_bad_actors(events=[{"source":"FIC101","timestamp":"...",
    "priority":"high"}, ...]).

Inputs: events (required), top_n, standing_s, window_minutes, +1 more.

alarm_cascadeA
Read-only

[READ][risk=low] Collapse an alarm flood into cascades + each cascade's first-out root.

Answers "which alarm to look at first" when 100+ alarms hit in minutes: groups annunciations
into cascades (a new cascade starts after a quiet gap > window_s) and reports the FIRST-OUT
alarm (earliest in the burst) as the likely root, plus downstream members and any chattering
sources. First-out is a transparent heuristic cited by timestamp — NOT causal (use
downtime_root_cause for causality). Pass 'events' for pure analysis, or an endpoint to collect
live via the OPC-UA active-condition scan. Read-only; bounded.

Args:
    endpoint: Endpoint name from config (used only when events is omitted).
    duration_s: Live collection window in seconds (1..300, default 60).
    window_s: Quiet gap (seconds) that separates one cascade from the next (default 60).
    min_cascade: Minimum annunciations for a group to count as a cascade (default 2).
    events: Injected alarm events — {source, timestamp (ISO-8601), state?}; skips live collect.

Returns dict: {cascade_count, total_activations, cascades:[{root:{source, ts}, size,
    distinct_sources, span_s, members[], chattering[]}], collected?}.

Example: alarm_cascade(events=[{"source": "PT101", "timestamp": "2026-06-28T10:00:00Z"}, ...]).

Inputs: events, endpoint, window_s, duration_s, +1 more.

alarm_event_clustersA
Read-only

[READ][risk=low] Collapse ten phrasings of one fault into one row.

`alarm_bad_actors` ranks by SOURCE, which answers "which instrument is
noisiest" and not "which fault is noisiest". A plant that words one condition
ten ways — `PT-101 HIGH`, `PT-102 HIGH`, `PT-103 high alarm` — gets ten bad
actors and no sign that they are one problem, so a rationalization meeting
works the list top-down and fixes the same thing three times. This groups the
same events by what they SAY instead of by who said it.

Clustering is **exact equality of a normalized string, not similarity**: case,
punctuation and embedded numbers are removed, and what remains must match
exactly. That is deliberately dumber than it could be, and it is why the
result needs no model and can be checked — two messages land together only
when they are literally the same sentence with the identifiers taken out.
Every cluster carries the distinct wordings and sources it merged, so you can
see what was combined. It does **not** claim two differently-worded alarms
mean the same thing; a person decides that.

Events carrying no message text are counted separately and excluded from the
shares, rather than being lumped together as one type.

Args:
    events: [{source?, message|description|text|condition|type, ...}].
    top_n: Clusters returned, largest first (default 20, capped at 100).
    min_count: Only report clusters with at least this many events (default 1 —
        a one-off is still reported, not tidied away).

Returns dict: {events_supplied, events_clustered, events_without_text,
    cluster_count, collapsed_count, clusters:[{signature, count, share_pct,
    distinct_wordings, distinct_sources, variants:[{text, count}],
    sources:[{source, count}]}], note}.

Example: alarm_event_clusters(events=[{"source":"PT-101","message":"pressure HIGH"},
    {"source":"PT-102","message":"Pressure high!"}]).

Inputs: events (required), top_n, min_count.

alarm_flood_analysisA
Read-only

[READ][risk=low] ISA-18.2 deep alarm-flood analysis: episodes + chattering + stale + advice.

Deepens alarm_bad_actors: detects flood *episodes* (start/end/count/peak rate/
top contributors + each episode's first-out annunciation, per ISA-18.2's >=10
alarms per 10 min per operator), alarms chattering ACTIVE↔CLEARED, standing/
stale alarms, and percent-time-in-flood vs the ISA-18.2 targets (~1-2 alarms/
10 min steady state, <1% time in flood). Also returns an ISA-18.2 'load_profile'
(per-bucket rate band + peak period + trend) and per-source 'suppression_advice'
(deadband/on-off-delay for chatter, time-limited shelve for standing alarms).
The suppression advice is ADVISORY ONLY — starting values for a human to review
and approve via your ISA-18.2 / management-of-change process; this tool never
applies suppression, shelving, deadband, or delay changes. Pass 'events' for
pure analysis, or an endpoint to collect live via the same OPC-UA active-
condition scan the RCA copilot uses (polled over duration_s; other protocols
contribute no alarms). Output is bounded; 'truncated' flags say when caps bit.

Args:
    endpoint: Endpoint name from config (used only when events is omitted).
    duration_s: Live collection window in seconds (1..300, default 60).
    window_s: Flood analysis window in seconds (ISA-18.2 default 600).
    threshold: Annunciations per window that start a flood (default 10).
    events: Injected alarm events — {source, timestamp (ISO-8601), state?
        (ACTIVE/RTN/CLEARED)}; skips live collection entirely.
    stale_after_s: Continuously-active age that marks a standing alarm (default 24h).
    max_episodes: Cap on returned flood episodes (default 20).
    max_rows: Cap on chattering / stale / suppression-advice / worksheet rows (default 50).
    load_bucket_s: Load-profile bucket width in seconds (ISA-18.2 default 600 = 10 min).

Returns dict: {event_count, summary:{insufficient_data, percent_time_in_flood,
    avg_alarms_per_10min, peak_alarms_per_10min, isa_18_2_targets, ...},
    load_profile:{overall_band, peak_bucket, band_distribution, trend,
    busiest_buckets:[...], ...}, flood_episodes:[{start, end, ..., top_contributors,
    first_out:{source, ts}}], chattering:[{source, cycles, cycles_per_hour, ...}],
    stale_standing:[{source, active_since, active_for_s}], suppression_advice:[{source,
    kind, technique, suggested_on_delay_s, suggested_off_delay_s, suggested_shelve_max_s,
    basis, advisory}], worksheet_preview:[...], advisory_note, truncated:{...}, collected?}.

Example: alarm_flood_analysis(events=[{"source":"FIC101",
    "timestamp":"2026-06-28T10:00:00Z","state":"ACTIVE"}, ...]).

Inputs: events, endpoint, max_rows, window_s, +5 more.

alarm_rationalization_worksheetA
Read-only

[READ][risk=low] ISA-18.2 alarm-rationalization worksheet (CSV or inline rows).

One row per alarm source, count-descending: count, % of total annunciations,
chattering?, flood contributor?, and a recommendation stub — the starting
document for an ISA-18.2 rationalization review. Pass 'events' for pure
analysis, or an endpoint to collect live via the same OPC-UA active-condition
scan the RCA copilot uses. With out_path the full worksheet is written as CSV
and the path returned; otherwise bounded inline rows (truncation noted).

Args:
    endpoint: Endpoint name from config (used only when events is omitted).
    duration_s: Live collection window in seconds (1..300, default 60).
    events: Injected alarm events — {source, timestamp (ISO-8601), state?}.
    window_s: Flood analysis window in seconds (ISA-18.2 default 600).
    threshold: Annunciations per window that start a flood (default 10).
    out_path: Optional CSV destination; parent directory must exist.

Returns dict: {row_count, columns:[alarm_id, count, pct_of_total, chattering,
    in_flood, recommendation], csv_path? , rows?:[...], truncated (bool)}.

Example: alarm_rationalization_worksheet(events=[...], out_path="worksheet.csv").

Inputs: events, endpoint, out_path, window_s, +2 more.

anomaly_scanA
Read-only

[DEPRECATED → opcua_anomaly_scan][READ][risk=low] Statistical outlier scan.

Samples a node over a bounded window and flags statistical outliers.
Computes mean/stddev/min/max and flags samples outside mean ± sigma*stddev.
Simple statistics only — no ML, no persisted model.

Args:
    node_id: The OPC-UA node id to scan.
    endpoint: Endpoint name from config.
    samples: Max samples (capped server-side).
    interval_ms: Delay between samples in milliseconds.
    sigma: Outlier band width in standard deviations.

Inputs: node_id (required), sigma, samples, endpoint, +1 more.

asset_inventoryA
Read-only

[READ][risk=low] Actively fingerprint endpoints into an asset register.

Connects to each target with our own protocol client and reads its identity
call (S7 CPU info, EtherNet/IP controller info, OPC-UA server build info,
Modbus device identification FC43, Mitsubishi CPU type, MTConnect device
model), aggregating vendor/model/firmware/serial per device.

Honest scope: ACTIVE fingerprinting (we connect to each device), NOT passive
SPAN/tap discovery. Only finds devices we are configured to reach.

Args:
    endpoints: Endpoint names to fingerprint; omit to fingerprint ALL
        configured endpoints.

Returns dict: {asset_count, reachable_count, unreachable_count, method:
    'active_fingerprint', assets:[{endpoint, protocol, address, vendor, model,
    firmware, serial, reachable, last_seen, error}]}.

Example: asset_inventory(endpoints=["press1","cell5"]).

Inputs: endpoints.

baseline_checkA
Read-only

[READ][risk=low] Check recent local samples against the learned baseline.

Reads the last window_s seconds from ~/.iaiops/data.db (no device I/O) and
judges them against the stored band. Conservative by design: a violation is
reported ONLY when values are beyond p1/p99 by more than 3×MAD AND sustained
for >=3 consecutive samples — a single spike is never flagged. Every
violation cites the baseline window (from/to ts, n samples), the band
values, and the offending samples' timestamps/values. No stored baseline →
an explicit no_baseline answer (never a guess). Bounded output (<=10
violations, <=20 cited samples each).

Args:
    tag: Tag name to check, e.g. 'line1.temp'.
    endpoint: Only samples from this endpoint label.
    window_s: Recent window to check, seconds (60..604800; default 3600).

Returns dict: {status: 'ok'|'violation'|'no_baseline', tag, checked_samples,
    thresholds, baseline_citation, violations:[{direction, from_ts, to_ts,
    consecutive_samples, samples:[{ts,value}], baseline}], note}.

Example: baseline_check(tag="line1.temp", window_s=7200).

Inputs: tag (required), endpoint, window_s.

baseline_check_in_contextA
Read-only

[READ][risk=low] Check readings against the band for ONE declared context.

A reading whose context was never learned comes back `unknown_context` and
stops there. It is **not** compared against the global band or the nearest
one, and that refusal is the entire point of the tool: borrowing a band turns
"we have never seen this regime" into "this regime is normal" — a silent
pass, in the direction nobody reports. The response lists the contexts that
do have bands so the gap is actionable.

Otherwise the usual conservative rules apply: a violation needs values beyond
the band by more than `margin_mad` × MAD AND sustained over `sustain_n`
consecutive samples, and every flag cites the baseline it was judged against.

Args:
    samples: [{ts, value, ...}] readings to check.
    contextual: A `baseline_learn_contextual` result.
    context: Which declared context these readings belong to.
    margin_mad: MAD margin beyond the band before flagging (default 3.0).
    sustain_n: Consecutive samples required (default 3 — no single-spike flags).

Returns dict (known context): the `baseline_check` shape plus {context,
    context_key}. (unknown): {status:"unknown_context", tag, context,
    known_contexts, checked_samples, reason, note}.

Example: baseline_check_in_context(samples=[...], contextual={...}, context="recipe-B").

Inputs: context (required), samples (required), contextual (required), sustain_n, +1 more.

baseline_learnA
Read-only

[READ][risk=low] Learn a conservative per-tag normal band from local history.

Source is ~/.iaiops/data.db — the local store written by
historian_push(sink="sqlite") — NOT a live device read. Learns robust
percentiles (p1/p99 + median/MAD, no ML) from the tag's own samples,
segmented at the latest change recorded via baseline_record_change (the band
reflects only the post-change regime). REFUSES with an explicit
insufficient_data verdict (listing exactly what is missing) below 100 usable
samples or under 24h of span — it never invents a band from thin data. On
success the band is persisted to ~/.iaiops/baselines.json (owner-only local
metadata, not an OT write).

Args:
    tag: Tag name to learn, e.g. 'line1.temp'.
    endpoint: Only samples from this endpoint label.
    since: Only samples at/after this ISO-8601 time.

Returns dict: {status: 'ok'|'insufficient_data', tag, band:{p1,p99,median,mad},
    n_samples, window:{from_ts,to_ts,span_s}, segment, missing?:[...], note}.

Example: baseline_learn(tag="line1.temp", since="2026-06-01T00:00:00").

Inputs: tag (required), since, endpoint.

baseline_learn_contextualA
Read-only

[READ][risk=low] Learn one conservative band per declared context, not one per tag.

One band per tag is wrong the moment a tag has more than one normal. A dryer
running recipe A at 180 °C and recipe B at 240 °C gets a band spanning both,
after which neither regime can go wrong — the band is too wide to catch a
real excursion and too mixed to mean anything. OT normal ranges move with
shift, product/recipe, and start-up versus steady state.

**The context is declared, never inferred** (D16). Each sample carries a
label under `context_key`; nothing here guesses which shift a timestamp falls
in or clusters values into regimes it then treats as real. Each context is
handed to the same learner as a global baseline, so it refuses on the same
terms — a thin context is left without a band rather than borrowing another
context's samples. Samples with no label are counted and named, not pooled
into a default bucket, because a default bucket is that same fallback.

Pass samples in (as with `spc_check` / `tag_health`). The local store's
`samples` table has no context column, so there is deliberately no
`iaiops baseline learn --context` yet; wiring one is a schema change and is
not done.

Args:
    samples: [{ts, value, quality?, tag?, <context_key>}] rows.
    tag: The tag being learned.
    context_key: Field that declares the context (default "context").
    min_samples: Per-context minimum before a band is learned (default 100).
    min_span_s: Per-context minimum history span in seconds (default 86400).

Returns dict: {tag, context_key, contexts:{label: learn_baseline result},
    learned_contexts, refused_contexts, uncontexted_samples, note}.

Example: baseline_learn_contextual(samples=[{"ts":"...","value":181.0,
    "context":"recipe-A"}], tag="dryer.temp").

Inputs: tag (required), samples (required), min_span_s, context_key, +1 more.

baseline_record_changeA
Read-only

[READ][risk=low] Record an operator change-log entry for a tag (local only).

Writes ONLY local metadata (~/.iaiops/baselines.json, owner-only) — never an
OT device write, hence risk=low. A recorded change (setpoint moved, valve
replaced, probe swapped) marks a regime boundary: the next baseline_learn
uses only samples AFTER the latest change, so the band never mixes
pre-change and post-change behavior. This operator change log — not a
black-box score — is what makes the baseline trustworthy.

Args:
    tag: Tag whose process changed, e.g. 'line1.temp'.
    note: What changed (required), e.g. 'setpoint 60→70C'.

Returns dict: {tag, change:{ts, note}, changes_recorded}.

Example: baseline_record_change(tag="line1.temp", note="setpoint 60→70C").

Inputs: tag (required), note (required).

baseline_statusA
Read-only

[READ][risk=low] Baseline status for one tag, or a bounded listing of all.

Read from the local store only (no history scan, no device I/O) and never
guesses: 'no_baseline' (nothing learned, no refused attempt), 'learning'
(last learn refused — still accumulating history), 'ok' (band learned, last
check clean), 'violation' (last check flagged a sustained excursion). With
no tag, lists every tracked tag (bounded to 100 entries).

Args:
    tag: Optional tag name; omit to list all tracked tags.

Returns dict: {tag, status, band?, baseline_window?, changes_recorded?, ...}
    for one tag, or {tracked_tags, listed, truncated, tags:[...]} for all.

Example: baseline_status(tag="line1.temp").

Inputs: tag.

changeover_analysisA
Read-only

[READ][risk=low] Changeover / SMED durations between products.

Breaks out what OEE availability only aggregates: each changeover is the gap
between the last good part of one product and the first good part of the next
— the setup/adjustment time SMED shrinks. Measures every changeover, ranks the
longest, and totals the lost time, worst-first, each duration cited by its two
bounding timestamps. Pure analysis over readings you pass in (a good-part
completion stream from the MES / PLC counters); read-only, advisory.

Args:
    good_parts: [{timestamp (ISO-8601), product}] — one per good part, any
        order (sorted by time). A changeover is recorded at each product change.

Returns dict: {good_parts, ignored, changeover_count, changeovers:[{from, to,
    start, end, durationS}], longest, avgDurationS, totalChangeoverS, note}.

Example: changeover_analysis(good_parts=[{"timestamp":"2026-07-12T08:00:00Z","product":"A"},
    {"timestamp":"2026-07-12T08:45:00Z","product":"B"}]).

Inputs: good_parts (required).

compliance_dengbao_levelsA
Read-only

[READ][risk=low] 等保 2.0 二级 vs 三级 per-pillar deltas + honest iaiops posture.

等保 2.0 (GB/T 22239) is graded — the same control tightens as the level rises.
Per governance pillar this shows the 二级 baseline, what 三级 additionally requires,
and how far iaiops moves you toward it (with the honest per-control status/gap).
An onboarding/self-assessment aid, NOT a certification.

Args:
    level: Focus on one level — 'l2'/'l3', '二级'/'三级', or '2'/'3'. Omit for both.

Returns dict: {framework, levels:[{id,name,note}], selected_level, pillar_count,
    deltas:[{pillar, l2_requires?, l3_adds?, iaiops, iaiops_status, gap}], note}.

Example: compliance_dengbao_levels(level="三级").

Inputs: level.

compliance_evidence_bundleA
Read-only

[READ][risk=low] Export the audit-evidence bundle (zip) for an auditor.

Packages the governance evidence trail into one deterministic zip:
audit_rows.jsonl (secrets already redacted upstream), chain_verification.json
(SHA-256 hash-chain walk result), rules.yaml (if present), doctor_summary.json
(non-probing config/secret-store facts), and manifest.json. Path is validated
(no '..' traversal; parent created 0700).

Args:
    out_path: Destination zip path (must end in .zip).
    since: Optional ISO-8601 floor on the audit row timestamp (inclusive).
    until: Optional ISO-8601 ceiling on the audit row timestamp (inclusive).

Returns dict: {path, row_count, chain{ok, checked, unhashed, ...}, files[],
    since, until}.

Example: compliance_evidence_bundle(out_path="/tmp/evidence.zip",
    since="2026-06-01T00:00:00+00:00").

Inputs: out_path (required), since, until.

compliance_frameworksA
Read-only

[READ][risk=low] 跨框架对照: 防护指南 ↔ 等保 2.0 ↔ IEC 62443 ↔ GxP ↔ NIS2 ↔ CRA.

Omit ``framework`` for one row per governance pillar: the matching 《防护指南》
requirement, 等保 2.0 control class, IEC 62443 FR, GxP clause, the NIS2 / CRA item
refs that cite the pillar, and the iaiops status. Pass framework="nis2" (Directive
(EU) 2022/2555 Art. 21(2)(a)-(j)) or "cra" (Regulation (EU) 2024/2847 Annex I) for
that text item by item, each with an honest coverage: product_evidence (a cited,
code-anchored mechanism produces relevant evidence — never "the measure is met"),
gap, or organisational (product provides no evidence). NIS2 obliges entities, the
CRA manufacturers — a product self-assessment, NOT a certification.

Args:
    framework: None for the per-pillar crosswalk, or 'nis2' / 'cra'.

Returns dict: per-pillar {frameworks[], framework_count, pillar_count,
    crosswalk:[{pillar, gjzn, dengbao, iec62443, gxp, nis2, nis2_refs, cra,
    cra_refs, iaiops_status}], note} — or for nis2/cra {framework, applies, scope,
    item_count, coverage_summary, items:[{id, ref, measure, coverage, iaiops, gap,
    mechanisms, mechanism_detail, pillars}], disclaimer, source}.

Example: compliance_frameworks(framework="nis2").

Inputs: framework.

compliance_mappingA
Read-only

[READ][risk=low] 《工控系统网络安全防护指南》 ↔ iaiops governance mapping.

An honest onboarding/sales self-assessment across the pillars 分区隔离 / 可审计 /
双向认证 / 最小权限 / 数据保护 / 自主可控. Each control names how iaiops addresses
it, an honest status (addressed / partial / 待核实), and the remaining gap.

Returns dict: {framework, frameworks[], pillars[], control_count, status_summary
    {addressed, partial, 待核实}, controls:[{pillar, requirement, iaiops, status,
    gap, crosswalk{dengbao, iec62443}}]}. See compliance_frameworks for the full
    cross-framework 对照.

Example: compliance_mapping().

Inputs: no named parameters.

compliance_reportA
Read-only

[READ][risk=low] Render the 等保 2.0 / IEC 62443 or NIS2 / CRA report (Markdown).

Turns the compliance crosswalk into a deliverable document a CISO can read:
title-page metadata (site / date / iaiops version), per-pillar 等保 L2/L3 status
table, IEC 62443 FR1–6 crosswalk, honest gap list, and a governance-controls
appendix (audit hash chain / approval tokens / dry-run+undo / mTLS). With
framework='nis2' / 'cra' / 'eu' it renders instead the English NIS2 Art. 21 /
CRA Annex I self-assessment (product evidence and gaps, organisational measures
separated, cited mechanisms with code anchors). An onboarding/self-assessment
aid, NOT a certification.

Args:
    level: 等保 2.0 target level — 'l2'/'l3', '二级'/'三级', '2'/'3'. Omit for both.
        Refused together with an EU framework.
    site: Site / plant name stamped on the title page.
    out_path: Optional file to write the markdown to (.md). Required when the
        report exceeds the inline bound (~400 lines): without it the inline
        markdown is truncated with a note.
    framework: Omit for the 等保 report; 'nis2', 'cra' or 'eu' (both).

Returns dict: {format, framework, level, line_count, path?} plus either the full inline
    {markdown} (when within bounds and no out_path) or {markdown (truncated),
    truncated: true} with a hint to pass out_path.

Example: compliance_report(level="三级", site="示例水厂",
    out_path="/tmp/compliance-report.md").

Inputs: site, level, out_path, framework.

cross_protocol_asset_modelA
Read-only

[READ][risk=low] Fuse per-protocol tag feeds into ONE unified asset model.

Unifies the two per-protocol tag models (OPC-UA address-space discovery +
Modbus register templates) into one cross-protocol asset/tag/alias model. Tags
are re-classified with the SAME semantic classifier the OPC-UA layer uses,
grouped into assets ACROSS protocols (a ``Line1`` OPC-UA folder + a ``Line1``
Modbus block become one asset), and each gets a canonical alias
``<site>.<asset>.<class_or_name>``. Advisory only — aliases are SUGGESTIONS,
never a server-side rename (OT-dangerous).

Args:
    feeds: List of per-protocol feeds, each
        ``{protocol, source, asset?, tags:[...]}``. ``tags`` may be OPC-UA
        discovery descriptors (from opcua_discover_tags), Modbus template tags
        (from modbus_apply_template), or already-normalized tags. A feed-level
        ``asset`` is applied to its tags that don't carry their own.
    site: Site prefix for canonical aliases (default 'site').

Returns dict: {site, protocols, tag_count, asset_count, assets:[{asset,
    protocols, tag_count, classes, tags:[{protocol, source, name, ref, asset,
    unit, klass, canonical_alias, suggested_alias}]}], naming_quality:
    {alias_collisions, cross_protocol_overlaps, cryptic_names, verdict}}.

Example: cross_protocol_asset_model(feeds=[
    {"protocol":"opcua","source":"line1","tags":[...]},
    {"protocol":"modbus","source":"meter1","asset":"Line1","tags":[...]}],
    site="plant").

Inputs: feeds (required), site.

data_quality_fleet_rollupA
Read-only

[READ][risk=low] Cross-endpoint fleet rollup of data-TRUST: worst tags + bad quality.

Builds on data_quality_scorecard to give a fleet-wide view: endpoints ranked by
their single worst tag, bad-quality tag counts aggregated across every endpoint,
and a first-class liveness rollup (dead-heartbeat / flatline). Staleness and gap
budgets are configurable per tag (staleness_s / gap_threshold_s) and per feed,
so a slow daily counter is not judged like a 1Hz sensor. Pure analysis.

Args:
    feeds: Per-endpoint feeds — {endpoint, staleness_s?, tags:[{ref, label?,
        samples:[scalars or {value, good|quality, timestamp?}], expected_update_s?,
        staleness_s?, gap_threshold_s?, flatline_after_s?, heartbeat?}]}.
    default_staleness_s: Fallback max sample-age (seconds) before 'stale' when a
        tag/feed sets no staleness_s/expected_update_s (default 300).
    now: ISO-8601 reference time for staleness (deterministic); omit for now-UTC.
    top_n: How many endpoints / bad-quality rows to return (default 10).

Returns dict: {evaluated_endpoints, evaluated_tags, fleet_score (0-100),
    fleet_status, endpoints_ranked_by_worst_tag:[...], bad_quality_rollup:
    {total_bad_quality_tags, endpoints_affected, by_endpoint:[{endpoint,
    bad_quality_tags, fully_bad, partial_bad}]}, liveness_rollup:
    {dead_heartbeat_count, flatline_count, dead_heartbeats[], flatlines[]},
    issue_breakdown{}}.

Example: data_quality_fleet_rollup(feeds=[{"endpoint":"line1","tags":[{"ref":"t",
    "samples":[{"value":None,"good":false}]}]}]).

Inputs: feeds (required), now, top_n, default_staleness_s.

data_quality_scorecardA
Read-only

[READ][risk=low] Fleet data-TRUST scorecard across endpoints' tag feeds.

Scores each tag 0-100 on whether its data can be BELIEVED — staleness, dead
heartbeat, bad-quality, flatline, gaps, anomaly — then rolls up per endpoint
and across the fleet. NOT process health (it does not score whether a value is
alarming, only whether it is trustworthy). Pure analysis over provided feeds.

Args:
    feeds: Per-endpoint feeds — {endpoint, tags:[{ref, label?, samples:[scalars
        or {value, good|quality, timestamp?}], expected_update_s?, heartbeat?}]}.
    default_staleness_s: Max sample-age before 'stale' when a tag sets no
        expected_update_s (default 300).
    now: ISO-8601 reference time for staleness (deterministic); omit for now-UTC.

Returns dict: {evaluated_endpoints, evaluated_tags, fleet_score (0-100),
    fleet_status, issue_breakdown{}, worst_endpoints[], worst_tags[],
    endpoints:[{endpoint, score, status, status_counts, worst_tag}]}.

Example: data_quality_scorecard(feeds=[{"endpoint":"line1","tags":[{"ref":"hb",
    "heartbeat":true,"samples":[5,5,5,5]}]}]).

Inputs: feeds (required), now, default_staleness_s.

device_advisory_checkA
Read-only

[READ][risk=low] Which scanned devices fall inside a mounted advisory's stated range.

`iaiops scan` already reads vendor / model / firmware / serial and then does
nothing with them. This closes that loop — and deliberately stops short of
where a vulnerability scanner would go.

**It reports that a device falls inside an advisory's stated range. Nothing
more.** Not "vulnerable", not "exploitable", no severity score. Whether a
published issue is reachable on a particular machine depends on
configuration, network position and compensating controls that a read-only
scan cannot see — and in OT most advisories against a protocol stack are not
findings at all, because the stack is not reachable from anywhere that
matters. A report full of red text that ignores that gets switched off by the
site, and then the real one is missed too.

**No database ships with this.** A bundled CVE feed is a maintenance
commitment this repo has not made, and a stale one that looks current is
worse than none — so the library is a file the site controls, which also
makes it work air-gapped. Every entry must carry a source, and one bad entry
refuses the whole file rather than half-mounting it.

Four verdicts, and the middle two are the point: `in_affected_range`,
`version_unknown` (model matches, no firmware read — neither a hit nor a
pass), `version_unparsed` (a firmware string it will not invent an ordering
for), `not_affected`. A device no advisory mentions is **absent** from the
findings, not reported clean: "nothing known" is not "nothing there".

Args:
    devices: [{ip?, vendor, model, firmware?}] — e.g. the `hosts` of a scan.
    library_path: Path to the advisory file (.yaml/.yml/.json) this site
        mounted, under $IAIOPS_HOME, the config directory or a directory
        the operator lists in IAIOPS_AGENT_READ_DIRS (other paths are refused unread);
        entries are {id, vendor, model, source, affected_below|affected_from|
        affected_versions, title?}.

Returns dict: {devices_checked, advisories_mounted, devices_with_findings,
    summary:{in_affected_range, version_unparsed, version_unknown,
    not_affected}, findings:[{ip, vendor, model, firmware, advisory_id, title,
    source, status, detail}], truncated, advisory_note, note}.

Example: device_advisory_check(devices=[{"ip":"10.0.0.5","vendor":"Siemens",
    "model":"S7-1500","firmware":"2.8.1"}], library_path="~/advisories.yaml").

Inputs: devices (required), library_path (required).

diagnose_dataflowA
Read-only

[READ][risk=low] Localize a 'no data' break across an endpoint's reachable hops.

Probes connect → read(ref) → freshness → variance and returns a verdict with
per-hop detail and a recommended action. The #1 OT triage: distinguishes
"cannot connect" (network/PLC down) from "comms OK but value stale"
(upstream/field/source) from "good status but flatline" (sensor stuck).

Args:
    endpoint: Endpoint name from config (any protocol).
    ref: Tag/node/address/device to read (OPC-UA node id, Modbus address,
        S7 address string, MELSEC device). Omit to test connectivity only.
    freshness_threshold_s: Max value-age (seconds) before 'stale' (default 60).
    series: Optional injected samples (scalars or {value,timestamp}) for
        flatline/variance reasoning when a live historian is out of reach.
    flatline_eps: Spread at/below which a series counts as flatline.

Returns dict: {verdict ('cannot_connect'|'comms_ok_value_unreadable'|
    'comms_ok_description_mismatch'|'comms_ok_bad_quality'|
    'comms_ok_value_stale'|'comms_ok_flatline'|'no_per_ref_read_in_this_build'|
    'no_connect_probe_in_this_build'|'healthy'), diagnosis,
    recommended_action, hops:[{hop, ok, detail}]}.
    'comms_ok_description_mismatch' means the sensor profile does not fit the
    device (wrong sensor fitted, other process-data layout, no profile): fix
    the configuration, not the field.

Example: diagnose_dataflow(endpoint="line1", ref="ns=2;i=5", freshness_threshold_s=30).

Inputs: ref, series, endpoint, flatline_eps, +1 more.

diff_alias_mapA
Read-only

[READ][risk=low] Diff a fresh discovery run against the adopted baseline.

Loads the site's previously adopted alias map, re-runs the cross-protocol
asset model over ``feeds``, and reports how the address space moved: tags
added / removed / renamed (same ref, new alias) / reclassified (same ref+alias,
new semantic class), plus a stable|changed verdict. Adopt a baseline first
with ``adopt_alias_map``.

Args:
    feeds: Fresh per-protocol tag feeds (same shape as adopt_alias_map).
    site: Site label whose baseline to diff against. Default 'site'.

Returns dict: {site, verdict, counts:{added,removed,renamed,reclassified},
    added:[...], removed:[...], renamed:[...], reclassified:[...]}.

Example: diff_alias_map(feeds=[{"protocol":"opcua","source":"l1","tags":[...]}],
    site="plant").

Inputs: feeds (required), site.

downtime_attributionA
Read-only

[READ][risk=low] Which stoppage started it, and which ones were downstream of it.

RCA weights evidence by TIME alone — a signal before onset counts, one after
counts less. That is the honest half of the axis. Run `downtime_root_cause`
per asset after one upstream stop and every downstream machine comes back
with its own confident local root cause: each internally consistent, each
citing real signals, and all but one about a machine that stopped because it
was starved. The distinguishing fact is not in the evidence — it is the
line's topology.

Two rules decide an attribution and both must hold: the candidate must be
**declared upstream** of the asset, and it must have **stopped first**. An
upstream asset that stopped later cannot have caused an earlier stop, however
upstream it is.

Topology is declared, never inferred (D25). Co-occurrence on a production
line is guaranteed — everything stops together — so mining it for edges would
manufacture the causality this exists to remove. With no relations declared
every row comes back `not_evaluable` and the reason names the command that
fixes it. Assets the topology does not connect are left `unattributed` rather
than folded into the origin's column.

This ranks the stoppages; it does not diagnose the origin. Run
`downtime_root_cause` on the origin asset for that.

Args:
    stoppages: [{asset, start, end?}] for one incident window (ISO-8601).
    site: Which declared line topology to use (default "default").
    max_lead_s: A downstream stop is attributed only if it began within this
        many seconds of the upstream one (default 900).

Returns dict: {site, stoppages_evaluated, relations_declared, max_lead_s,
    verdict ('origin'|'multiple_origins'|'unattributed'|'not_evaluable'),
    origins, consequence_count, attributions:[{asset, start, status,
    origin_asset?, hops_upstream?, lead_s?, explains?, detail}], advisory}.

Example: downtime_attribution(stoppages=[{"asset":"filler","start":"2026-01-05T06:00:00Z"},
    {"asset":"capper","start":"2026-01-05T06:01:00Z"}]).

Inputs: stoppages (required), site, max_lead_s.

downtime_eventsA
Read-only

[READ][risk=low] Detect running→stopped transitions and categorize stoppages.

Args:
    series: Timestamped samples — {timestamp (ISO-8601), state} where state is
        a string (RUNNING/IDLE/FAULT…), a bool, or a number.
    category_map: Optional {state_label: category} override (else keyword
        heuristics map to changeover/material/mechanical/quality/break/unknown).
    min_duration_s: Ignore stoppages shorter than this (seconds).

Returns dict: {samples, event_count, total_downtime_s, by_category:{cat:
    {count, downtime_s}}, events:[{start, end, duration_s, state, category}]}.

Example: downtime_events(series=[{"timestamp":"2026-06-28T08:00:00Z","state":"RUNNING"},
    {"timestamp":"2026-06-28T08:05:00Z","state":"FAULT"}, ...]).

Inputs: series (required), category_map, min_duration_s.

downtime_root_causeA
Read-only

[READ][risk=low] AI downtime root-cause copilot — cited verdict, ADVISORY only.

Correlates whatever evidence you supply around a downtime/incident window —
alarm events, tag samples, a diagnose_dataflow verdict, a machine-state series —
ranks candidate root causes, and cites the REAL signals behind each. Read-first:
it proposes a human-approved, undoable (MOC-gated) action but executes nothing.
Anti-hallucination: only signals present in the input are cited; thin evidence
downgrades to 'insufficient_evidence' with a 'recommended_next_data' list rather
than a confident guess. Confidence combines independent, time-correlated evidence
(signals BEFORE onset outweigh signals during it).

Args:
    window: {start (ISO-8601), end? (ISO-8601), asset?, category?}. If 'end' is
        omitted but state_series is given, the first running→stopped span bounds it.
    alarms: Alarm/condition events — {source, timestamp, message?, priority?, state?}.
    tags: Per-tag samples — {ref, samples:[scalars or {value, good|quality}],
        warn_high?, alarm_high?, ...} (scored via tag_health).
    dataflow: A diagnose_dataflow result dict (its 'verdict' localizes comms vs field).
    state_series: {timestamp, state} samples to bound the window if 'end' is absent.
    lead_window_s: How far before onset a signal may sit and still count as a cause
        (default 300s); signals after onset are treated as consequences.
    cause_weights: Optional per-site {cause: multiplier} override (e.g. from
        learn_cause_weights) — scales each cause's evidence (1.0 = neutral
        default) before the noisy-OR. Unknown causes / non-numeric weights are
        rejected; values are clamped. Omit for the shipped default weighting.
    include_graph: When true, also return a 'graph' block — the SAME verdict
        re-projected as a causal graph {nodes, edges, mermaid, meta} (signal →
        cause → downtime) for a frontend/Grafana. Pure re-shape: signal→cause
        edge weights are the evidence contribution scores, cause→symptom edge
        weights are the hypothesis confidences — no new reasoning. Omit for the
        flat verdict only (default).

When a per-site 'historian:' block is configured (~/.iaiops/config.yaml, A7),
the 2h pre-incident window is additionally pulled from that reader and scored
as historian trend evidence — cited with its source ('historian:<name>'),
window, and sample count. Without the config, behaviour is unchanged.

Returns dict: {window, verdict ('root_cause_identified'|'multiple_candidates'|
    'insufficient_evidence'), primary_cause, hypotheses:[{cause, confidence (0..1),
    confidence_band, evidence:[{signal, ref, at?, lead_time_s?, detail, weight}],
    recommended_action}], evidence_summary, recommended_next_data?,
    anti_hallucination, graph? (when include_graph): {nodes:[{id, kind
    (signal|cause|symptom), label, score, ...}], edges:[{from, to, weight,
    relation (supports|attributed_to)}], mermaid, meta}}.

Example: downtime_root_cause(window={"start":"2026-06-28T10:00:00Z","asset":"line1"},
    alarms=[{"source":"M1_DRIVE","timestamp":"2026-06-28T09:59:50Z",
             "message":"motor overload trip"}], dataflow={"verdict":"healthy"}).

Inputs: window (required), tags, alarms, dataflow, +4 more.

downtime_root_cause_liveA
Read-only

[READ][risk=low] AI downtime RCA copilot that GATHERS its own live evidence.

Same advisory, read-only, evidence-cited contract as downtime_root_cause — but
instead of hand-injecting evidence you give an endpoint + incident window and it
pulls the evidence itself: a cross-protocol diagnose_dataflow probe, a short
sampled series per ref (so flatline/bad-quality/anomaly surface via tag_health),
and active OPC-UA conditions. Light read load; non-destructive; nothing executed.
The gathered bundle is echoed under 'collected_evidence' (no hidden inputs).

Args:
    endpoint: Endpoint name from config (any protocol). Omit for the default.
    window: {start (ISO-8601), end?, asset?, category?, freshness_threshold_s?}.
    refs: Tags/nodes/addresses to sample for this incident (first is also the
        diagnose_dataflow target). Capped at 20.
    sample_count: Reads per ref to build its series (1..60, default 8).
    interval_ms: Delay between reads (>=50ms, default 200).
    include_alarms: Surface active OPC-UA conditions as alarm evidence (OPC-UA only).
    lead_window_s: Causal lead window before onset (default 300s).
    include_graph: When true, also return the 'graph' block (same {nodes, edges,
        mermaid, meta} causal-graph re-projection as downtime_root_cause). Pure
        re-shape of the verdict; no new reasoning. Omit for the flat verdict.

Returns dict: same shape as downtime_root_cause plus 'collected_evidence'
    {endpoint, protocol, refs_sampled, alarms_found, dataflow_verdict}.

Example: downtime_root_cause_live(endpoint="line1",
    window={"start":"2026-06-28T10:00:00Z","asset":"line1"},
    refs=["ns=2;i=5","ns=2;i=6"]).

Inputs: refs, window, endpoint, interval_ms, +4 more.

downtime_triageA
Read-only

[READ][risk=low] One-call downtime triage: first-look alarm + RCA cause + precursors.

Answers the operator's three simultaneous questions on a stopped line — which
alarm to look at first, the likely cause, and whether anything warned us —
then cross-checks whether the first-out alarm agrees with the RCA verdict.
Composes alarm_cascade + downtime_root_cause + pdm_forecast over ONE incident;
every field traces to a sub-report echoed under 'cascade'/'rca'/
'precursor_forecasts'. Read-first and advisory: it proposes but executes
nothing. Thin evidence downgrades honestly rather than guessing.

Args:
    window: {start (ISO-8601), end?, asset?, category?}. If 'end' is omitted
        but state_series is given, the first running→stopped span bounds it.
    alarms: Alarm/condition events — {source, timestamp, message?, priority?,
        state?}. Feeds BOTH the first-out cascade and the RCA.
    tags: Per-tag samples — {ref, samples:[...], warn_high?, ...} (via tag_health).
    dataflow: A diagnose_dataflow result dict (localizes comms vs field).
    state_series: {timestamp, state} samples to bound the window if 'end' is absent.
    precursors: Signals to check for a pre-incident trend — [{signal, series:
        [scalars or {value, timestamp}], warn_high?, alarm_high?, warn_low?,
        alarm_low?}]; each is run through pdm_forecast and kept only when it was
        degrading/imminent before the trip.
    cascade_window_s: Quiet gap (s) separating alarm cascades (default 60).
    lead_window_s: Causal lead window before onset (default 300s).
    cause_weights: Optional per-site {cause: multiplier} RCA override.
    imminent_within_s: ETA horizon that marks a precursor 'imminent' (default 24h).
    include_graph: When true, the echoed 'rca' sub-report also carries a 'graph'
        block — the SAME verdict re-projected as a causal graph {nodes, edges,
        mermaid, meta} (signal → cause → downtime) for a frontend. Pure re-shape;
        no new reasoning. Omit to keep the flat rca summary (default).

Returns dict: {window, triage:{first_look:{source, ts, cascade_size, basis},
    likely_cause:{cause, verdict, confidence, confidence_band,
    recommended_action}, cross_check:{status ('corroborated'|'diverging'|
    'no_alarm_root'|'no_rca_primary'), detail}, precursors_missed:[{signal,
    status, direction, eta_to_limit, unit, limit}], recommended_next_data},
    cascade:{...}, rca:{verdict, primary_cause, top_hypotheses, graph?},
    precursor_forecasts:[...], anti_hallucination}.

Example: downtime_triage(window={"start":"2026-06-28T10:00:00Z","asset":"line1"},
    alarms=[{"source":"M1_DRIVE","timestamp":"2026-06-28T09:59:50Z",
             "message":"motor overload trip"}],
    precursors=[{"signal":"M1_temp","series":[...],"warn_high":80}]).

Inputs: window (required), tags, alarms, dataflow, +7 more.

eip_controller_infoA
Read-only

[READ][risk=low] Controller identity (proves the CIP link).

Args:
    endpoint: Endpoint name from config (protocol 'ethernetip'/'eip'); omit for default.
    plctype: Driver selector override — 'logix' (default), 'slc' (PLC-5/SLC-500/
        MicroLogix, PCCC), or 'micro800'. Omit to use the endpoint's configured plctype.

Returns dict: {endpoint, host, slot, plctype, controller, info_error}. For
    logix/micro800 controller carries {vendor, product_type, revision, serial,
    product_name, name, ...}; for slc it carries {processor_type}.

Example: eip_controller_info(endpoint="slc05", plctype="slc").

Inputs: plctype, endpoint.

eip_list_tagsA
Read-only

[READ][risk=low] Discover the controller's tags (Logix) or PCCC data files (SLC).

Logix/Micro800: enumerate the controller's symbol table without prior
knowledge (program-scoped tags appear as 'Program:<prog>.<tag>'). SLC/PCCC has
no symbol table, so the data-file directory (N7/B3/F8/... with element counts)
is returned instead.

Args:
    endpoint: Endpoint name from config.
    plctype: Driver selector override — 'logix' (default), 'slc', or 'micro800'.

Returns dict: logix → {endpoint, plctype, tag_count, tags:[{name, data_type,
    tag_type, structure, dimensions}]}; slc → {endpoint, plctype, file_count,
    files:[{file, elements, length}], directory_error, note}.

Example: eip_list_tags(endpoint="cell5"); eip_list_tags(endpoint="slc05", plctype="slc").

Inputs: plctype, endpoint.

eip_read_manyA
Read-only

[READ][risk=low] Batch-read many tags/addresses in one request.

Args:
    tags: Logix tag names (["Speed", "Temp", "Array[0]"]) OR SLC/PCCC
        data-table addresses (["N7:0", "F8:0", "B3:0/0"]).
    endpoint: Endpoint name from config.
    plctype: Driver selector override — 'logix' (default), 'slc' (PCCC), or 'micro800'.

Returns dict: {endpoint, plctype, count, items:[{tag, value, type, error, good}]}.

Example: eip_read_many(tags=["Speed","Temp"], endpoint="cell5");
    eip_read_many(tags=["N7:0","F8:0"], endpoint="slc05", plctype="slc").

Inputs: tags (required), plctype, endpoint.

eip_read_tagA
Read-only

[READ][risk=low] Read one tag/address with its type.

Args:
    tag: Logix tag ('Conveyor.Speed', 'Array[3]', 'Program:Main.X') OR an
        SLC/PCCC data-table address ('N7:0' int, 'B3:0/0' bit, 'F8:0' float,
        'T4:0.ACC', 'N7:0{10}' slice).
    endpoint: Endpoint name from config.
    plctype: Driver selector override — 'logix' (default), 'slc' (PCCC), or 'micro800'.

Returns dict: {endpoint, plctype, tag, value, type, error, good}.

Example: eip_read_tag(tag="Conveyor.Speed", endpoint="cell5");
    eip_read_tag(tag="N7:0", endpoint="slc05", plctype="slc").

Inputs: tag (required), plctype, endpoint.

eip_write_tagA
Destructive

[WRITE][risk=HIGH][MOC] Write ONE value to a tag/data-table address (off by default).

OT-DANGEROUS. Defaults to dry_run=True (nothing written). Captures the BEFORE
value (read-back) and records an undo descriptor so the change is reversible.
Set dry_run=False AND record an approver (OPCUA_AUDIT_APPROVED_BY) to apply.
未经授权勿对生产控制系统写入.

Args:
    tag: Logix tag name OR SLC/PCCC data-table address ('N7:0', 'F8:0', 'B3:0/0').
    value: Value to write (pycomm3 coerces to the tag's CIP/PCCC type).
    endpoint: Endpoint name from config.
    plctype: Driver selector override — 'logix' (default), 'slc' (PCCC), or 'micro800'.
    dry_run: When True (default) returns a preview without writing.

Returns dict: dry-run → {tag, plctype, dry_run:true, before, would_write, note};
    applied → {tag, plctype, dry_run:false, before, written, applied:true, _undo_id}.

Example (preview): eip_write_tag(tag="Setpoint", value=42, endpoint="cell5").

Inputs: tag (required), value (required), dry_run, plctype, +1 more.

ethercat_master_stateA
Read-only

[READ][risk=low] Open the master on the configured NIC; report bus state.

Needs Linux + root/CAP_NET_RAW + a dedicated NIC + real slaves (pysoem extra).
Degrades to a teaching error dict if pysoem/permission/NIC/bus is missing.

Args:
    endpoint: Endpoint name from config (protocol 'ethercat'); omit for default.

Returns dict: {endpoint, nic, master_state (INIT/PREOP/SAFEOP/OP/...),
    expected_working_counter, slaves_found, slaves_expected, slave_count_ok}.

Example: ethercat_master_state(endpoint="bus1").

Inputs: endpoint.

ethercat_read_pdoA
Read-only

[READ][risk=low] One cyclic snapshot of a slave's input process-data image.

Does a single send/receive cycle (never loops) and returns the input image.

Args:
    slave: Zero-based slave index.
    endpoint: Endpoint name from config.

Returns dict: {endpoint, slave, working_counter, input_byte_length, input_hex,
    output_byte_length}.

Example: ethercat_read_pdo(slave=0, endpoint="bus1").

Inputs: slave (required), endpoint.

ethercat_read_sdoA
Read-only

[READ][risk=low] CoE SDO upload: read one object-dictionary entry (acyclic).

Args:
    slave: Zero-based slave index.
    index: CoE object index (decimal, e.g. 0x1018 → 4120).
    subindex: Sub-index (default 0).
    size: Expected byte size (0 = let SOEM size it).
    endpoint: Endpoint name from config.

Returns dict: {endpoint, slave, index, subindex, byte_length, hex, as_uint}.

Example: ethercat_read_sdo(slave=0, index=0x1018, subindex=1, endpoint="bus1").

Inputs: index (required), slave (required), size, endpoint, +1 more.

ethercat_set_stateA
Destructive

[WRITE][risk=HIGH][MOC] Request an AL-state transition (off by default).

OT-DANGEROUS: moving to/from OP can START or STOP machine motion. Defaults to
dry_run=True. ``slave`` < 0 applies to the master (all slaves). Captures the
CURRENT state for undo. Set dry_run=False AND record an approver to apply.
未经授权勿对生产控制系统写入.

Args:
    state: Target AL-state: INIT | PREOP | SAFEOP | OP (or a numeric code).
    slave: Zero-based slave index, or -1 (default) for the whole master.
    endpoint: Endpoint name from config.
    dry_run: When True (default) returns a preview without changing state.

Returns dict: dry-run → {scope, dry_run:true, before, would_request, note};
    applied → {scope, dry_run:false, before, requested, reached, applied:true}.

Example (preview): ethercat_set_state(state="OP", slave=0, endpoint="bus1").

Inputs: state (required), slave, dry_run, endpoint.

ethercat_slave_infoA
Read-only

[READ][risk=low] Detail one slave: identity, SM/FMMU config, OD summary.

Args:
    slave: Zero-based slave index (from ethercat_slaves).
    endpoint: Endpoint name from config.

Returns dict: {endpoint, index, name, vendor_id, product_code, revision,
    config_addr, state, input_bytes, output_bytes, sync_managers[], fmmus[],
    object_dictionary:[{index, name, entry_count}]}.

Example: ethercat_slave_info(slave=0, endpoint="bus1").

Inputs: slave (required), endpoint.

ethercat_slavesA
Read-only

[READ][risk=low] Bus scan: enumerate every slave on the segment.

Args:
    endpoint: Endpoint name from config (protocol 'ethercat').

Returns dict: {endpoint, slave_count, slaves:[{index, name, vendor_id,
    product_code, revision, config_addr, state}]}.

Example: ethercat_slaves(endpoint="bus1").

Inputs: endpoint.

ethercat_write_sdoA
Destructive

[WRITE][risk=HIGH][MOC] CoE SDO download: write one OD entry (off by default).

OT-DANGEROUS. Defaults to dry_run=True (nothing written). ``value`` is a hex
string of the raw little-endian bytes (e.g. 'e803' = 1000 as uint16). Captures
the BEFORE value (SDO read-back) and records an undo descriptor. Set
dry_run=False AND record an approver to apply. 未经授权勿对生产控制系统写入.

Args:
    slave: Zero-based slave index.
    index: CoE object index (decimal, e.g. 0x607A → 24698).
    value: Hex string of raw little-endian bytes to write.
    subindex: Sub-index (default 0).
    endpoint: Endpoint name from config.
    dry_run: When True (default) returns a preview without writing.

Returns dict: dry-run → {slave, index, dry_run:true, before, would_write, note};
    applied → {slave, index, dry_run:false, before, written, applied:true}.

Example (preview): ethercat_write_sdo(slave=0, index=0x607A, value="e8030000").

Inputs: index (required), slave (required), value (required), dry_run, +2 more.

export_dataA
Read-only

[READ][risk=low] Export collected samples from the LOCAL SQLite sink to a file.

Source is ~/.iaiops/data.db — the local queryable store written by
historian_push(sink="sqlite") — NOT a live device read. Writes csv (Excel),
sqlite (SQL browser / Power BI) or parquet (pandas/Spark; needs
pip install 'iaiops[export]'), and returns the file path + row count with a
bounded inline preview (first 200 rows max) so the response never floods.

Args:
    fmt: 'csv' | 'sqlite' | 'parquet'.
    since/until: Optional ISO-8601 time bounds (inclusive).
    endpoint: Only samples from this endpoint label.
    tag: Only samples for this tag.
    limit: Max rows exported (1..100000; default 10000).
    out_path: Output file; default ~/.iaiops/exports/iaiops-export-<ts>.<ext>.

Returns dict: {format, path, rows, preview_rows:[{ts, endpoint, protocol, tag,
    value, quality, unit}] (≤200), preview_truncated}.

Example: export_data(fmt="csv", tag="line1.temp", since="2026-07-01T00:00:00").

Inputs: fmt (required), tag, limit, since, +3 more.

fins_cpu_infoA
Read-only

[READ][risk=low] Omron CPU model/version via FINS 0501 (proves the link).

Args:
    endpoint: Endpoint name from config (protocol must be 'fins'); omit for default.

Returns dict: {endpoint, model, version}.

Example: fins_cpu_info(endpoint="line2").

Inputs: endpoint.

fins_cpu_statusA
Read-only

[READ][risk=low] Omron controller status via FINS 0601 (run/stop, mode, errors).

Args:
    endpoint: Endpoint name from config (protocol must be 'fins').

Returns dict: {endpoint, status, mode, fatal_error_data, non_fatal_error_data}.

Example: fins_cpu_status(endpoint="line2").

Inputs: endpoint.

fins_read_bitsA
Read-only

[READ][risk=low] Read bits from an Omron memory area (FINS 0101, bit codes).

Args:
    area: Bit-capable area: "CIO", "W", "H", "A", or "DM".
    address: Word address the first bit lives in, e.g. 0 for CIO 0.00.
    bit: Bit number within the word (0..15).
    endpoint: Endpoint name from config.
    count: Number of consecutive bits (1..256).

Returns dict: {endpoint, area, address, bit, count, bits:[bool,...]}.

Example: fins_read_bits(area="CIO", address=0, bit=0, count=16).

Inputs: bit, area, count, address, +1 more.

fins_read_manyA
Read-only

[READ][risk=low] Batched word reads over one FINS session (bounded).

Args:
    endpoint: Endpoint name from config.
    items: Read specs, each {"area": "DM", "address": 100, "count": 2}
        (max 20 items, count capped at 500 each).

Returns dict: {endpoint, reads:[{area, address, count, words:[int,...]}]}.

Example: fins_read_many(items=[{"area":"DM","address":100,"count":2},
    {"area":"CIO","address":0,"count":1}]).

Inputs: items, endpoint.

fins_read_wordsA
Read-only

[READ][risk=low] Read 16-bit words from an Omron memory area (FINS 0101).

Args:
    area: Memory area: "DM", "CIO", "W", "H", "A", or "EM" (current bank).
    address: Word address to start at, e.g. 100 for DM100.
    endpoint: Endpoint name from config.
    count: Number of consecutive words (1..500, capped server-side).

Returns dict: {endpoint, area, address, count, words:[int,...]} (unsigned 16-bit).

Example: fins_read_words(area="DM", address=100, count=8).

Inputs: area, count, address, endpoint.

fins_write_wordsA
Destructive

[WRITE][risk=HIGH][MOC] Write 16-bit words to an Omron area (off by default).

OT-DANGEROUS. Defaults to dry_run=True. Captures the BEFORE values (read-back
of the same range) and records an undo descriptor. Set dry_run=False AND
record an approver (OPCUA_AUDIT_APPROVED_BY) to apply.
未经授权勿对生产控制系统写入.

Args:
    area: Memory area to write: "DM", "CIO", "W", "H", "A", or "EM".
    address: Word address to start at, e.g. 100 for DM100.
    values: List of 16-bit word values to write (length 1..500).
    endpoint: Endpoint name from config.
    dry_run: When True (default) returns a preview without writing.

Returns dict: dry-run → {area, address, dry_run:true, before, would_write, note};
    applied → {area, address, dry_run:false, before, written, applied:true, _undo_id}.

Example (preview): fins_write_words(area="DM", address=100, values=[1,2,3]).

Inputs: area (required), values (required), address (required), dry_run, +1 more.

fleet_incidentsA
Read-only

[READ][risk=low] Roll up active RCA incidents across sites → fleet-wide top causes.

Aggregates the incidents each site reports into a fleet picture: how many incidents, which sites
are affected, and the most common root causes across the whole fleet. Read-only; no device I/O.

Args:
    sites: Per-site reports carrying incidents: [{site, incidents:[{cause|primary_cause,
        confidence?}]}].

Returns dict: {total_incidents, sites_with_incidents, affected_sites[], top_causes[]}.

Example: fleet_incidents(sites=[{"site":"plant-sh","incidents":[{"cause":"network"}]}]).

Inputs: sites (required).

fleet_statusA
Read-only

[READ][risk=low] Roll up per-site status reports into one fleet health view.

The tier above data_quality_fleet_rollup (per-endpoint within one site): this aggregates across
many edge SITES for central management. A site is 'offline' if its last_seen is older than
stale_after_s; fleet_status is the worst site status present. Read-only, pure; no device I/O.

Args:
    sites: Per-site reports, each
        [{site, location?, profile?, status?, score?, issues?, last_seen?}]; status ∈
        ok|degraded|critical|offline (else derived from score); score 0..1.
    stale_after_s: A site with no report newer than this is 'offline' (default 300).
    now: Optional ISO-8601 'now' for deterministic staleness (default: current UTC).

Returns dict: {site_count, fleet_status, fleet_score, by_status, worst_sites[], sites[]}.

Example: fleet_status(sites=[{"site":"sh","score":0.9},{"site":"bj","status":"critical"}]).

Inputs: sites (required), now, stale_after_s.

health_summaryA
Read-only

[DEPRECATED → opcua_health_summary][READ][risk=low] Classify OPC-UA tags.

Classifies tag node-ids against warn/alarm thresholds. Returns
ok/warn/alarm/unknown counts plus the offending tags. Thresholds
come from config tags, or per-ref overrides in ``thresholds``.

Args:
    endpoint: Endpoint name from config.
    node_ids: Tag node ids to evaluate; omit to use configured tags.
    thresholds: Optional {ref: {warn_high, alarm_high, warn_low, alarm_low}}.

Inputs: endpoint, node_ids, thresholds.

heartbeat_healthA
Read-only

[READ][risk=low] Is a heartbeat/watchdog tag still alive? (liveness check).

A heartbeat must keep CHANGING; a flatlined one means the upstream is dead even
when comms/quality look fine. With timestamped samples + max_interval_s, also
flags the longest stall.

Args:
    series: Heartbeat samples — scalars or {value, timestamp?} (a counter/toggle).
    max_interval_s: Max allowed gap between changes; exceeding it = not alive.

Returns dict: {alive (bool), samples, distinct_transitions, spread,
    longest_stall_s, reason}.

Example: heartbeat_health(series=[1,2,3,4,5], max_interval_s=10).

Inputs: series (required), max_interval_s.

historian_coverageA
Read-only

[READ][risk=low] Per-tag history coverage — what history do we actually have.

Answers the question every RCA starts with: which tags have stored history,
how many rows, and over what time span — per tag {rows, first_ts, last_ts}
from the same store historian_push writes. Read-only, bounded (tag list is
capped with a truncation flag); no device I/O.

Args:
    reader: 'sqlite' | 'tdengine' | 'iotdb'. Omit to use the per-site
        'historian:' block in ~/.iaiops/config.yaml, else the local sqlite
        store. TSDB readers need their extra: pip install iaiops[tdengine|iotdb].
    limit: Max tags returned (1..2000; default 500).

Returns dict: {reader, source, tag_count, tags:[{tag, rows, first_ts,
    last_ts}], truncated} plus the standard return envelope
    (items_returned, items_total, items_total_is_exact, is_truncated,
    truncation_note).

Example: historian_coverage().

Inputs: limit, reader.

historian_healthA
Read-only

[READ][risk=low] Bad-tag / flatline / gap detection over a provided series.

Pure analysis over an injected sample series — no live historian needed.

Args:
    series: Samples — scalars or {value, timestamp (ISO-8601), quality|good}.
    gap_threshold_s: Time gap (seconds) between consecutive samples that counts
        as a data gap (default 60).
    flatline_eps: Spread at/below which the series counts as flatline.

Returns dict: {samples, numeric_samples, bad_quality_count, flatline (bool),
    gap_count, gaps:[{after, gap_seconds}], stdev,
    verdict ('ok'|'degraded'|'gappy'|'flatline'|'bad_tag')}.

Example: historian_health(series=[{"value":10,"timestamp":"2026-06-28T10:00:00Z"}, ...]).

Inputs: series (required), flatline_eps, gap_threshold_s.

historian_pushA

[WRITE][risk=low][→historian] Push collected telemetry to a national TSDB.

Writes already-collected points to a domestic historian (信创) — TDengine or
IoTDB — instead of binding InfluxDB. Data egress to the operator's OWN database,
NOT a control-system write. Non-numeric points are skipped (numeric value column).

Args:
    points: Collected points — {ref|metric, value|present_value, timestamp?, ...}
        (e.g. the output of interrogate / integrity_poll / read_points / monitor).
    sink: 'tdengine' or 'iotdb'.
    host/port/user/password: TSDB connection params (sensible defaults per sink
        when blank/0).
    database: Target database (TDengine db / IoTDB storage group, e.g. 'root.iaiops');
        for 'sqlite' a .db file under $IAIOPS_HOME, the config directory or an
        IAIOPS_AGENT_READ_DIRS directory (empty = the iaiops store).

Returns dict: {sink, received, written, skipped_non_numeric, database}.

Example: historian_push(points=[{"ref":"line1.temp","value":21.5}], sink="tdengine",
    host="10.0.0.20", database="iaiops").

Inputs: sink (required), points (required), host, port, +3 more.

historian_queryA
Read-only

[READ][risk=low] Query a tag's historical samples from a historian.

Reads history back OUT of the store the sinks write — the local SQLite
store (~/.iaiops/data.db), TDengine, or IoTDB — so the RCA copilot / an
agent can see real pre-incident windows instead of only short live samples.
Read-only over the operator's OWN historian; no device I/O. Bounded: rows
are capped and a truncation flag is set when more history exists.

Args:
    tag: Tag/metric name as stored by historian_push (e.g. 'line1.temp').
    since/until: Optional ISO-8601 time bounds (inclusive).
    endpoint: Only samples from this endpoint label (sqlite reader only —
        the TSDB layout stores no endpoint label).
    reader: 'sqlite' | 'tdengine' | 'iotdb'. Omit to use the per-site
        'historian:' block in ~/.iaiops/config.yaml, else the local sqlite
        store. TSDB readers need their extra: pip install iaiops[tdengine|iotdb].
    limit: Max rows returned (1..10000; default 1000).

Returns dict: {reader, source, tag, since, until, rows,
    samples:[{ts, endpoint, protocol, tag, value, quality, unit}], truncated}
    plus the standard return envelope (items_returned, items_total,
    items_total_is_exact, is_truncated, truncation_note). Trust
    `is_truncated`: an empty `samples` with is_truncated=false means the
    history really is empty, NOT that the result was cut short.

Example: historian_query(tag="line1.temp", since="2026-07-02T06:00:00Z",
    until="2026-07-02T08:00:00Z").

Inputs: tag (required), limit, since, until, +2 more.

ignition_alarm_statusA
Read-only

[READ][risk=low] Active/acknowledged alarm list (normalized).

Args:
    base_url: Gateway HTTP base URL.
    flavor: Gateway API deployment dialect — 'webdev' or 'gateway'.
    secret_name: Secret-store key holding the API token (omit if none).
    verify_tls: Verify the Gateway's TLS certificate (default True). Passing False
        is refused unless the operator set IAIOPS_ALLOW_INSECURE_TLS=1.

Returns dict: {flavor, base_url, alarm_count,
    alarms:[{name, source, priority, state, label, timestamp}]}.

Example: ignition_alarm_status(base_url="https://gw:8043", flavor="webdev").

Inputs: base_url (required), flavor, verify_tls, secret_name.

ignition_gateway_statusA
Read-only

[READ][risk=low] Gateway/module health + reachability (the Gateway doctor step).

Talks to the vendor SCADA/MES platform's Gateway HTTP web API (not OPC-UA —
that stays on the opcua connector). The API token is resolved from the
encrypted secret store by key name, never passed inline. Token-egress guard:
with a secret set, base_url must point at an internal host (private IP /
single-label / .local-style name) or a host the operator allowlisted via
IAIOPS_TOKEN_EGRESS_HOSTS — public hosts are refused before any request
(prevents stored-token exfiltration).

Args:
    base_url: Gateway HTTP base URL, e.g. 'https://gw-host:8043'.
    flavor: Gateway API deployment dialect — 'webdev' or 'gateway'.
    secret_name: Secret-store key holding the API token (omit if none).
    verify_tls: Verify the Gateway's TLS certificate (default True). Passing False
        is refused unless the operator set IAIOPS_ALLOW_INSECURE_TLS=1.

Returns dict: {flavor, base_url, reachable, gateway:{name, version, state},
    module_count, modules:[{name, state, version}]}.

Example: ignition_gateway_status(base_url="https://gw:8043", flavor="webdev").

Inputs: base_url (required), flavor, verify_tls, secret_name.

ignition_tag_browseA
Read-only

[READ][risk=low] Browse the tag tree under a provider/path.

Args:
    base_url: Gateway HTTP base URL.
    provider: Tag provider name (e.g. 'default').
    path: Folder path under the provider to browse (blank = root).
    flavor: Gateway API deployment dialect — 'webdev' or 'gateway'.
    secret_name: Secret-store key holding the API token (omit if none).
    verify_tls: Verify the Gateway's TLS certificate (default True). Passing False
        is refused unless the operator set IAIOPS_ALLOW_INSECURE_TLS=1.

Returns dict: {flavor, base_url, provider, path, node_count,
    nodes:[{name, path, type, has_children}]}.

Example: ignition_tag_browse(base_url="https://gw:8043", provider="default",
    path="Line1").

Inputs: base_url (required), provider (required), path, flavor, +2 more.

ignition_tag_historyA
Read-only

[READ][risk=low] Historian query for one tag over a time window (aggregated).

Args:
    base_url: Gateway HTTP base URL.
    provider: Tag provider name (e.g. 'default').
    tag_path: Tag path whose history to query.
    start: Window start (ISO-8601 or the gateway's accepted time string).
    end: Window end (ISO-8601 or the gateway's accepted time string).
    count: Max samples to return (1..5000, capped server-side).
    flavor: Gateway API deployment dialect — 'webdev' or 'gateway'.
    secret_name: Secret-store key holding the API token (omit if none).
    verify_tls: Verify the Gateway's TLS certificate (default True). Passing False
        is refused unless the operator set IAIOPS_ALLOW_INSECURE_TLS=1.

Returns dict: {flavor, base_url, provider, tag_path, start, end,
    sample_count, samples:[{timestamp, value, quality}]}.

Example: ignition_tag_history(base_url="https://gw:8043", provider="default",
    tag_path="Line1/OvenTemp", start="2026-07-13T00:00:00Z",
    end="2026-07-13T06:00:00Z", count=200).

Inputs: end (required), start (required), base_url (required), provider (required), +5 more.

ignition_tag_readA
Read-only

[READ][risk=low] Current value(s)/quality/timestamp for tag path(s).

Args:
    base_url: Gateway HTTP base URL.
    provider: Tag provider name (e.g. 'default').
    tag_paths: Tag paths to read (from ignition_tag_browse).
    flavor: Gateway API deployment dialect — 'webdev' or 'gateway'.
    secret_name: Secret-store key holding the API token (omit if none).
    verify_tls: Verify the Gateway's TLS certificate (default True). Passing False
        is refused unless the operator set IAIOPS_ALLOW_INSECURE_TLS=1.

Returns dict: {flavor, base_url, provider, tag_count,
    tags:[{path, value, quality, timestamp}]}.

Example: ignition_tag_read(base_url="https://gw:8043", provider="default",
    tag_paths=["Line1/OvenTemp"]).

Inputs: base_url (required), provider (required), tag_paths (required), flavor, +2 more.

investigation_listA
Read-only

[READ][risk=low] List saved investigations, newest first.

Inputs: site.

investigation_openA
Read-only

[READ][risk=low] Open an investigation over one past window and walk what can be walked.

Contacts no device — the window is already past, and its evidence is whatever
was collected at the time. Each of the eight steps records its own outcome:
`done` (it ran, here is what it found), `refused` (it could not run HERE —
no samples, no alarm source; a site fact) or `not_possible` (this product
cannot do it at all).

The investigation is persisted, so it can be re-read and advanced later.

Inputs: end (required), start (required), endpoint (required), site, +1 more.

investigation_readinessA
Read-only

[READ][risk=low] How far into an investigation this site could get, and what each gap needs.

`readiness` answers "which scenarios can this site run"; this answers the
next question down — if something stopped tomorrow, how many of the eight
evidence steps could actually be walked, and for each one that could not,
what is missing.

Contacts nothing: no device, no network, no historian. It is derived from
the config and the local store, which is what makes it usable on a site
nobody has been authorised to probe yet.

Each gap says whether it is *unmet* (you have not supplied it — the fix names
the command) or *not yet expressible* (this product offers no way to supply
it at all). Those two send a person to very different places.

Inputs: site.

investigation_showA
Read-only

[READ][risk=low] Re-read a saved investigation — the state it was left in.

Inputs: investigation_id (required).

learn_cause_weightsA
Read-only

[READ][risk=low] Learn a per-site RCA {cause: weight} profile from history.

Derives a per-site cause-weight profile from a corpus of CONFIRMED past
incidents so downtime_root_cause adapts to what THIS site's evidence actually
predicts. Pure + explainable: each weight is the smoothed signal→cause
precision relative to chance (>1 = evidence for that cause is reliable here,
<1 = often misleading) — no black box. Anti-overfit: Laplace smoothing + a
per-cause min-sample guard, and a fall-back to the shipped defaults when the
corpus is too thin. Feed the returned 'cause_weights' to downtime_root_cause's
cause_weights argument. Advisory: it tunes ranking, never executes anything.

Args:
    history: Confirmed incidents — [{cause, signals:[...]}] where 'cause' is the
        known root cause and 'signals' are the cause labels the evidence pointed
        at (both from the copilot taxonomy: mechanical_fault, comms_loss,
        sensor_fault, material_starvation, quality_reject, changeover, utility_fault).
    min_samples: Minimum confirmed incidents before adapting at all (default 8);
        below it the defaults are kept.
    smoothing: Laplace pseudo-count pulling each estimate toward chance (default 1.0).

Returns dict: {cause_weights:{cause: multiplier}, n_incidents, per_cause:{cause:
    {support, hits, precision, weight, note}}, rationale}.

Example: learn_cause_weights(history=[{"cause":"mechanical_fault",
    "signals":["mechanical_fault"]}, {"cause":"comms_loss","signals":["comms_loss"]}]).

Inputs: history (required), smoothing, min_samples.

line_relation_declareB
Read-only

[READ][risk=low] Record that one asset feeds another — the second RCA axis.

`[READ]` follows this repo's convention, where the tag is about PLANT state:
it touches no device, exactly like `baseline_record_change` and
`adopt_alias_map`, which are the same shape. It does write — a declaration
about the line, into the site knowledge base.

With time alone, an upstream stoppage produces a string of equally-confident
downstream false causes, because on a line downstream co-occurrence is
guaranteed whatever the cause. That guarantee is exactly why this is a
declaration and not something inferred (D25): a person stating the line
order needs no inference at all.

``by`` is required — a person is the evidence, and an edge with no author is
indistinguishable from a guess a year later. Self-loops and cycles are
refused here, where somebody can still fix them.

Inputs: by (required), upstream (required), downstream (required), site.

line_relations_listB
Read-only

[READ][risk=low] The declared line order for a site, and what each asset feeds.

Inputs: site.

mc_cpu_statusA
Read-only

[READ][risk=low] MELSEC CPU type/code (proves the MC link is alive).

Args:
    endpoint: Endpoint name from config (protocol must be 'mc'); omit for default.

Returns dict: {endpoint, plctype, cpu_type, cpu_code}.

Example: mc_cpu_status(endpoint="cell3").

Inputs: endpoint.

mc_read_bitsA
Read-only

[READ][risk=low] Batch-read bit devices from a head device.

Args:
    headdevice: MELSEC bit device, e.g. "M0", "X10", "Y20", "B0".
    endpoint: Endpoint name from config.
    count: Number of consecutive bits (1..256).

Returns dict: {endpoint, headdevice, count, bits:[bool,...]}.

Example: mc_read_bits(headdevice="M0", count=16).

Inputs: headdevice (required), count, endpoint.

mc_read_manyA
Read-only

[READ][risk=low] Random-read scattered word + dword devices in one request.

Args:
    endpoint: Endpoint name from config.
    word_devices: Word device names, e.g. ["D100", "D200", "M0"].
    dword_devices: Double-word device names, e.g. ["D300", "D400"].

Returns dict: {endpoint, words:[{device, value}], dwords:[{device, value}]}.

Example: mc_read_many(word_devices=["D100","D101"], dword_devices=["D200"]).

Inputs: endpoint, word_devices, dword_devices.

mc_read_wordsA
Read-only

[READ][risk=low] Batch-read 16-bit word devices from a head device.

Args:
    headdevice: MELSEC word device, e.g. "D100", "W10", "R0".
    endpoint: Endpoint name from config.
    count: Number of consecutive words (1..256, capped server-side).

Returns dict: {endpoint, headdevice, count, words:[int,...]} (signed 16-bit).

Example: mc_read_words(headdevice="D100", count=8).

Inputs: headdevice (required), count, endpoint.

mc_write_wordsA
Destructive

[WRITE][risk=HIGH][MOC] Write 16-bit words from a head device (off by default).

OT-DANGEROUS. Defaults to dry_run=True. Captures the BEFORE values (read-back
of the same range) and records an undo descriptor. Set dry_run=False AND
record an approver (OPCUA_AUDIT_APPROVED_BY) to apply.
未经授权勿对生产控制系统写入.

Args:
    headdevice: MELSEC word device to start at, e.g. "D100".
    values: List of 16-bit word values to write (length 1..256).
    endpoint: Endpoint name from config.
    dry_run: When True (default) returns a preview without writing.

Returns dict: dry-run → {headdevice, dry_run:true, before, would_write, note};
    applied → {headdevice, dry_run:false, before, written, applied:true, _undo_id}.

Example (preview): mc_write_words(headdevice="D100", values=[1,2,3]).

Inputs: values (required), headdevice (required), dry_run, endpoint.

mechanism_library_checkA
Read-only

[READ][risk=low] What a mounted fault-mechanism library says about one candidate cause.

Three answers, and the difference between the first two is the whole point:

* ``nothing_known`` — the library has never heard of this cause. **Not** "no
  objection": a knowledge base that knows nothing about something has not
  cleared it.
* ``known``, not excluded — mechanisms for it apply here, with what would
  confirm each.
* ``known``, excluded — every mechanism for it is inapplicable to this
  equipment, so the candidate can be ruled out. That is the strong move a
  ranker cannot make.

It never confirms. Raising a candidate to `confirmed` comes from outside the
ranking — a measurement, a reproduction, or a person (D29).

Inputs: cause (required), site, protocol.

mechanism_library_listC
Read-only

[READ][risk=low] The fault mechanisms mounted for a site, and where each came from.

Inputs: site.

modbus_apply_templateA
Read-only

[READ][risk=low] Read a register block and decode it into named tags via a template.

Args:
    template: Template name (see modbus_list_templates).
    endpoint: Endpoint name from config.
    address: Absolute address of the first register read (aligns to offsets).
    count: Registers to read; omit to use the template's span.

Inputs: template (required), count, address, endpoint.

modbus_detect_byte_orderA
Read-only

[READ][risk=low] Auto-detect the word/byte order of a raw Modbus register block.

Pure decode logic (no device): decodes the raw registers under every candidate
order for the numeric type and scores them against a known/expected value
and/or a plausible range. Solves the "right registers, wrong endianness" pain.

Args:
    registers: Raw 16-bit register values (e.g. from modbus_read_holding).
    value_type: uint16|int16|uint32|int32|float32.
    hint: A known/expected sample value to match against.
    value_min: Lower bound of a plausible value band.
    value_max: Upper bound of a plausible value band.

Inputs: registers (required), hint, value_max, value_min, +1 more.

modbus_health_summaryA
Read-only

[READ][risk=low] Classify Modbus registers against warn/alarm thresholds.

Mirrors the OPC-UA health_summary classifier. Returns ok/warn/alarm/unknown
counts plus offenders; ``overall`` is ``unknown`` when nothing is in
warn/alarm and any point could not be classified (``ok`` means every point
was observed in band), and ``coverage`` (complete|partial|none) says how many
points were judged at all — an alarm with ``coverage: partial`` is not the
only problem. Configured tags may be typed points (``ir:0:float32:CDAB``) or
profile channels (``ch:<name>``, decoded through the endpoint's
sensor_profile), which carry their own table and type — register_type/decode
apply only to bare addresses.

Args:
    endpoint: Endpoint name from config.
    addresses: Register addresses to evaluate; omit to use configured tags.
    thresholds: Optional {address_str: {warn_high, alarm_high, ...}}.
    register_type: holding|input.
    decode: uint16|int16 — how to interpret each register before
        threshold comparison (int16 for bipolar/signed tags).

Inputs: decode, endpoint, addresses, thresholds, +1 more.

modbus_list_templatesA
Read-only

[READ][risk=low] List built-in vendor register-map templates (name / type / tags).

Inputs: no named parameters.

modbus_read_coilsA
Read-only

[READ][risk=low] Read coils (FC01) — digital outputs, read-only here.

Args:
    address: Starting coil address.
    endpoint: Endpoint name from config.
    count: Number of coils.

Inputs: address (required), count, endpoint.

modbus_read_discreteA
Read-only

[READ][risk=low] Read discrete inputs (FC02) — read-only digital inputs.

Args:
    address: Starting discrete-input address.
    endpoint: Endpoint name from config.
    count: Number of inputs.

Inputs: address (required), count, endpoint.

modbus_read_holdingA
Read-only

[READ][risk=low] Read holding registers (FC03) with a decode hint.

Args:
    address: Starting register address.
    endpoint: Endpoint name from config.
    count: Number of registers (capped server-side).
    decode: raw|uint16|int16|uint32|int32|float32.

Inputs: address (required), count, decode, endpoint.

modbus_read_inputA
Read-only

[READ][risk=low] Read input registers (FC04) with a decode hint.

Args:
    address: Starting register address.
    endpoint: Endpoint name from config.
    count: Number of registers (capped server-side).
    decode: raw|uint16|int16|uint32|int32|float32.

Inputs: address (required), count, decode, endpoint.

monitor_changesA
Read-only

[READ][risk=low] Capture only the value CHANGES of a point over a bounded window.

Polls ``ref`` and returns only the changes (with timestamps), not every
sample — the OT deadband-report pattern. Works across OPC-UA / Modbus / S7 /
Mitsubishi MC / EtherNet/IP. Hard-capped by duration_s and max_changes (never
an infinite loop).

Args:
    ref: Point to watch — OPC-UA node id, Modbus address, S7 address string,
        MELSEC device, or Logix tag (per the endpoint's protocol).
    endpoint: Endpoint name from config.
    duration_s: Wall-clock window in seconds (1..120, capped server-side).
    interval_ms: Poll interval in milliseconds (>=50).
    deadband: Numeric change must exceed this to count (0 = any change).
    max_changes: Stop after this many changes (1..500, capped server-side).

Returns dict: {endpoint, ref, duration_s, interval_ms, deadband, samples_polled,
    change_count, changes:[{value, previous, source_timestamp, wall_clock}]}.

Example: monitor_changes(ref="ns=2;i=5", endpoint="line1", duration_s=20, deadband=0.5).

Inputs: ref (required), deadband, endpoint, duration_s, +2 more.

mqtt_publishA
Destructive

[WRITE][risk=HIGH][MOC] Publish/command to an MQTT topic (off by default).

OT-DANGEROUS. A command (e.g. Sparkplug NCMD/DCMD) can change a live control
system. Defaults to dry_run=True. Set dry_run=False AND record an approver
(OPCUA_AUDIT_APPROVED_BY) to send. 未经授权勿对生产控制系统下发指令.

Reversibility depends on retain: a transient (retain=False) command has NO
inverse — delivered is delivered. A RETAINED publish overwrites durable broker
state, so the prior retained payload is captured first (returned as `before`)
and an undo descriptor recorded, as the protocol write tools do.

Args:
    topic: MQTT topic to publish to.
    payload: Message payload (string; JSON is fine).
    endpoint: Endpoint name from config.
    qos: MQTT QoS 0..2.
    retain: Set the broker retain flag.
    dry_run: When True (default) returns a preview without publishing.

Returns dict: dry-run → {topic, dry_run:true, would_publish_bytes, note};
    applied → {topic, dry_run:false, published_bytes, applied:true}, plus
    before:{found, payload, binary} when retain=True (the captured prior
    retained payload; _undo_id is added when an inverse was recorded).

Example (preview): mqtt_publish(topic="factory/line1/cmd", payload='{"setpoint":50}').

Inputs: topic (required), payload (required), qos, retain, +2 more.

mqtt_read_topicA
Read-only

[READ][risk=low] Plain MQTT: collect a BOUNDED set of messages from a topic.

Subscribes, gathers up to ``count`` messages or until ``timeout_s``, then
disconnects — never an open-ended loop. Payloads are decoded as JSON/text;
binary (e.g. Sparkplug protobuf) is reported with a hex preview + hint.

Args:
    endpoint: Endpoint name from config (protocol must be 'mqtt').
    topic: Topic filter (default: the endpoint's configured topic or '#').
    count: Max messages (1..500, capped server-side).
    timeout_s: Max seconds to wait (1..60, capped server-side).

Returns dict: {endpoint, topic, message_count, messages:[{topic,
    payload:{encoding, json|text|hex_preview}}]}.

Example: mqtt_read_topic(topic="factory/+/temperature", count=10, timeout_s=5).

Inputs: count, topic, endpoint, timeout_s.

mtconnect_assetsB
Read-only

[READ][risk=low] Assets the agent knows (cutting tools, fixtures, programs).

Args:
    endpoint: Endpoint name from config.

Returns dict: {endpoint, asset_count, assets:[{asset_type, asset_id, timestamp}]}.

Example: mtconnect_assets(endpoint="vmc1").

Inputs: endpoint.

mtconnect_currentA
Read-only

[READ][risk=low] Latest value of every data item (a snapshot of the machine now).

Args:
    endpoint: Endpoint name from config.

Returns dict: {endpoint, observation_count, next_sequence,
    observations:[{data_item_id, type, name, timestamp, sequence, value}]}.
    Pass next_sequence as from_sequence to mtconnect_sample to stream from 'now'.

Example: mtconnect_current(endpoint="vmc1").

Inputs: endpoint.

mtconnect_oee_snapshotA
Read-only

[READ][risk=low] Availability / Execution / mode / program (OEE inputs).

Surfaces the live data items an availability/performance calc needs. Does NOT
compute a single OEE % (needs planned-time + ideal-cycle context MTConnect
doesn't expose).

Args:
    endpoint: Endpoint name from config.

Returns dict: {endpoint, availability, execution, controller_mode, program,
    available (bool), running (bool), verdict ('running'|'available_idle'|'down')}.

Example: mtconnect_oee_snapshot(endpoint="vmc1").

Inputs: endpoint.

mtconnect_probeA
Read-only

[READ][risk=low] The device model: devices → components → data items.

The MTConnect 'schema' — what the machine can report. Call this first to
discover dataItem ids/types before reading values.

Args:
    endpoint: Endpoint name from config (protocol must be 'mtconnect').

Returns dict: {endpoint, device_count, devices:[{name, uuid, component_count,
    components:[{component, id, name, data_items:[{id, type, category, name, units}]}]}]}.

Example: mtconnect_probe(endpoint="vmc1").

Inputs: endpoint.

mtconnect_sampleA
Read-only

[READ][risk=low] Recent observations — a bounded snapshot OR a bounded incremental long-poll stream. Both modes are read-only and can NEVER run unbounded.

Modes:
  - snapshot (default): one /sample page of up to `count` observations. Pass
    `from_sequence` for a single incremental page starting at that sequence.
  - stream: set `max_samples` and/or `duration_s` to poll the agent
    repeatedly, advancing by the header's nextSequence each round, until a
    bound is hit. Feed the returned `next_sequence` back as `from_sequence`
    to resume exactly where you stopped.

Args:
    endpoint: Endpoint name from config.
    count: Max observations per /sample page (1..500, capped server-side).
    from_sequence: Start sequence for an incremental pull (use next_sequence
        from mtconnect_current or a prior call). None = the most recent `count`.
    interval_ms: Poll spacing between rounds in stream mode (0..10000; 0 =
        back-to-back). Client-side spacing — NOT the agent's server-push interval.
    max_samples: Total observation budget across rounds; >0 selects stream mode
        (capped at 2000). 0 = snapshot.
    duration_s: Wall-clock budget in seconds; >0 selects stream mode (capped 120).

Returns dict (snapshot): {endpoint, mode:'snapshot', requested_count,
    from_sequence, next_sequence, first_sequence, last_sequence,
    observation_count, observations:[{data_item_id, type, name, timestamp,
    sequence, value}]}.
Returns dict (stream): {endpoint, mode:'stream', from_sequence, next_sequence,
    observation_count, poll_count, stopped_reason, interval_ms, max_samples,
    observations:[...]}.

Example (snapshot): mtconnect_sample(endpoint="vmc1", count=200).
Example (stream):   mtconnect_sample(endpoint="vmc1", from_sequence=1500,
    interval_ms=1000, max_samples=500, duration_s=30).

Inputs: count, endpoint, duration_s, interval_ms, +2 more.

oee_computeA
Read-only

[READ][risk=low] OEE = Availability × Performance × Quality (+ loss/energy depth).

Args:
    planned_time_s: Planned production time (seconds).
    run_time_s: Actual running time (seconds) — planned minus downtime.
    ideal_cycle_time_s: Ideal/nameplate cycle time per part (seconds).
    total_count: Total parts produced.
    good_count: Good (non-reject) parts produced.
    breakdown_time_s: Optional — unplanned-stop seconds (splits availability loss).
    setup_time_s: Optional — changeover/setup seconds (splits availability loss).
    minor_stop_time_s: Optional — minor-stop seconds (splits performance loss;
        the remainder is speed loss).
    startup_reject_count: Optional — startup/warm-up rejects (splits quality
        loss; the remainder is production rejects).
    actual_kwh: Optional — measured energy for this run; enables the energy block.
    baseline_kwh: Optional — expected/baseline energy for the actual-vs-baseline
        deviation verdict.
    emission_factor_kg_per_kwh: Optional — carbon factor (kg CO2e/kWh). Default is
        a flagged placeholder (see the tool's carbon note); pass the grid's value.
    energy_tolerance: ± band (fraction) for the over/under/on-target verdict.

Returns dict: OEE factors + oee/oee_pct + inputs + losses, plus
    ``six_big_losses`` (breakdown/setup/minor-stops/speed/startup/production-reject
    time-ladder that sums with OEE to 100%) and, when ``actual_kwh`` is given,
    ``energy`` (kwh_per_unit, carbon, and baseline deviation).

Example: oee_compute(planned_time_s=28800, run_time_s=25200,
    ideal_cycle_time_s=2.0, total_count=12000, good_count=11800,
    setup_time_s=1800, actual_kwh=940, baseline_kwh=880).

Inputs: good_count (required), run_time_s (required), total_count (required), planned_time_s (required), +9 more.

oee_multidimA
Read-only

[READ][risk=low] Aggregate OEE (+ optional energy) across dimensions.

Args:
    records: Labelled records — {<dimension labels>, planned_time_s, run_time_s,
        ideal_cycle_time_s, total_count, good_count} plus optional actual_kwh /
        baseline_kwh to enable the energy rollup.
    dimensions: Dimension keys to group by (default ['machine','part','shift']);
        use ['shift'] for the classic by-shift energy comparison.
    emission_factor_kg_per_kwh: Optional carbon factor (kg CO2e/kWh); default is a
        flagged placeholder — pass the grid's published value.
    energy_tolerance: ± band (fraction) for the actual-vs-baseline verdict.

Returns dict: {dimensions, group_count, mean_oee, worst_performers:[...],
    matrix:[{dimensions, oee, oee_pct, availability, performance, quality,
    energy?}]}. When any record carries energy, adds an ``energy_baseline`` block
    that flags cross-group deviation anomalies (tolerance + robust-outlier rules).

Example: oee_multidim(records=[{"shift":"day","planned_time_s":28800,
    "run_time_s":25000,"ideal_cycle_time_s":2,"total_count":12000,
    "good_count":11800,"actual_kwh":940,"baseline_kwh":880}], dimensions=["shift"]).

Inputs: records (required), dimensions, energy_tolerance, emission_factor_kg_per_kwh.

onboarding_config_draftA
Read-only

[READ][risk=low] The config.yaml endpoints a stored scan can justify.

Closes the gap where a site scanned forty devices and then retyped all forty
by hand. Reads a stored scan; writes nothing. `config.yaml` is edited by a
person, exactly as with `iaiops tags apply`.

**Every drafted field says whether the scan established it.** A field with
`value: null` was NOT established, and its `caution` says what it is waiting
for — do not fill one in and do not drop it. Dropping it lets the protocol
default apply in silence, which is how a Modbus gateway gets read at unit 1
and shows a confident number for the wrong machine. Carry the cautions to
whoever merges this; they are the content, not decoration.

**Only CONFIRMED protocols become endpoints.** An open port means something
is listening, not that it speaks the protocol; those hosts appear under
`skipped` with the reason. `limits` states what this draft structurally
cannot contain — a protocol's absence here is not evidence of its absence at
the site.

`tags` is always empty and this tool will not fill it. A scan finds devices;
which point means run state or good count is process knowledge, and a wrong
production counter yields a plausible OEE, which is worse than an error
(D16). That confirmation is a person's, via `iaiops tags export` / `apply`.

`scan_id` empty means the newest stored scan. `db` overrides the store
(.db/.sqlite, under $IAIOPS_HOME, the config dir or an IAIOPS_AGENT_READ_DIRS dir).

Inputs: db, scan_id.

onboarding_statusA
Read-only

[READ][risk=low] Where this site is on the path from a network to an answer.

One altitude below `site_readiness`. That one lists every scenario and what
each is waiting for; this one answers the smaller, earlier question a caller
actually has first — **which journey this site is on, and which single command
comes next** on it. There are two, with different first steps:

    devices — no UNS yet: scan → endpoints → point list → what each point
              MEANS → collect → ask the question
    uns     — data already in an MQTT/UNS broker: connect → audit the
              namespace → choose points → MEANS → collect → ask

`track` is `auto` (derived from config.yaml), `devices` or `uns`. On `uns` a
stored namespace audit forks it into B1 (audited clean) and B2 (governance is
the work); until an audit is stored the result says B1/B2 is unknown rather
than assuming either. When nothing is configured, or both kinds of endpoint
are, the single step is a question with two `choices` — relay both to the
caller and pick neither; the files on disk cannot say which kind of site this
is, and neither can you.

Derived from the local store and `config.yaml` every time; there is no
onboarding state file, so a site that edits config.yaml by hand or restores a
backup still gets a true answer rather than a remembered one.

Every step carries its own `command`, including the ones still waiting. Show
the caller the one under `next_command`; the rest are context, not a to-do
list, and handing someone five commands is the same as handing them none.

A step that is genuinely done stays `done` even when it sits behind the
cursor — a site that hand-wrote config.yaml before ever scanning has real
endpoints, and reporting otherwise to keep the sequence tidy would be a lie
in the direction that makes this tool look more necessary.

Contacts nothing. `db` overrides the local store path (.db/.sqlite, under
$IAIOPS_HOME, the config dir or an IAIOPS_AGENT_READ_DIRS dir); empty means the
iaiops store.

Inputs: db, track.

opcua_alarm_eventsA
Read-only

[READ][risk=low] Timestamped Alarms & Conditions via a bounded event subscription.

Subscribes to the Server object for Condition-type events, optionally calls
ConditionRefresh so currently-retained conditions are re-announced WITH their
original event Time, listens for at most duration_s seconds, unsubscribes.
The timed complement to opcua_read_alarms: each event carries the server's own
timestamp, so RCA can time-localize alarm evidence. Requires a server that
implements A&C event subscriptions (待核实 per server); an empty result can mean
no events in the window OR no A&C support — pair with opcua_read_alarms.

Args:
    endpoint: Endpoint name from config.
    duration_s: Listen window in seconds (0..60, default 5).
    refresh: Call ConditionRefresh to replay retained/active conditions (default true).
    max_events: Stop after this many events (1..200).

Returns dict: {endpoint, duration_s, condition_refresh, refresh_error, event_count,
    events:[{source, message, severity, state (ACTIVE|RTN|EVENT), timestamp}], note}.

Example: opcua_alarm_events(endpoint="line1", duration_s=5).

Inputs: refresh, endpoint, duration_s, max_events.

opcua_anomaly_scanA
Read-only

[READ][risk=low] Sample a node over a bounded window and flag statistical outliers.

Computes mean/stddev/min/max and flags samples outside mean ± sigma*stddev.
Simple statistics only — no ML, no persisted model.

Args:
    node_id: The OPC-UA node id to scan.
    endpoint: Endpoint name from config.
    samples: Max samples (capped server-side).
    interval_ms: Delay between samples in milliseconds.
    sigma: Outlier band width in standard deviations.

Inputs: node_id (required), sigma, samples, endpoint, +1 more.

opcua_browseA
Read-only

[READ][risk=low] Browse the OPC-UA node tree from a node id (bounded depth).

Args:
    node_id: Root node id (default i=85, the Objects folder).
    endpoint: Endpoint name from config.
    depth: Bounded browse depth (capped server-side).

Inputs: depth, node_id, endpoint.

opcua_diagnose_connectionA
Read-only

[READ][risk=low] Diagnose why an OPC-UA endpoint won't connect — a classified verdict.

Attempts a connect (no writes, disconnects immediately) and classifies any
failure into the well-known OPC-UA buckets instead of returning a raw error,
each with a concrete next step:
certificate (server doesn't trust our client cert) · auth (user/password) ·
security_policy (policy/mode mismatch) · port_closed · dns · firewall_timeout ·
unreachable · config (bad endpoint_url / connector not installed) · ok.

Args:
    endpoint: Endpoint name from config; omit to use the default endpoint.

Returns dict: {endpoint, reachable (bool), class, diagnosis, remediation, detail}.

Inputs: endpoint.

opcua_discover_tagsA
Read-only

[READ][risk=low] Auto-discover OPC-UA tags and build a semantic asset model.

Walks the address space, collects every Variable node, and enriches each with
datatype / value / engineering-unit / a heuristic semantic class (temperature,
pressure, flow, setpoint, alarm, state, …) and a suggested clean alias. Tags
are grouped into assets by their browse path, and a naming-quality report
flags alias collisions + cryptic names. Aliases are ADVISORY — nothing is
written back to the server (a server-side rename would be OT-dangerous).

Args:
    endpoint: Endpoint name from config; omit to use the default endpoint.
    root: Root node id to discover from (default i=85, the Objects folder).
    max_depth: Bounded recursion depth (capped server-side at 8).
    include_standard: Include OPC-UA namespace-0 server infrastructure
        (default False — only real process tags in vendor namespaces).

Returns dict: {endpoint, root, tag_count, asset_count,
    assets:[{asset, tag_count, classes, tags:[{node_id, browse_name,
    browse_path, datatype, value, unit, writable, class, suggested_alias}]}],
    naming_quality:{alias_collisions, cryptic_names, verdict},
    companion_specs:{suggestions:[{node_id, browse_path, spec, type, role,
    running_when, why, caveats}], recognised_without_role, is_truncated}}.
    companion_specs are what the device DECLARES through OPC UA companion
    specs (Machinery; PackML recognised only), matched by type definition — SUGGESTIONS a
    person confirms with `iaiops tags apply`. Never write them into config
    as declared roles yourself (D16).

Inputs: root, endpoint, max_depth, include_standard.

opcua_health_summaryA
Read-only

[READ][risk=low] Classify OPC-UA tag node-ids against warn/alarm thresholds.

Returns ok/warn/alarm/unknown counts plus the offending tags; ``overall``
is never ``ok`` while any tag could not be judged, and ``coverage``
(complete|partial|none) says how many were. Thresholds come from config
tags, or per-ref overrides in ``thresholds``.

Args:
    endpoint: Endpoint name from config.
    node_ids: Tag node ids to evaluate; omit to use configured tags.
    thresholds: Optional {ref: {warn_high, alarm_high, warn_low, alarm_low}}.

Inputs: endpoint, node_ids, thresholds.

opcua_read_alarmsA
Read-only

[READ][risk=low] Best-effort surfacing of active alarm/condition booleans (untimed).

Browses the address space (bounded) for alarm-like boolean nodes reading
True. Untimed by nature — for servers with A&C event support use
opcua_alarm_events, which returns conditions WITH the server's timestamps.

Args:
    endpoint: Endpoint name from config.
    node_id: Root node id to scan from (default i=85).
    depth: Bounded scan depth.

Inputs: depth, node_id, endpoint.

opcua_read_historyA
Read-only

[READ][risk=low] OPC-UA Historical Access (HDA): raw historical values over a window.

Reads stored history for a node via the server's HistoryRead service, bounded
by ``max_points``. Returns a clear 'unsupported' note when the server does not
historize the node (no crash).

Args:
    node_id: The OPC-UA node id to read history for (e.g. ns=2;i=5).
    endpoint: Endpoint name from config.
    start: ISO-8601 window start (default: 1 hour before end).
    end: ISO-8601 window end (default: now).
    max_points: Max points to return (capped server-side at 2000).

Returns dict: {node_id, supported (bool), start, end, count,
    values:[{value, source_timestamp, status_code}]}.

Example: opcua_read_history(node_id="ns=2;i=5", start="2026-06-28T08:00:00Z").

Inputs: node_id (required), end, start, endpoint, +1 more.

opcua_read_manyA
Read-only

[READ][risk=low] Batch-read multiple node ids in one session (bounded count).

Args:
    node_ids: List of OPC-UA node ids to read.
    endpoint: Endpoint name from config.

Inputs: node_ids (required), endpoint.

opcua_read_nodeA
Read-only

[READ][risk=low] Read one node: value, datatype, source timestamp, status code.

Args:
    node_id: The OPC-UA node id to read (e.g. ns=2;i=5).
    endpoint: Endpoint name from config.

Inputs: node_id (required), endpoint.

opcua_server_infoA
Read-only

[READ][risk=low] OPC-UA server status, build info, and namespace array.

Args:
    endpoint: Endpoint name from config; omit to use the default endpoint.

Inputs: endpoint.

opcua_subscribe_sampleA
Read-only

[READ][risk=low] Sample a node a BOUNDED number of times, then return (never loops).

Args:
    node_id: The OPC-UA node id to sample.
    endpoint: Endpoint name from config.
    samples: Max number of readings (capped server-side).
    interval_ms: Delay between readings in milliseconds.
    timeout_s: Hard wall-clock cap in seconds (capped server-side).

Inputs: node_id (required), samples, endpoint, timeout_s, +1 more.

pdm_forecastA
Read-only

[READ][risk=low] Forecast a value's trend + time until it crosses a warn/alarm limit.

The predictive step above baseline_check (which flags a violation that already happened): fits a
robust Theil-Sen trend to the recent history and, if it continues, estimates the ETA to the
nearest limit in the direction of travel — the early warning that makes maintenance predictive
(inverter/turbine degradation, bearing drift, filter clogging). Refuses thin history; read-only,
pure over the provided series; no device I/O.

Beyond the trend, the result deepens into three explainable, stdlib-only views: a degradation
'pattern' (gradual vs sudden vs cyclic), a remaining-useful-life 'rul' block when degrading
(linear + exponential extrapolation to the limit, a confidence band from the slope spread, and a
fit R^2), and optional time-domain 'waveform' features (RMS/kurtosis/crest/... for
vibration-type signals). Each states its own uncertainty rather than guessing.

Args:
    series: Time-ordered samples: [{value, timestamp?}] (timestamp ISO-8601; if all present the
        ETA is in seconds, otherwise in samples). >= 30 numeric samples required.
    warn_high/alarm_high/warn_low/alarm_low: Optional limits; the forecast targets the nearest
        one in the trend's direction (rising → highs, falling → lows).
    imminent_within_s: ETA (seconds) at/under which status is 'imminent' (default 86400 = 24h).
    include_waveform: Add the time-domain 'waveform' feature block (default True). Set False for
        slow trend-only signals where vibration features do not apply.

Returns dict: {status (insufficient_data|stable|degrading|imminent), samples, direction,
    slope_per_unit, unit (s|samples), current, limit:{name,value}, eta_to_limit,
    degradation:{pattern,confidence,rationale,metrics},
    waveform:{rms,crest_factor,kurtosis,...} (when include_waveform),
    rul:{linear,exponential,eta_band,recommended_model,confidence,...} (when degrading)}.

Example: pdm_forecast(series=[{"value": 62.1, "timestamp": "2026-07-12T00:00:00Z"}, ...],
    warn_high=75, alarm_high=85).

Inputs: series (required), warn_low, alarm_low, warn_high, +3 more.

plc_program_driftA
Read-only

[READ][risk=low] Has this program changed since its approved snapshot, and what moved?

Three verdicts, and the wording of each is load-bearing. **identical** means
the same SHA-256 and nothing else earns the word. **logic_changed** means the
extracted structure differs — reported per block, naming which categories
(variables / calls / branches / timers_counters) moved. **changed_outside_
extracted_structure** means the bytes differ while every block fingerprint
matched: usually comments or formatting, but these parsers extract structure
rather than parse a grammar, so a real change inside a construct they do not
model looks identical from here. Calling that "documentation only" would be
the comfortable reading of evidence that does not support it, so it is not
called that, and it is not a clearance — line and comment counts are reported
beside it so a reviewer can see which way it leans.

Nothing here decides whether a change was authorised; that is change control's
job. No device is touched — this reads a file a person exported.

Args:
    path: The current exported program file to check (same roots as above).
    name: Tracked program name (defaults to the file's stem).
    against: Snapshot id to compare with; default is the latest.

Returns dict: {program, name_source, baseline:{snapshot_id, taken_at, label,
    source_file}, current:{source_file}, verdict, content_changed,
    structure_changed, content_sha256:{before, after}, blocks:{added[],
    removed[], changed:[{block, kind, line, previous_line, changed[]}],
    unchanged}, totals:{block_count, line_count, comment_count}, parse_errors,
    note, advisory}.

Example: plc_program_drift(path="~/.iaiops/plc/Line3_today.scl", name="Line3").

Inputs: path (required), name, against.

plc_program_historyA
Read-only

[READ][risk=low] Tracked programs, or one program's snapshot history.

Local read of the program-baseline store — no file is parsed and no device is
touched. Nothing is ever pruned automatically: a change-control history that
quietly drops last quarter's baseline is worse than one that grows, and a
stored row is block names, hashes and counts rather than source. Removing history is a
deliberate act and is CLI-only (`iaiops program forget`) — deleting
change-control evidence should not be one tool call away.

Args:
    name: Tracked program name. Omit for the list of every tracked program.

Returns dict (listing): {store, program_count, programs:[{program,
    snapshot_count, latest, latest_taken_at}]}; (one program): {store,
    program, snapshot_count, snapshots:[{snapshot_id, taken_at, source_file,
    content_sha256, label, note}]}.

Example: plc_program_history(name="Line3").

Inputs: name.

plc_program_outlineA
Read-only

[READ][risk=low] Structural outline of an EXPORTED PLC program file.

Parses one exported text file (Siemens SCL/ST .scl/.st, AWL/STL .awl,
Rockwell Studio 5000 .L5X — .txt is content-sniffed) and returns blocks
(FB/FC/OB/DB/routines/AOIs) with VAR sections, IF/CASE branch inventory,
timers/counters, and the call graph. Never uploads from a live PLC; reads
exactly the named file (≤5 MB). Every element cites source_file + line
(rung number for L5X ladder) — quote those citations when explaining.
Malformed sections degrade to entries in parse_errors, never a crash.

Args:
    path: Exported program file (.st/.scl/.awl/.l5x/.txt; must exist, ≤5 MB),
        under $IAIOPS_HOME, the config dir or an IAIOPS_AGENT_READ_DIRS dir.

Returns dict: {source_file, format, stats:{blocks, variables, call_edges,
    branches, timers_counters, comments, lines, parse_errors},
    blocks:[{name, kind, language, line, end_line, variables (≤100,
    variables_truncated), calls, branches, timers_counters, networks,
    comment}] (≤50, blocks_truncated), call_graph:[{caller, callee,
    source_file, line}], parse_errors, citation_note}.

Example: plc_program_outline(path="~/.iaiops/plc/Line3_Conveyor.scl").

Inputs: path (required).

plc_program_sectionA
Read-only

[READ][risk=low] Source text of ONE named block from an exported program.

Returns the exact source of a single block (FB/FC/OB/DB name for SCL/AWL;
Program.Routine or routine name for L5X — rungs are rendered as
'[rung N] ...'), capped at 200 lines with an explicit truncated flag, so
the agent reads exactly the section it is explaining instead of guessing.
Unknown block names fail with the list of available blocks.

Args:
    path: Exported program file (.st/.scl/.awl/.l5x/.txt; must exist, ≤5 MB),
        under $IAIOPS_HOME, the config dir or an IAIOPS_AGENT_READ_DIRS dir.
    block: Block/routine name (case-insensitive; quotes optional).

Returns dict: {source_file, format, block, kind, start_line, end_line,
    lines_returned, truncated, source, parse_errors}.

Example: plc_program_section(path="~/.iaiops/plc/Line3.scl", block="FB_Conveyor").

Inputs: path (required), block (required).

plc_program_snapshotA
Read-only

[READ][risk=low] Record an exported program's structure as a change baseline.

A control program is a controlled document, and the usual way an undocumented
change to one gets noticed is that somebody remembers. This gives the
comparison a number: the file's SHA-256, plus a per-block structural
fingerprint (name/kind/language, declared variables, calls, branch conditions,
timers) that deliberately excludes line numbers, comments and block order — so
adding a comment at the top of a file does not report the whole program as
changed. Stored locally under the iaiops home as block names, hashes and
counts — never a declaration, a source line or a comment — so the store is not
a second copy of the program. Reads the named EXPORTED file only; never a live
PLC upload.

Re-snapshotting a byte-identical file records nothing and says so — a history
padded with identical rows hides the rows that are not.

Args:
    path: Exported program file (.st/.scl/.awl/.l5x/.txt; must exist, ≤5 MB),
        under $IAIOPS_HOME, the config dir or an IAIOPS_AGENT_READ_DIRS dir.
    name: Program identity across exports. Defaults to the file's stem, and
        the result says which was used — the export path changes every time
        somebody opens the engineering station, the program does not.
    label: Short label, e.g. "approved v3.2 / MOC-118".
    note: Free note recorded with the snapshot.

Returns dict: {status ('recorded'|'unchanged'), program, name_source,
    snapshot:{snapshot_id, taken_at, source_file, content_sha256, label, note},
    block_count, snapshot_count, previous_snapshot}.

Example: plc_program_snapshot(path="~/.iaiops/plc/Line3.scl", label="approved v3.2").

Inputs: path (required), name, note, label.

plc_program_visibilityA
Read-only

[READ][risk=low] Maintainability / operational-risk profile of a legacy PLC program.

The "what am I inheriting?" view over one EXPORTED program (SCL/ST, AWL/STL,
Rockwell L5X): folds the structural outline into documentation coverage, the
least-commented blocks, blocks nothing references (possible dead code), the
complexity hotspots, risky constructs (unconditional JMPs, retentive RTO
timers, loops), and a TRANSPARENT additive risk score whose every point cites
its reason. Structural only — it anchors an engineer's review of a line
somebody else left behind, not a semantic understanding. Reads exactly the
named file (≤5 MB); never a live PLC upload. Every finding cites source_file +
line (rung number for L5X ladder).

Args:
    path: Exported program file (.st/.scl/.awl/.l5x/.txt; must exist, ≤5 MB),
        under $IAIOPS_HOME, the config dir or an IAIOPS_AGENT_READ_DIRS dir.

Returns dict: {source_file, fmt, stats:{blocks, call_edges, line_count,
    comment_count, comment_ratio, variables, branches, timers_counters},
    documentation:{comment_ratio, band ('well_commented'|'sparse'|
    'undocumented'), uncommented_block_count, uncommented_blocks},
    entry_points:[{name, kind}], unreferenced_blocks:[{name, kind,
    source_file, line}], complexity_hotspots:[{block, kind, score, branches,
    calls, timers_counters, source_file, line}], risky_constructs:{
    unconditional_jumps, unconditional_jump_count, loops, loop_count,
    retentive_timers, retentive_timer_count}, risk:{score (0..100), band
    ('low'|'medium'|'high'), reasons[]}, parse_errors, note}.

Example: plc_program_visibility(path="~/.iaiops/plc/Line3_Conveyor.scl").

Inputs: path (required).

plc_program_xrefA
Read-only

[READ][risk=low] Cross-reference one symbol in an exported PLC program.

Finds every read/write/call/declare site of a symbol or absolute address
(e.g. Motor_Run, "FB_Conveyor", DB10.DBX0.1, M0.0, Tank[2].Level) in one
exported file, quoting the surrounding source line verbatim so the agent
cites real code. Access classification is heuristic (op/regex based, not
data-flow analysis): SCL ':='→write, '('→call; AWL T/=/S/R→write,
L/A/O…→read, CALL→call; L5X OTE/OTL/OTU/RES and MOV-dest→write. For L5X,
line is the rung number.

Args:
    path: Exported program file (.st/.scl/.awl/.l5x/.txt; must exist, ≤5 MB),
        under $IAIOPS_HOME, the config dir or an IAIOPS_AGENT_READ_DIRS dir.
    symbol: Symbol / tag / absolute address to trace (word-bounded match).

Returns dict: {source_file, format, symbol, hit_count,
    hits:[{symbol, access, block, source_file, line, source_line}] (≤200),
    hits_truncated, by_access:{read, write, call, declare, reference}}.

Example: plc_program_xref(path="~/.iaiops/plc/OB1.awl", symbol="M10.0").

Inputs: path (required), symbol (required).

plc_program_xref_configA
Read-only

[READ][risk=low] Join an exported program's addresses with one endpoint's configured points.

Answers "which program symbol is that point on the line?" by **exact address
match only** — never by name. A configured label that reads like a program
symbol, or a ref one character from a tag, is NOT a match (semantics are given
by a person, never guessed). Comparable pairs: Siemens AWL / .scl × an ``s7``
endpoint (area, DB, byte, bit and width must all agree) and Rockwell L5X × a
Logix ``ethernetip`` endpoint (the tag path is the CIP address). Every other
pair returns ``comparable: false`` with the reason and NO lists — e.g. Modbus
registers are assigned in the device's Modbus map, which no export contains.

Args:
    path: Exported program file (.st/.scl/.awl/.l5x/.txt; must exist, ≤5 MB),
        under $IAIOPS_HOME, the config dir or an IAIOPS_AGENT_READ_DIRS dir.
    endpoint: Configured endpoint name whose ``tags`` are joined.
    live: Also read MATCHED points now. Logix requires a matching live
        controller name. AWL/SCL has no CPU identity, so MCP live reads are
        refused; an operator can attest origin through the CLI. A failed
        read is a gap with no value.

Returns dict: {program:{source_file, format, content_sha256}, endpoint:{name,
    protocol, configured_tag_count}, comparable, address_space,
    unmatchable:{program_format, protocol, reason}|null, refused (why an
    unreadable export was not answered)|null, parse_errors, program.controller
    (L5X: {name, processor_type}),
    matched:[{address, program_symbol, configured_ref, label, role, match
    ('exact_address'|'member_of_tag'), sites_scope (L5X), sites:[{access, block, line,
    source_line}], site_count}]|null, in_export_not_configured|null,
    configured_not_in_export|null, configured_not_comparable, overlaps,
    symbolic_only, indirect_access_sites, counts, notes,
    live:{points:[{configured_ref, status, ...}], read_count, gap_count}
    (only when live=True): a 'read' point has value, read_at, freshness; a 'gap'
    has error and NO value (read_at only when an empty answer arrived)}.

Example: plc_program_xref_config(path="~/.iaiops/plc/OB1.awl", endpoint="line3").

Inputs: path (required), endpoint (required), live.

profinet_asset_inventoryA
Read-only

[READ][risk=low] PROFINET asset register from a DCP IdentifyAll sweep.

Segment-wide, read-only — no per-device connection. The DCP device-role bitmask
is decoded when the client exposes it; pnio-dcp does not, so roles and the
controller/device counts come back empty and 0. Names, MACs and IP suites are
unaffected — those are what the register is for.

Args:
    endpoint: Endpoint name from config (protocol 'profinet').

Returns dict: {endpoint, asset_count, io_controller_count, io_device_count,
    assets:[{name_of_station, mac, ip, vendor_id, device_id, roles[], family}],
    method:'dcp_identify_all'}.

Example: profinet_asset_inventory(endpoint="cell1").

Inputs: endpoint.

profinet_dcp_setA
Destructive

[WRITE][risk=HIGH][MOC] DCP Set — re-address one PROFINET station (off by default).

OT-DANGEROUS. Defaults to dry_run=True (nothing set). Re-addresses a live
station's name-of-station and/or IP suite via a unicast DCP Set (can disrupt the
IO connection). Captures the BEFORE addressing (by MAC) and records an undo
descriptor. Set dry_run=False AND record an approver (OPCUA_AUDIT_APPROVED_BY) to
apply. 未经授权勿对生产控制系统写入.

Args:
    mac: Target station MAC, e.g. '00:1b:1b:12:34:56' (from profinet_discover).
    set_name: New name-of-station (omit to leave unchanged).
    set_ip: New IP address (omit to leave the IP suite unchanged).
    netmask: New subnet mask (used with set_ip).
    gateway: New default gateway (used with set_ip).
    endpoint: Endpoint name from config (protocol 'profinet').
    dry_run: When True (default) returns a preview without setting anything.

Returns dict: dry-run → {mac, dry_run:true, before, would_set, note};
    applied → {mac, dry_run:false, before, set, applied:true, _undo_id}.

Example (preview): profinet_dcp_set(mac="00:1b:1b:12:34:56", set_name="plc-new").

Inputs: mac (required), set_ip, dry_run, gateway, +3 more.

profinet_discoverA
Read-only

[READ][risk=low] DCP IdentifyAll — every PROFINET station on the segment.

One layer-2 broadcast surfaces all stations without connecting to any. Needs
raw-socket access on the NIC on the PROFINET subnet (pnio-dcp extra); degrades
to a teaching error dict when pnio-dcp/permission/NIC is missing.

Args:
    endpoint: Endpoint name from config (protocol 'profinet'); omit for default.

Returns dict: {endpoint, local_ip, station_count, stations:[{name_of_station,
    mac, ip, netmask, gateway, vendor_id, device_id, device_role_raw,
    device_roles[], device_family}]}. vendor_id/device_id/device_role* are
    always empty — pnio-dcp does not expose them (see the connector note).

Example: profinet_discover(endpoint="cell1").

Inputs: endpoint.

profinet_identify_stationA
Read-only

[READ][risk=low] Identify one station by its PROFINET name-of-station.

Args:
    name_of_station: Exact (case-insensitive) PROFINET station name, e.g. 'plc1'.
    endpoint: Endpoint name from config (protocol 'profinet').

Returns dict: {endpoint, found (bool), name_of_station, mac, ip, netmask,
    gateway, vendor_id, device_id, device_roles[], device_family}.

Example: profinet_identify_station(name_of_station="et200sp-1", endpoint="cell1").

Inputs: name_of_station (required), endpoint.

profinet_station_paramsA
Read-only

[READ][risk=low] Targeted DCP Get for one station (by MAC): name + IP suite.

Args:
    mac: The station's MAC address, e.g. '00:1b:1b:12:34:56'.
    endpoint: Endpoint name from config (protocol 'profinet').

Returns dict: {endpoint, mac, found (bool), name_of_station, ip, netmask, gateway}.

Example: profinet_station_params(mac="00:1b:1b:12:34:56", endpoint="cell1").

Inputs: mac (required), endpoint.

protocols_supportedA
Read-only

[READ][risk=low] Capability map — protocols, status, tools, connection params.

Call this to discover what iaiops can do before choosing a protocol/tool.
Lists implemented protocols (OPC-UA incl. HDA, Modbus, S7comm, Mitsubishi MC,
MTConnect, MQTT/Sparkplug B full-decode, EtherNet/IP Logix) and the EtherCAT
roadmap stub, plus cross-protocol analytics (OEE/downtime, asset inventory,
CoV), each with its read/write tools and the endpoint params it needs.

Also reports whether this server runs under the no-egress gate, so a model is
TOLD the posture instead of having to infer it from tools it cannot see.
Read/write authorisation is NOT a server posture here — it is the caller's
decision; every call (read or write, MCP or CLI) is audited.

Returns dict: {tool, posture, implemented_protocols:[...], roadmap_stubs:[...],
    protocols:[{protocol, status, library, transport, auth, read_tools,
    write_tools, params}], diagnostics:[...], analytics:[...], tool_counts,
    safety, write_note, no_egress_mode, no_egress_note}.

Example: protocols_supported().

Inputs: no named parameters.

rca_corpus_from_maintenanceA
Read-only

[READ][risk=low] Turn a CMMS/work-order export into the RCA incident corpus.

Auto-builds the labeled history learn_cause_weights needs from closed maintenance
records: an explicit taxonomy cause column wins; else a built-in EN/中文 CMMS
synonym table (extendable via 'synonyms'); else UNAMBIGUOUS keyword inference
over the row's free text using the copilot's own cause keywords. Rows it cannot
map land in 'unmapped' with the reason — never silently guessed. 'signals' come
from an explicit column or the symptom/alarm text (may stay empty — no fabricated
evidence). Pure + advisory; with learn=true the learned weights are included.

Args:
    rows: Work-order records, one dict each. Recognized cause columns:
        cause / root_cause / failure_class / category / problem_code; free-text
        columns: description / problem / notes / comment / text / 故障描述;
        signal text: symptom(s) / alarm(s) / 现象.
    synonyms: Extra site vocabulary, e.g. {"spindle crash": "mechanical_fault"};
        values must be taxonomy causes.
    learn: Also run learn_cause_weights on the mapped corpus (default true).
    min_samples: Passed to learn_cause_weights (default 8).
    smoothing: Passed to learn_cause_weights (default 1.0).

Returns dict: {corpus:[{cause, signals}], n_rows, n_mapped, unmapped:[{row,
    reason, excerpt}], mapped_via, weights?, next_step}.

Example: rca_corpus_from_maintenance(rows=[{"category":"轴承损坏",
    "symptom":"drive overload alarm"}], synonyms={"spindle crash":"mechanical_fault"}).

Inputs: rows (required), learn, synonyms, smoothing, +1 more.

rca_narrateA

[READ][risk=low] Narrate a cited RCA verdict in plain language via an on-box LLM.

Air-gapped: hands the already-computed, already-cited verdict to a LOCAL model (Ollama) that
ONLY rephrases it — it never adds a cause, number, or citation (strict prompt; see docs/RCA.md).
Read-only; no device I/O. Needs the extra + a running local model: pip install iaiops[ollama].

Args:
    verdict: An RCA verdict dict (e.g. the output of downtime_root_cause).
    base_url: Ollama server URL (default http://localhost:11434).
    model: Local model name (default 'llama3.1').
    provider: LLM provider (currently 'ollama').

Returns dict: {provider, model, narration}.

Example: rca_narrate(verdict=<downtime_root_cause output>, model="llama3.1").

Inputs: verdict (required), model, base_url, provider.

s7_cpu_infoA
Read-only

[READ][risk=low] S7 CPU identity + run/stop status (proves the link).

Args:
    endpoint: Endpoint name from config (protocol must be 's7'); omit for default.

Returns dict: {endpoint, rack, slot, cpu_status (e.g. 'run'/'stop'),
    cpu_info: {module, serial, version, ...}}.

Example: s7_cpu_info(endpoint="press1").

Inputs: endpoint.

s7_read_areaA
Read-only

[READ][risk=low] Read count items of a type from an S7 memory area.

Args:
    area: Memory area — DB | M (merker/flag) | I (input) | Q (output).
    dtype: S7 data type — BIT|BYTE|WORD|INT|DWORD|DINT|REAL|LREAL|CHAR.
    start: Byte offset within the area/DB (0-based).
    endpoint: Endpoint name from config.
    db: Data block number (required when area=DB).
    count: Number of consecutive items (1..100, capped server-side).
    bit: Bit offset 0..7 (only when dtype=BIT).

Returns dict: {endpoint, area, db, dtype, start, count,
    items:[{address, value}]}. ``value`` is bool/int/float per dtype.

Example: s7_read_area(area="DB", dtype="REAL", start=4, db=1, count=2).

Inputs: area (required), dtype (required), start (required), db, +3 more.

s7_read_dbA
Read-only

[READ][risk=low] Read count dtype items from data block db.

Args:
    db: Data block number (e.g. 1 for DB1).
    dtype: S7 data type — BIT|BYTE|WORD|INT|DWORD|DINT|REAL|LREAL.
    start: Byte offset within the DB (0-based).
    endpoint: Endpoint name from config.
    count: Number of consecutive items (1..100).

Returns dict: {endpoint, area:'DB', db, dtype, start, count, items:[{address, value}]}.

Example: s7_read_db(db=1, dtype="INT", start=0, count=10).

Inputs: db (required), dtype (required), start (required), count, +1 more.

s7_read_manyA
Read-only

[READ][risk=low] Batch-read raw pyS7 address strings in one request.

Args:
    addresses: pyS7 addresses, e.g. ["DB1,REAL4", "DB1,X0.0", "MW10", "I0.0"].
    endpoint: Endpoint name from config.

Returns dict: {endpoint, count, items:[{address, value}]}.

Example: s7_read_many(addresses=["DB1,REAL4","M0.0"]).

Inputs: addresses (required), endpoint.

s7_write_dbA
Destructive

[WRITE][risk=HIGH][MOC] Write ONE value to an S7 data block (off by default).

OT-DANGEROUS. Defaults to dry_run=True (nothing written). Captures the BEFORE
value (read-back) and records an undo descriptor so the change is reversible.
Set dry_run=False AND record an approver (OPCUA_AUDIT_APPROVED_BY) to apply.
未经授权勿对生产控制系统写入.

Args:
    db: Data block number.
    dtype: S7 data type — BIT|BYTE|WORD|INT|DWORD|DINT|REAL|LREAL.
    start: Byte offset within the DB.
    value: Value to write (coerced to the dtype's Python type).
    endpoint: Endpoint name from config.
    dry_run: When True (default) returns a preview without writing.

Returns dict: dry-run → {address, dry_run:true, before, would_write, note};
    applied → {address, dry_run:false, before, written, applied:true, _undo_id}.

Example (preview): s7_write_db(db=1, dtype="INT", start=0, value=42).

Inputs: db (required), dtype (required), start (required), value (required), +2 more.

site_readinessA
Read-only

[READ][risk=low] Which scenarios THIS site can run today, and what each gap needs.

The companion to `protocols_supported`, one altitude down. That one says what
the product can do; this says what this installation can do — and calling the
first without the second is how an agent plans a scenario the site has no
inputs for.

Contacts nothing: no device, no network, no historian. It is derived from
`config.yaml` and the local store, which is what makes it runnable against a
site nobody has authorised you to probe — the site that most needs it.

Three states, and the middle one carries the value: `ready`, `degraded` (it
RUNS, on less than full evidence — root cause without a historian still ranks
causes, it just cannot see the two hours before the stoppage) and `blocked`.

`blocked_on` is the actionable half: one missing input usually unlocks several
scenarios, ranked by how many.

It never fills a gap in for you. Which tag is the production counter is
process knowledge, and a wrong guess yields plausible-looking OEE numbers —
considerably worse than an error (D16). Where a prerequisite cannot be
supplied at all yet, the row says `not_yet_expressible` rather than implying
somebody forgot to configure it.

`db` overrides the local store path (.db/.sqlite, under $IAIOPS_HOME, the
config dir or an IAIOPS_AGENT_READ_DIRS dir); empty means the iaiops store.

Inputs: db.

sparkplug_decode_payloadA
Read-only

[READ][risk=low] Decode a single raw Sparkplug B payload to structured metrics.

Full protobuf decode (vendored Eclipse Tahu schema): per metric returns name,
alias, datatype (Int/Float/Bool/String/DateTime/DataSet/Template…), value,
timestamp, and is_historical / is_null flags. Rich types expand: a DataSet
value decodes to {columns, types, rows} and a Template value to {template_ref,
is_definition, version, members, parameters} (members decoded recursively).

Args:
    payload: Raw Sparkplug B protobuf bytes as a string, ``base64`` (default) or ``hex``.
    encoding: 'base64' or 'hex'.
    alias_map: Optional {alias: name} (from a prior BIRTH) so alias-only
        NDATA/DDATA metrics resolve to names.

Returns dict: {encoding:'sparkplug_b', timestamp, seq, uuid, metric_count,
    historical_count, metrics:[{name, alias, datatype, value, timestamp,
    is_historical, is_null}]}. A DataSet ``value`` is {dataset:true, columns,
    types, rows, row_count}; a Template ``value`` is {template:true,
    template_ref, is_definition, version, members:[{name, type, value}],
    parameters}.

Example: sparkplug_decode_payload(payload="CAESBwoDYWJjEAE=", encoding="base64").

Inputs: payload (required), encoding, alias_map.

sparkplug_live_schemaA
Read-only

[READ][risk=low] Capture a LIVE Sparkplug schema (bounded) → drift-ready dict.

Subscribes, collects up to ``max_msgs`` messages or until ``duration_s``, decodes
NBIRTH/DBIRTH metrics, and returns ``schema`` = {node: {metric: datatype}} (node =
group/edge[/device]) — exactly the shape uns_schema_drift accepts. Use it as a
baseline or current snapshot.

Args:
    endpoint: Endpoint name from config.
    topic: Topic filter (default 'spBv1.0/#').
    duration_s: Capture window in seconds (1..60).
    max_msgs: Max messages to capture (1..500).

Returns dict: {endpoint, topic, message_count, birth_count, node_count,
    schema:{node:{metric:datatype}}}.

Example: sparkplug_live_schema(topic="spBv1.0/Plant1/#", duration_s=15).

Inputs: topic, endpoint, max_msgs, duration_s.

sparkplug_node_listA
Read-only

[READ][risk=low] Discover edge nodes/devices + online state + primary-host STATE.

Builds the birth/death + seq model from BIRTH/DATA/DEATH/STATE topics: each
node reports online/born, its devices, learned metric aliases, and seq gaps;
STATE topics surface primary-host status.

Args:
    endpoint: Endpoint name from config.
    timeout_s: Observation window in seconds (1..60). Longer catches infrequent nodes.
    count: Max messages to inspect (1..500).

Returns dict: {endpoint, node_count, nodes:[{group_id, edge_node_id, online,
    born, devices:[...], metric_aliases_known, seq_gap_count, seq_issues}],
    primary_hosts:[{host_id, state}]}.

Example: sparkplug_node_list(timeout_s=15).

Inputs: count, endpoint, timeout_s.

sparkplug_point_draftB
Read-only

[READ][risk=low] BIRTH metrics → unconfirmed configured-point proposal.

Captures a bounded live schema. Every candidate has a collectable
``group/edge[/device]:metric`` ref, but role and label remain blank for a
person to review. No config is written; a short capture is never complete.

Inputs: topic, endpoint, max_msgs, duration_s.

sparkplug_subscribe_sampleA
Read-only

[READ][risk=low] Bounded Sparkplug B sample with full decode + birth/death/seq.

Topics are parsed and payloads fully protobuf-decoded; a birth/death + seq
model resolves aliases (from NBIRTH/DBIRTH), applies NDATA/DDATA by alias, and
flags is_historical metrics and seq gaps.

Args:
    endpoint: Endpoint name from config.
    topic: Topic filter (default 'spBv1.0/#').
    count: Max messages (1..500).
    timeout_s: Max seconds to wait (1..60).

Returns dict: {endpoint, topic, message_count, historical_metric_count,
    seq_gap_count, samples:[{topic, sparkplug:{group_id, message_type,
    edge_node_id, device_id}, payload:{metrics:[{name, alias, datatype, value,
    is_historical}]}}]}.

Example: sparkplug_subscribe_sample(topic="spBv1.0/Plant1/#", count=20).

Inputs: count, topic, endpoint, timeout_s.

stream_publishA

[READ][risk=low] Publish already-read normalized points to a message bus (NATS).

Egress of data the agent already READ — NOT a control write. Each numeric point becomes a JSON
message on ``<subject_prefix>.tag.<metric>``; non-numeric points are skipped (use a historian
sink for text/state). Needs the extra: pip install iaiops[nats].

Args:
    points: Collected point dicts (e.g. from *_read_many): {ref/metric, value, timestamp, ...}.
    subject_prefix: NATS subject root (default 'iaiops').
    servers: Comma-separated NATS server URLs (default nats://localhost:4222).
    token: Optional NATS auth token.
    tls: Use TLS to the broker.
    publisher: Bus kind (currently 'nats').

Returns dict: {publisher, subject_prefix, received, published, skipped_non_numeric}.

Example: stream_publish(points=[{"ref": "line1.temp", "value": 21.5}], subject_prefix="plant").

Inputs: points (required), tls, token, servers, +2 more.

stream_publish_eventA

[READ][risk=low] Publish one computed event (RCA verdict / alarm) to a message bus (NATS).

Egress of a finding the brain already COMPUTED — e.g. an RCA verdict or an alarm episode — to
``<subject_prefix>.<subject>`` as JSON. NOT a control write. Needs: pip install iaiops[nats].

Args:
    subject: Event subject suffix (e.g. 'rca.verdict', 'alarm.flood').
    event: The event payload dict (published as JSON).
    servers/token/tls/subject_prefix/publisher: bus connection (see stream_publish).

Returns dict: {publisher, subject, published}.

Example: stream_publish_event(subject="rca.verdict", event={"primary_cause": "seal"}).

Inputs: event (required), subject (required), tls, token, +3 more.

subscription_healthA
Read-only

[READ][risk=low] Health of a sequenced subscription feed (OPC-UA or Sparkplug B).

Detects dropped notifications (sequence gaps), duplicates / out-of-order, a high
republish-rejection rate, and overloaded channels — the classic Kepware
"too many tags on one channel → republish/queue-flush dropouts" fault.

Args:
    sequence: Sequence numbers actually received, in arrival order.
    republish_requested: How many republish requests were made.
    republish_rejected: How many were rejected (server couldn't keep up).
    tags_per_channel: {channel/endpoint: tag_count} — flags channels over the max.
    max_tags_per_channel: Density above which a channel is flagged (default 5000).
    wrap_at: Modulus for rolling counters (e.g. 256 for Sparkplug B seq); omit
        for monotonic OPC-UA counters.

Returns dict: {received, missed_count, duplicate_count, out_of_order_count,
    republish_requested, republish_rejected, republish_reject_rate,
    overloaded_channels:[{channel, tags}], max_tags_per_channel,
    verdict ('ok'|'reordered'|'lossy'|'overloaded'), recommendation}.

Example: subscription_health(sequence=[1,2,4,5], tags_per_channel={"ch1":7000}).

Inputs: sequence (required), wrap_at, tags_per_channel, republish_rejected, +2 more.

tag_healthA
Read-only

[READ][risk=low] Rank tag offenders by bad-quality / flatline / range / anomaly.

Args:
    tags: Per-tag dicts — {ref, label?, samples:[scalars or {value, good|quality}],
        warn_high?, alarm_high?, warn_low?, alarm_low?}.
    thresholds: Optional {ref: {warn_high, alarm_high, warn_low, alarm_low}} override.

Returns dict: {evaluated, overall ('ok'|'warn'|'alarm'), offender_count,
    offenders:[{ref, label, samples, latest, flags:[...], anomaly_count,
    severity (0..3)}], results:[...]}. Flags include bad_quality, flatline,
    out_of_range_warn/alarm, statistical_anomaly.

Example: tag_health(tags=[{"ref":"ns=2;i=5","samples":[70,71,70,99]}]).

Inputs: tags (required), thresholds.

uns_browseA
Read-only

[READ][risk=low] Browse the live topic tree (UNS) under a filter (bounded).

Args:
    endpoint: Endpoint name from config.
    topic: Topic filter to browse under (default '#').
    timeout_s: Observation window in seconds (1..60).
    count: Max messages to inspect (1..500).

Returns dict: {endpoint, filter, topic_count, topics:[...], tree:{nested segments}}.

Example: uns_browse(topic="factory/#", timeout_s=8).

Inputs: count, topic, endpoint, timeout_s.

uns_live_auditA
Read-only

[READ][risk=low] Capture the LIVE UNS topic tree (bounded) then audit it.

Closes the governance loop: subscribes to a live broker, collects up to
``max_msgs`` messages or until ``duration_s`` (whichever first), then runs the
naming-conformance + topic-sprawl audit over the observed topics. Never an
open-ended loop.

Args:
    endpoint: Endpoint name from config (protocol must be 'mqtt').
    topic: Topic filter to capture under (default '#').
    duration_s: Capture window in seconds (1..60, capped server-side).
    max_msgs: Max messages to capture (1..500, capped server-side).
    allowed_roots: Permitted top-level segments; others are flagged (optional).
    min_segments: Minimum namespace depth a well-formed topic must have.
    max_leaf_parents: A leaf under more than this many parents is scattered.

Returns dict: the uns_topic_audit result (topic_count, depth, verdict, findings)
    plus capture:{endpoint, topic, observed_messages, unique_topics, topics[]}
    and stored_for_onboard (False when the capture saw no topics).

Example: uns_live_audit(topic="factory/#", duration_s=8, allowed_roots=["factory"]).

Inputs: topic, endpoint, max_msgs, duration_s, +3 more.

uns_live_driftA
Read-only

[READ][risk=low] Capture the LIVE Sparkplug schema (bounded) and diff vs baseline.

Captures current node/metric definitions from live BIRTHs, then runs schema drift
against ``baseline`` — added / removed / type-changed metrics per node with a
none/additive/breaking verdict.

Args:
    baseline: Prior schema {node:{metric:datatype}} (e.g. from sparkplug_live_schema).
    endpoint: Endpoint name from config.
    topic: Topic filter (default 'spBv1.0/#').
    duration_s: Capture window in seconds (1..60).
    max_msgs: Max messages to capture (1..500).

Returns dict: the uns_schema_drift result (changed_nodes, verdict, node_changes)
    plus capture:{endpoint, topic, message_count, birth_count, node_count}.

Example: uns_live_drift(baseline={"Plant1/Edge1":{"Temperature":"Double"}}).

Inputs: baseline (required), topic, endpoint, max_msgs, +1 more.

uns_publishA

[READ][risk=low] Publish already-read normalized points to an MQTT broker / UNS.

Egress of data the agent already READ — NOT a control write. Each numeric point becomes a JSON
message on ``<topic_prefix>/<metric>``, with a dotted metric nested into topic levels
(``line1.temp`` -> ``plant/line1/temp``) so a Unified Namespace stays browsable. Non-numeric
points are skipped (use a historian sink for text/state). The topic is always derived from
``topic_prefix`` — it is never taken verbatim, so this cannot address a command topic. Needs the
extra: pip install iaiops[mqtt].

Args:
    points: Collected point dicts (e.g. from *_read_many): {ref/metric, value, timestamp, ...}.
    topic_prefix: Root of the topic tree (default 'iaiops'); wildcards are stripped.
    host: Broker hostname or IP (default localhost).
    port: Broker port; 0 picks 8883 with TLS else 1883.
    username: Optional broker username.
    password: Optional broker password.
    use_tls: Use TLS to the broker.
    qos: MQTT QoS 0/1/2 (default 0, fire-and-forget); values outside 0-2 are clamped.
    retain: Ask the broker to retain the last value per topic (useful for a UNS).

Returns dict: {publisher, topic_prefix, broker, received, published, skipped_non_numeric}.

Example: uns_publish(points=[{"ref": "line1.temp", "value": 21.5}], topic_prefix="plant",
    host="10.0.0.5").

Inputs: points (required), qos, host, port, +5 more.

uns_schema_driftA
Read-only

[READ][risk=low] Detect Sparkplug/UNS schema drift between two snapshots.

Compares baseline vs current node/metric definitions (e.g. two NBIRTH snapshots)
and reports added / removed / type-changed metrics per node, with a verdict.

Args:
    baseline: {node: {metric: datatype}} or [{node|topic, metrics:[{name, datatype}]}].
    current: Same shape — the newer snapshot to compare against the baseline.

Returns dict: {baseline_nodes, current_nodes, changed_nodes,
    verdict ('none'|'additive'|'breaking'), node_changes:[{node, node_status,
    added[], removed[], type_changed:[{metric, from, to}]}]}.

Example: uns_schema_drift(baseline={"N1":{"temp":"Float"}},
    current={"N1":{"temp":"Int32","rpm":"Float"}}).

Inputs: current (required), baseline (required).

uns_topic_auditA
Read-only

[READ][risk=low] Govern a UNS topic tree: naming conformance + topic sprawl.

Pure analysis over a provided list of UNS topic strings (no live broker). Flags
non-conforming roots, too-shallow topics, casing collisions of the same logical
name, leaf metrics scattered under many parents, depth outliers, and duplicates.

Args:
    topics: UNS topic strings, e.g. ["Enterprise/Site/Area/Line1/temperature", ...].
    allowed_roots: Permitted top-level segments; others are flagged (optional).
    min_segments: Minimum namespace depth a well-formed topic must have.
    max_leaf_parents: A leaf appearing under more than this many parents is scattered.

Returns dict: {topic_count, unique_topics, root_count, roots[], depth{min,max,mean},
    verdict ('clean'|'minor'|'sprawling'), sprawl_findings, findings{
    non_conforming_root[], too_shallow[], casing_collisions[], scattered_leaves[],
    depth_outliers[], duplicate_topics[]}}.

Example: uns_topic_audit(topics=["Ent/Site/Line1/temp","Ent/site/Line1/Temp"],
    allowed_roots=["Ent"], min_segments=3).

Inputs: topics (required), min_segments, allowed_roots, max_leaf_parents.

verify_determinismA
Read-only

[READ][risk=low] Prove this engine's analysis is reproducible without a model.

Runs a named suite of analyses (availability, production counts, the Six Big
Losses, ISA-18.2 alarm load, control charts, the conservative baseline, the
RCA copilot) over a pinned reference dataset, canonically encodes each result
and digests it — twice in this process and, with ``subprocesses``, once more
in each of two fresh interpreters started at different PYTHONHASHSEED values.
That last arm is the one that catches a set or dict iteration order reaching a
result; a single run never can. The socket API raises throughout, so a
computation that reached for a device or a hostname fails here rather than
quietly succeeding on a machine that happens to be online. ``sys.modules`` is
checked afterwards for any model library — empty is the guarantee.

Use it to answer "how do I know your AI didn't make this number up": the
answer is that no model is in the path, and here is the SHA-256 that says so,
reproducible on the customer's own box. Read-only; nothing is written unless
the CLI (`iaiops verify determinism --out record.json`) is used to save the
signable record for a validation file.

Args:
    subprocesses: Also re-run in two fresh interpreters at fixed, different
        hash seeds (default True; adds roughly a second).

Returns dict: {check, result:{verdict ('reproducible'|'not_reproducible'),
    suite_digest, dataset:{name, revision, digest}, checks:[{name, covers,
    digest}], arms:[{arm, suite_digest, matches_first_arm}], arms_disagreeing,
    model_modules_loaded, network}, context:{iaiops_version, python, platform,
    generated_at, ...}, note}. ``result`` is identical between runs; ``context``
    is not — it records when and where this run happened.

Example: verify_determinism().

Inputs: subprocesses. Returns: object

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.4/5.0

    Scored across 157 tools

    Disambiguation2/5

    The set contains many near-overlapping tools: protocol-specific read variants (s7_read_area/s7_read_db/s7_read_many, fins_read_words/fins_read_many, mc_read_words/mc_read_many), deprecated aliases (health_summary vs opcua_health_summary, anomaly_scan vs opcua_anomaly_scan), and multiple alarm/RCA/data-quality tools with subtly different scopes. The long descriptions help, but at 157 tools an agent will frequently have to compare several plausible tools before choosing.

    Naming Consistency3/5

    Almost all names are snake_case and many are grouped by protocol or domain prefix, which makes the set readable. However the convention is mixed: some tools are protocol_verb_noun (s7_read_db), others are noun_verb or noun phrases (line_relations_list, sparkplug_point_draft, site_readiness, alarm_flood_analysis), and deprecated aliases coexist with their replacements.

    Tool Count1/5

    157 tools is an extreme mismatch for a single MCP server surface, far beyond the typical 3-15 well-scoped range and well past the 50+ threshold for a severe over-scoping problem. Even for a broad industrial platform, the surface is too large to navigate reliably without strong grouping or routing.

    Completeness4/5

    Coverage is very broad: many OT protocols, historian access, UNS/MQTT/Sparkplug, PLC program analysis, RCA, alarm analytics, OEE, compliance, baselines, and several MOC-gated write paths. Minor gaps remain, such as absent OPC-UA and Modbus write tools and some protocol-specific write variants, but the core read/analyze/write lifecycle is largely present.

    Maintenance

    ActivityActive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Connects AI agents to OPC UA-enabled industrial systems for real-time monitoring and control of operational data. It enables users to read, write, and browse industrial device nodes through natural language interactions.
      MIT
    • A
      license
      B
      quality
      B
      maintenance
      Exposes a deterministic IoT edge runtime — Modbus/CAN/J1939 acquisition, local rules, alarms, and history — to AI assistants as typed, governed MCP tools. Reads are safe by default; device control stays deny-by-default, explicitly confirmed, and audited.
      23
      3
      Apache 2.0
    • A
      license
      B
      quality
      B
      maintenance
      Governed, read-only OT data tap for substation and utility telecontrol — IEC 60870-5-104, DNP3/IEEE 1815, and IEC 61850 MMS connectors with cross-protocol asset discovery, alarm and downtime RCA, unbypassable audit logging (MCP + CLI), budget/runaway guards, and an airgap no-egress mode. Energy edition of Industrial-AIOps, built on iaiops.core.
      81
      107 PyPI
      3
      MIT
    • F
      license
      Not graded
      quality
      C
      maintenance
      Enables AI agents to connect to Allen-Bradley, Siemens, and CODESYS PLC projects for discovering, asking questions about, analyzing, and proposing code changes, with access to live tag values and version exports under permission-scoped controls.
      -