opcua-readonly-mcp
README.md
# opcua-readonly-mcp
[](https://github.com/andrew-myers-collab/opcua-readonly-mcp/actions/workflows/ci.yml)
## Problem
An AI model that can browse and read plant data over OPC UA is useful. A model that can write a setpoint or call a method on a running machine is a safety risk. This project is a Model Context Protocol (MCP) server that lets a model browse and read OPC UA nodes through a node allowlist, a rate limit, and an audit log. The code has no write, method call, or subscription path. Static tests and runtime tests prove this. The tool limits what this server can send. It does not make a plant safe.
## Quick start
```
python -m venv .venv
.venv/Scripts/python -m pip install -r requirements.txt # Linux/macOS: .venv/bin/python
.venv/Scripts/python demo.py
```
The demo starts an in-process OPC UA simulator on a free port, builds the MCP server, and calls the tools through `mcp.Client`. It exits 0 when all simulator counters are 0.
Run as a stdio MCP server against your own test server:
```
python -m opcua_readonly_mcp --config config/demo.json --check # connect, resolve, print allowlist; exit 0, or 2 on error
python -m opcua_readonly_mcp --config config/demo.json # stdio MCP server
```
To run the simulator alone on port 4840 (matches `config/demo.json`): `python -m simulator.sim_server`.
## Tools
| Tool | Arguments | Returns |
|---|---|---|
| `server_info` | none | `endpoint`, `namespaces`, `server_state`, `current_time`, `allow`, `deny`. Reads ServerStatus (`i=2256`), a fixed read. |
| `browse` | `node_id`, `max_results` (1..`max_browse_results`, default 100) | `node_id`, `children` (`node_id`, `browse_name`, `display_name`, `node_class`), `hidden` count, `truncated`. Forward hierarchical references (`i=33` and subtypes). |
| `read_values` | `node_ids` (1..`max_nodes_per_read`) | One row per node: `node_id`, `value`, `data_type`, `status`, `source_timestamp`, `server_timestamp`, and `truncated` when cut. One OPC UA Read call. |
| `read_attributes` | `node_id`, `attributes` | `node_id`, `attributes`, `status`. Allowed names: DisplayName, Description, NodeClass, DataType, ValueRank, ArrayDimensions, AccessLevel, UserAccessLevel, MinimumSamplingInterval. |
Resource `opcua://allowlist` returns the resolved allow and deny patterns, the roots, and the namespace array.
Errors are MCP tool errors with a fixed prefix: `Access denied:`, `Rate limit:`, `Bad request:` (REQ001 too many nodes, REQ002 `max_results` out of range, REQ003 node ID does not parse, REQ004 attribute name not in the set), `OPC UA error:`, `Timeout:`.
## Read-only layers
| Layer | Where | What it stops | Test |
|---|---|---|---|
| RO1 Tool surface | `server.py` | Exactly four tools and one resource. No tool has a value, data, or method argument. Extra JSON keys are dropped. | `test_readonly.ToolSurfaceTests.test_ro1_exact_tools_and_resource` |
| RO2 One gateway | `uaread.py` | Only this module imports asyncua. The client is private; the gateway has only `connect`, `close`, `namespace_array`, `browse`, `read`. | `StaticTests.test_ro2_asyncua_import_only_in_gateway`, `test_ro2_gateway_public_methods` |
| RO3 Forbidden names | `selfscan.py` (ast scan) | Write, call, subscribe, node management, and history names; `write`/`call` in `uaread.py`; `getattr`, `__getattribute__`, `exec`, `eval`, `importlib`, `__import__`. | `StaticTests.test_ro3_package_scan_is_clean`, `test_ro3_scanner_catches_planted_file` |
| RO4 Runtime proof | `simulator/sim_server.py` | Counts writes, method calls, subscriptions, and node changes while every tool runs on every allowed node plus hostile input. All stay 0; all Plant values and the address space size stay the same. | `RuntimeTests.test_ro4_counters_zero_after_full_run`, `test_ro4_bait_value_unchanged`, `test_hostile_node_ids_give_no_write` |
| RO5 Negative control | `tests/test_readonly.py` | A raw asyncua client writes the bait node and calls the bait method; each counter goes to 1. This proves RO4 can see a write. | `NegativeControlTests.test_ro5_write_counter_goes_to_1`, `test_ro5_method_counter_goes_to_1` |
| RO6 Server side | your OPC UA server | Connect with an OPC UA user whose server rights are read-only. The server is the real guard. | none (the simulator does not enforce users) |
How the simulator counts (asyncua has callbacks for some cases only):
- writes: `CallbackType.PreWrite` server callback, client sessions only (the server updates its own status nodes through an internal session).
- method calls: the handler of the bait method `Plant.Line1.ResetCounter`.
- subscriptions: `CallbackType.ItemSubscriptionCreated` (monitored items) plus a counting wrapper on the subscription service, because there is no callback for CreateSubscription.
- node changes: a counting wrapper on AddNodes, DeleteNodes, AddReferences, DeleteReferences, because asyncua has no callback for them. RO4 also compares all Plant values and the node count before and after.
Run the static scan alone: `python -m opcua_readonly_mcp.selfscan [DIR]` (exit 1 on a hit).
## Allowlist and namespace URIs
- A caller may send `ns=2;s=...`, `nsu=<uri>;s=...`, or bare `i=`, `s=`, `g=`, `b=` (namespace 0).
- The server turns each node ID into the canonical form `nsu=<uri>;<type>=<id>` with the server namespace array, then matches it with `fnmatch.fnmatchcase`.
- Patterns must use the `nsu=` form with a literal URI, so a namespace index change on the server cannot move a pattern to other nodes.
- Deny wins over allow. A `*` in a caller node ID is a literal character, never a pattern.
- Namespace 0 nodes are denied unless an allow pattern names `nsu=http://opcfoundation.org/UA/;...` explicitly.
- A denied node and a missing node give the same message, so a caller cannot probe for hidden nodes.
## Configuration
Unknown keys are an error. Config errors exit 2 at start.
| Key | Default | Meaning |
|---|---|---|
| `endpoint` | required | `opc.tcp://host:port/path`. For a user login use `opc.tcp://user:password@host:port/path`; `server_info` removes the login from the output. |
| `security` | `null` | `null` for policy None, or an asyncua security string (for example `Basic256Sha256,SignAndEncrypt,cert.der,key.pem`). |
| `roots` | required | Start nodes. Each must be allowed (CFG005). |
| `allow` / `deny` | required / `[]` | `nsu=<uri>;<type>=<fnmatch pattern>` (CFG002 bad form, CFG003 URI not on the server). |
| `rate_per_minute` | 60 | Sliding 60-second window per process. |
| `max_nodes_per_read` | 50 | REQ001 above this. |
| `max_browse_results` | 200 | Upper bound for `max_results` (REQ002). |
| `max_string_chars` | 4096 | Strings, ByteString base64, and structure text are cut to this. |
| `max_array_items` | 1000 | Arrays are cut to this. |
| `timeout_s` | 5 | `asyncio.wait_for` on every OPC UA call. |
| `audit_log` | `audit.log` | JSONL file, one line per tool call: `ts`, `tool`, `node_ids`, `outcome`, `n`, `ms`. Values are never logged. |
All limits must be positive integers (CFG004). Values: DateTime as ISO 8601 UTC, ByteString as base64, LocalizedText as text, structures as `{"type", "repr"}`.
## Sample output
Real output of `python demo.py`:
```
simulator: opc.tcp://127.0.0.1:62616/demo/ namespace urn:demo:plant
> server_info ok state=Running namespaces=3
> browse Plant.Line1 ok 4 children, 1 hidden
> read_values Press1.* ok Temperature=20.0 Running=True CycleCount=1200 State=AUTO
> read_values Recipe ok truncated at 4096 chars
> read Maintenance.Password Access denied
> 61 calls in one minute call 61: Rate limit
> audit.log 66 lines, outcomes ok 64 denied 1 rate_limited 1
simulator counters: writes 0, method calls 0, subscriptions 0, node changes 0
```
## Tests
```
python -m unittest discover -s tests -t .
```
45 tests: config (8), allowlist (8), tools (12), limits and audit (7), read-only (10).
## Design notes
- No subscriptions: a subscription keeps server resources alive and pushes data without a tool call, so it bypasses the rate limit and the audit log. Polling with `read_values` is enough for a model.
- One gateway module: the read-only claim is easy to check when one small file holds the only asyncua import and the only client object. The ast scan enforces this in CI.
- Same message for denied and missing: different messages would let a caller find hidden node names by trial.
- No `getattr` or string dispatch: a tool cannot turn caller text into a method name.
- Built on the official `mcp` SDK (`MCPServer`, `@mcp.tool()`, `@mcp.resource(...)`, `ToolError`), the same pattern as the sibling `readonly-sql-mcp` project.
## Limits
- Only security policy None is tested. Other security strings pass to asyncua unchanged.
- One OPC UA endpoint per process. No reconnect after the connection drops; restart the process.
- The rate limit is per process, not per user.
- The server rights of the OPC UA user are the real guard (RO6). This project limits what this MCP server can send; it does not make a plant safe.
- The simulator does not enforce users or access rights.
- asyncua version: `requirements.txt` pins `asyncua==1.1.8` for Python below 3.14. On Python 3.14, 1.1.8 installs but its client fails at run time (TypeError in the binary serializer), so Python 3.14 uses `asyncua==2.1.0`, the newest release. Local tests ran on Python 3.14 with 2.1.0 only; the 1.1.8 path runs in CI on Python 3.12.
- Tool argument type errors are rejected by the MCP SDK before the tool runs, so they have no audit line.
All data is synthetic.
This server cannot be deployed
Maintenance
ActivityMaintained
ResponsivenessNo recent community issues