# Description Implements **OPC UA — Vision** and uses it to build the demo the companion specifications were drafted for: an eye-in-hand camera watches a bin of parts, a language model *looks at the frame*, decides which part matches the instruction, and commands the robot through Robot Intent — with the OpenUSD viewer showing the arm move and the bin empty out. > **Draft, and stacked.** [#4195](https://github.com/OPCFoundation/UA-.NETStandard/pull/4195) has merged and master is merged in, so what is left on top of `master` is the Vision work plus the unmerged `marcschier/ai-model-management` branch, which the demo needs for the model/dataset/deployment provenance. Review the Vision commits; the AI Model Management work lands with its own PR. ## What is here **The specification, implemented.** `Opc.Ua.Vision` is generated from the spec's own `Opc.Ua.Vision.NodeSet2.xml`, vendored byte-identically (SHA-256 `79C592C6…`, verified against a fresh download and stored LF-preserved like the Robot Intent NodeSet). `Opc.Ua.Vision.Server` builds the §4.2 discovery object, sensors, the coordinate-frame tree, calibrations, media endpoints, inference pipelines and the §9 feedback methods, with rendering and inference behind injectable providers. `Opc.Ua.Vision.Client` is built on the generated ObjectType proxies and composes transforms across the frame tree, which is what turns a detection in camera coordinates into a pose a robot can act on. **Two perception paths behind one contract**, which is exactly what `InferenceLocationEnum` is for. `OnServer` is a deterministic detector derived from the stage's ground truth — no model, no network, no GPU, so CI can exercise the whole loop. `EdgeOffServer` is the agent: it sees the frame over MCP and calls `SubmitDetections`, and the Server publishes results it did not compute. A client reads `DetectionResultType` identically either way. **The agent's eyes.** `tools/Opc.Ua.Mcp.Vision` adds 22 `vision_*` tools, which with the four shared connection tools makes the `vision` profile 26; `vision_get_frame` returns the camera image as an MCP `ImageContentBlock`, so the model looks at pixels rather than reading a description of them. Tool profiles now compose — `--profile vision,robotics` yields 62 tools — so one agent can both see and act without dragging in the full 136-tool catalogue. **The cell.** `samples/Robotics/BinPickingCell` follows the spec's own Robotics-Vision Addendum: the `world → robot_base → flange → gripper_tcp` frame tree with `camera_eih` on the flange, the `HandEye` extrinsics and the `Intrinsics612x512` intrinsics — the addendum's 2448×2048 calibration scaled to the 4×4-binned grid the camera actually delivers. `samples/Robotics/BinPickingClient` hosts the composed MCP catalogue and optionally the viewer. **Documentation.** `docs/Vision.md` (~800 lines) covers the model, hosting, the build context, every topology builder, both perception paths, feedback, the MCP profile and the limitations; linked from `docs/README.md`, with the profile table in `docs/McpServer.md` and READMEs for both samples. ## Evidence, not assertions Each of these was measured on a running system rather than assumed: | Claim | Evidence | |---|---| | The camera sees the bin | 612×512 frame with the bin and all five parts in view — red `(212,47,47)`, green `(61,193,71)`, blue `(54,85,218)`, yellow `(215,196,58)`, orange `(209,119,55)` | | An agent can act on what it sees | Over MCP, `vision_get_frame` returns a 612×512 PNG that decodes from base64 to 1,254,051 bytes, the descriptor beside the detections says 612×512, and all five `BoundingBox2D` centres land **inside** the frame on the pixel colour their own detection claims | | The geometry is right | A detection composed `camera_eih → world` lands on the authored position, residual **0.0000 m** — on both the on-server and off-server paths | | The detector tracks the world | Placing a part drops the next scan from 5 detections to 4, with that part absent | | The robot obeys the agent | Scripted run took command authority and completed a pick and a place, both `Succeeded` | | Tool catalogues are honest | Counted from a running server: vision 26, robotics 40, `vision,robotics` 62, full 136, **zero duplicates** | | Every node is browsable by NodeId | Eight representative NodeIds — both folders, a pipeline, a frame, the sensor, its Calibrations folder, the HandEye calibration, the Media folder — all `Good` | That tool-count check matters because the profile tests collapse names into a `HashSet` and *cannot see* a duplicate registration — so the new tests count registrations, not names. ## Things that were wrong, and are not now Writing the tests found three defects of one kind — code that answered instead of refusing. A zero-norm quaternion was silently rewritten to identity, so a caller with an all-zero orientation got a confident wrong grasp pose. `SubmitCorrection` rewrote a null `ResultId` to empty and called the sink anyway. A bad `StageIdentifier` **killed the host process** inside native `UsdStage.Open`, via an exception .NET cannot catch. All three now refuse loudly and are pinned by tests. **Nodes that existed but could not be reached.** The node manager indexes the Vision root before configurators run, so everything the fluent builder grafted on afterwards — both folders, the pipelines with their Results and Feedback, the frames, the sensors with their optics, calibrations and media endpoints — was never added to the index. Browsing *forward from a parent* worked, because that walks `NodeState.Children` in memory; browsing any of those nodes *by its own NodeId* returned `BadNodeIdUnknown`, which is how an ordinary client and the MCP discovery tools navigate. Registration is now deferred and flushed after each configurator. The first fix covered only the DI path and left the documented non-DI fallback broken in exactly the same way, so `ConfigureVisionAsync` now exists and registers what it builds. That defect survived a green suite because every test browsed children. The new tests assert by NodeId, and were checked against the broken code — with the flush removed, they fail. **Every Method was uncallable.** The Server passed 426 unit tests while not one of its Methods could be invoked over a real session — `RunInference` returned `Bad_TooManyArguments`, and so did every other Method that takes arguments, which is all of them but `StartContinuous` and `Stop`. Three independent faults, each sufficient on its own: the Method nodes were never created (they are Optional children, and the dispatcher guards every attachment with a null check, so it silently attached nothing); nothing declared the arguments, so the stack concluded none were expected; and `MethodDeclarationId` pointed at a synthesised NodeId rather than the NodeSet declaration a client calls with, so the lookup missed the instance Method entirely. The builder now creates the Methods, the `Results` folder and the `Feedback` object when a provider or sink is configured, declares every signature, and names the right declaration. Unit tests could not have caught this: they invoke the handler delegates directly and never go through `MethodState.Call`. It took an end-to-end test over a real session. Relatedly, children created by the generated `CreateOrReplace` helpers carry no `ReferenceTypeId`, so nothing could reach them — fixed once in the build context rather than at the several dozen call sites. **And one where I was wrong.** Earlier in this branch I reversed my own agents' decision and made `SubmitDetections` accept an empty detection set, reasoning that "I looked and the bin is empty" is a correct observation and refusing it forces a correct agent to invent a detection. The reasoning is sound; it is also an argument *against* the specification rather than an implementation of it. §9.5 is normative and explicit — its StatusCode table lists `Bad_InvalidArgument` for "`Detections` empty; or `SubmitCorrection` supplies both or neither corrected array". Worse, **none of §9.5's argument rules were enforced anywhere** — the dispatcher forwarded every submission straight to the feedback sink, so conformance depended on whichever sink a host installed. They are Server obligations, so they now live in the dispatcher, ahead of the sink, proven by strict mocks that would throw if the sink were consulted. The usability problem is real and does not go away by conforming, so it is raised where it can be fixed: [opcua-drafts#70](https://github.com/marcschier/opcua-drafts/issues/70). ## Tracking the updated drafts The Vision, Robot Intent and AI Model Management NodeSets on `opcua-drafts` `main` have moved, partly because of feedback this branch raised. All three are re-vendored byte-identically — verified by comparing git blob hashes against the upstream files rather than by eye — and the implementations follow. **Two statements that were previously inexpressible now have a wire representation.** `SubmitDetections` takes `SceneIsEmpty` and `SubmitCorrection` takes `RetractAll`, so an agent can report "I examined this frame and there is nothing in it" — the terminating condition of the bin-picking task — and can retract a false positive by correcting a result down to nothing. Both are checked in both directions, because the flag is exactly what separates a deliberate empty observation from a lost payload: an empty array without the flag is refused, and the flag with an array attached is refused as two contradictory claims about one frame. Implemented in the dispatcher, the client, the MCP tools the agent drives, and the sample cell. Also absorbed: `LampType` and `LightingMode` became enums (§66), `ProfileName` became `DefaultProfileName` on the endpoint (distinct from the `ProfileName` a caller passes to `GetStreamEndpoint`, which keeps its name), AI `Invoke`/`InvokeAsync` gained `PayloadUri` under the same exactly-one rule, and AI `ListModels` gained a `ContinuationPoint` — because `MaxResults` alone puts everything past the bound permanently out of reach. **OpenUSD is on `0.9.0-alpha`**, verified on the running cell rather than by restore alone: D3D12 backend, 612×512 frame, the bin and all five parts in view and detected — the same result `0.8.0-alpha` produced. The one local workaround that survives is `VisionMethodArguments`, and its reason has changed rather than gone away: the builder materialises these Methods as Optional children through `CreateOrReplace`, which constructs the state object directly and never runs the generated factory that now carries the signatures. Checked rather than assumed — removing the declarations fails five of the eight `VisionMethodSurfaceTests`. ## Review feedback Three threads, all addressed in `0fe2803a3`: - **The AI Model Management work is now a library family, not a sample.** `src/Opc.Ua.AI` (model), `.Inference` (`IInferenceBackend` and backends), `.Server` (node manager) and `.Client` (discovery, reads, calls, artefact transfer), in the same shape as the Robotics and Vision families; the samples become `samples/AI/ModelManagementServer` and `ModelManagementClient`. The client library needed real work rather than relocation: its browsing surface was `private` inside the sample's scenario runner, so moving the file alone would have produced a library nobody could call. - **No cloud-vendor SDK is referenced anywhere.** Inference goes through `Microsoft.Extensions.AI` — an `IChatClient` is implemented by hosted services and on-device runtimes alike, which is exactly the property clause 8.1 asserts. `Azure.Identity` is gone: workload identity is not an Azure feature, every platform projects a token into a file and each SDK reads that file behind its own API, so the resolver reads it directly. The comment claiming `Microsoft.Extensions.AI` would force a `System.Text.Json` bump was stale — it pins 10.0.10, which this repository already centralises on. - **`BinPickingCell` and `BinPickingClient` moved into `samples/Robotics/`**, which is where they belonged: the cell was already linking the arm, its kinematics and both USD assets out of `IntentEnabledRobot`. ## Upstream Work that belonged elsewhere went elsewhere rather than being worked around locally: - **`openusd-dotnet` [#13](https://github.com/marcschier/openusd-dotnet/pull/13)** — merged and shipped in `0.8.0-alpha`. `SilkFrameCapture.Capture` rendered only the first capture of a session and silently returned a blank frame for every one after it. Also filed [#14](https://github.com/marcschier/openusd-dotnet/issues/14) (no camera-by-prim API) and [#15](https://github.com/marcschier/openusd-dotnet/issues/15) (skipped tests reported as passed — which fooled me for several runs). Both are fixed; this branch takes `0.8.0-alpha` and deletes two workarounds, including 143 lines of hand-rolled projection maths. - **`opcua-drafts` [#66](https://github.com/marcschier/opcua-drafts/issues/66)–[#69](https://github.com/marcschier/opcua-drafts/issues/69)** — a close read of the spec produced 22 candidate ambiguities; 12 were discarded as misreadings with clause citations and the remaining 10 filed. One is concrete: five members exist in the NodeId CSV that no clause documents. - **`opcua-drafts` [#70](https://github.com/marcschier/opcua-drafts/issues/70)** — §9.5 could not express an empty observation or a false-positive retraction. **Adopted**, with the explicit-flag resolution argued for: `SubmitDetections` gained `SceneIsEmpty`, `SubmitCorrection` gained `RetractAll`, and the corrected-array rule relaxed from *exactly one* to *at most one*. - **`opcua-drafts` [#71](https://github.com/marcschier/opcua-drafts/issues/71)** — the Vision NodeSet browse-named all 13 `InputArguments` / `OutputArguments` Properties in the Vision namespace rather than the base namespace, so a stack could not find them and every Method in the specification was uncallable. **Fixed**; this branch now tracks the corrected artefact. ## The defect underneath it all The end-to-end suite was removed earlier in this branch because nine of its fourteen tests failed on one symptom: a client could not open a pipeline's `Feedback` object or enumerate its `Results`, even though browsing the same parent listed both. Restoring it meant explaining that, and the explanation was not in Vision. `RelativePathElement` initialised **`IsInverse` to `true`**. A caller that sets a `ReferenceTypeId` and a `TargetName` — which reads as *"the child reached by this Reference"* — was therefore asking the Server for the **inverse** Reference, and got `Bad_NoMatch` with nothing in the request to suggest why. `ObjectTypeClient.ResolveChildNodeIdAsync` is such a caller, and it is what **every source-generated Optional-child accessor in the stack** is built on — the accessor whose own documentation cites `AlarmConditionTypeClient.GetShelvingStateAsync` as an example. Vision is merely where it surfaced, because Vision puts two Optional children on the path an off-Server agent must take. The sibling helper in `StateMachineTypeClientExtensions` already set `IsInverse = false` by hand, which is the shape of a trap rather than a default. The default is now forward, `ResolveChildNodeIdAsync` says so explicitly, and the existing test that had recorded `true` as *expected* now pins `false` with the reasoning. Of the forty `RelativePathElement` construction sites in the tree, that accessor was **the only one relying on the default at all** — every deliberate caller already set it. Two further defects were found underneath it, both real and both fixed: - The generated `CreateOrReplace` helpers construct a child state object directly and leave **`TypeDefinitionId`** unset as well as `ReferenceTypeId`. A child referenced by nothing cannot be browsed; one with no type definition is a malformed Object that a client filtering by type silently skips — which is exactly what `EnumerateResultsAsync` does. Normalisation moved to `VisionNodeManager`, so it also covers the case the builder cannot see: a result published **at runtime** by an inference provider, long after the address space was built. That path produced results a client could list but not read. - `Opc.Ua.AI` shipped without an `AssemblyInfo`, so the solution built with six `CA1014` warnings. I had initially "fixed" this in the Vision client with Browse-based fallbacks, on the strength of a probe that appeared to show `TranslateBrowsePathsToNodeIds` failing even for `Server → ServerStatus`. That probe was wrong: it used an unqualified `ReferenceTypeIds`, which inside a `Opc.Ua.Vision.*` namespace binds to *Vision's* `ReferenceTypeIds` and yields a nonsense NodeId. Chasing that to the end is what turned up the real cause. **The fallbacks are gone** — they would have hidden a stack-wide bug behind a Vision-shaped workaround, and one of them matched on browse name while ignoring the namespace index. `tests/Opc.Ua.Vision.Intent.Tests` is restored and back in `UA.slnx`, passing **14/14** on its own merit rather than through a client-side workaround. A registration test now pins the pipeline's `Feedback` and `Results` children, which nothing covered before. ## Running it, and what that found The demo's premise is that a language model **looks at the bin and reasons about what it sees**. Running it end to end showed it could not, for reasons no test covered, because every one of them lived between components. **The sample did not compile.** Two `CS8604` nullable errors with `TreatWarningsAsErrors`, so neither the cell server nor the demo could be started at all. Worth recording that my first explanation was wrong: CI *does* build this project - the Linux leg's `net10.0` pass compiles it, log-confirmed - so this is not a coverage gap in the workflow, and no workflow change was made. **`Pick` and `Place` never moved the arm.** They were a delay plus a gripper action, so the operations reported `Succeeded` while nothing travelled. They now solve IK once and interpolate in joint space. **And the parts never moved**: the arm swung but the bin stayed full, because nothing tied the held object to the world state. The connector now creates 11 monitored items where it created 6, and a scripted run delivers `SeqNo=151` across 10 messages where it delivered `SeqNo=3` across 1. **The frame was smuggled through a string field.** The media provider put a base64 *data URI* of the PNG into `VisionImageReferenceDataType.Uri` - a field meant to be a *reference*, while the bytes were already returned in the inline `ByteString`. Every response therefore shipped the image twice, and a 1,311,400-byte PNG became a 1,748,536-character string against a `MaxStringLength` of 65,535: **26.7x over**. That is why raising `MaxByteStringLength`, `MaxArrayLength` and `MaxMessageSize` never helped - none of them govern a `String`. Separately the MCP tool assigned raw bytes where `ImageContentBlock` requires base64, so the wire carried `"data":"�PNG..."` - every non-UTF-8 byte replaced by U+FFFD, destroying the image and inflating the response to 6.8 MB. **The camera was aimed at nothing.** The arm's home pose, the flange scan pose the Vision model declared and the joint angles in the USD stage were three independent claims about where the camera was, and they disagreed - the declared flange orientation pointed the view 86 degrees away from the projection camera. Solving them as one thing exposed two further constraints that are easy to miss: the camera has to sit off the tool axis or it photographs its own gripper, and the IK branch has to be elbow-back or a link parks under the camera and fills the frame with the arm's own upper arm. A third was a regression this branch introduced and `Opc.Ua.Robotics.Tests` caught - aiming a straight-down camera from a point on the base's own X-Z plane puts the wrist on the J4/J6 singularity, so every motion away from home fails to solve. A 15-degree camera roll, free because the camera still looks straight down, gets 25 degrees clear, which is the margin the poses before this branch had. **The frame and the detections were different images.** The sensor declared 2448x2048, the clip endpoint 1280x1024, and the renderer produced 640x512 - not even the same aspect ratio. The ground-truth detector projects through the declared intrinsics, so its boxes lived in 2448x2048 space while an agent was handed a 640x512 picture: *"pick the red cube you can see"* arrived with coordinates that pointed off the image. Everything now agrees at 612x512, an exact 4x4 bin of the native sensor with the intrinsics scaled to match; the native size stays in the model and serial number, where it describes the hardware rather than the image. **`LatestClip` was created and never written**, so it reported `Bad_NoDataAvailable` for the life of the Server and a consumer following the model - read the published frame, call the method only if there is none - never got a frame. The dispatcher now publishes a clip it has just encoded, for every Vision server rather than this sample alone. One genuine API gap turned up on the way: `OpcUaServerOptions` exposes `MaxByteStringLength`, `MaxArrayLength` and `MaxMessageSize` and **no `MaxStringLength`**, so a Server that legitimately needs a long string could not raise the limit through the hosting API at all. Added, with tests. It is not the fix for anything above - that was a design bug - but the missing knob was real. ## Not finished - **Two projects sit below the repository's 80% line coverage.** `Opc.Ua.Vision.OpenUsd` is at 71.1% — what is left only executes with a real OpenUSD stage and plugin tree, which is not on every build agent. `Opc.Ua.AI.Inference` is now at **86.7%**, up from 12.9%: the code this branch *wrote* is covered by 25 tests, and `RestChatCompletionsBackend` — previously the whole of the shortfall — is covered by 18 more against a stubbed `HttpMessageHandler`, exercising success, refusal, throttling, retry-after, timeout and cancellation without a network. Everything else clears the bar — `Opc.Ua.Vision.Server` 92.1%, `Opc.Ua.AI` 91.4%, `.Vision.Client` 88.1%, `Opc.Ua.Vision` 85.7%, `Opc.Ua.AI.Server` 80.1%, all measured with coverlet. The CI coverage gate reports itself as advisory and non-blocking. - **`SamplesCollected` is not counted here, and `docs/Vision.md` now says so.** Section 9.4 requires a Server to count a negative example (`SceneIsEmpty` / `RetractAll` carrying a `GroundTruthLabel`) exactly as it counts one carrying geometry. `VisionNodeManager` does not, and structurally cannot: `SamplesCollected` is a property of `LearningJobType`, which the *AI Model Management* companion defines, and Vision reaches the job through a `NodeId` value rather than a Reference **precisely so this model takes no dependency on the model that defines it**. What the Server does guarantee is that the negative example survives the hop intact — both flags are carried verbatim to `IVisionFeedbackSink` — so a host that binds a learning job has everything it needs to satisfy the clause on the counter it owns. Stated in the limitations rather than left implied. ## Related Issues Was stacked on #4195, now merged. No tracking issue yet for the Vision implementation itself — happy to open one if you would like the design recorded as an ADR before this goes further. ## Checklist - [x] I have signed the [CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf) and read the [CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md) doc. - [x] I have added tests that prove my fix is effective or that my feature works and increased code coverage. — *Types 8562, Server 4072, Client 2123, InformationModel 1063, Robotics 540, Tools 466, Vision 442, AI 74 and the restored Vision+Intent end-to-end suite 14/14, all green on net10.0. Only `.OpenUsd` (71.1%) is below the 80% bar — see Not finished.* - [x] I have added all necessary documentation. - [x] I have verified that my changes do not introduce (new) build or analyzer warnings. — *`dotnet build UA.slnx -c Release`: 0 errors, 0 warnings.* - [x] I ran **all** tests locally using the **UA.slnx** solution against at least .net **framework** and .net **10**, and all passed. — *net48: Types 8555, Client 2126, Vision 385 green. Two net48 Server tests fail (`CreateUserManagementSeamBindsTheModelToTheServerAsync`, and `DurableDataValueQueueVerifyReferenceBatchingAsync` only under parallel load); both were confirmed **pre-existing** by re-running them with the `IsInverse` change reverted, which fails identically.* - [ ] I fixed **all** failing and flaky tests in the CI pipelines and **all** CodeQL warnings. — *The net48 build legs failed because the restored end-to-end project used `ValueTask.FromResult` / `string.Create`, which do not exist on .NET Framework; fixed in `fb57522da` and verified building on every TFM. `DisposeDrainsHeldConnectionCallbackBeforeListenerDisposal` failed once on the Ubuntu Client leg — a 13 ms timing-sensitive reverse-connect disposal test that passes locally 2123/2123 and touches no browse paths.* - [ ] I have addressed **all** PR feedback received. ## Typed Vision-guided Robotics MCP workflows The branch now also makes the demo workflow first-class in the Full MCP profile: - replaces stringified Robotics intent and mission inputs with typed request schemas and exact name-or-NodeId selectors; - adds bounded operation/mission paging, stable step-to-operation identity, retained mission discovery, and `robotics_wait_mission`; - makes `vision_run_inference` return bounded typed detection, inspection, or segmentation summaries in one call; - adds same-session `robotics_vision_pick` to select a detection and submit Pick or Pick/Place work without implicitly taking authority, retrying, cancelling, or waiting; and - starts Publish workers for classic subscriptions so an independently launched OpenUSD viewer receives live robot and part updates. The migration guide documents the intentionally breaking MCP request-schema changes. --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: 1dab1302-19c5-4a9b-a50c-d97d389713aa Copilot-Session: a248a589-9a20-4372-868e-5d347e57001b Copilot-Session: 99d1ab42-f83a-41ab-bf3e-85bf81fadace Copilot-Session: bcbc8ac9-5abd-42a8-8bac-e10533790e2e
27 KiB
OPC UA MCP Server
The OPC UA MCP Server exposes all OPC UA Part 4 service calls as Model Context Protocol (MCP) tools. This enables AI assistants — Claude, GitHub Copilot, VS Code Copilot, Cursor, and any MCP-compatible client — to connect to OPC UA servers and interact with industrial automation systems through natural language.
What It Does
The MCP server wraps the OPC UA .NET Standard client library, translating between JSON-based MCP tool calls and OPC UA binary protocol operations. The server exposes tools through a tool profile — a named, bounded catalog selected at startup — rather than a single fixed tool count. The default full profile currently registers every tool below; running a narrower profile (core, services, administration, pubsub, diagnostics, robotics, or vision) exposes only the subset relevant to that workflow. The tables below list the complete tool surface, organized by OPC UA Part 4 service set:
| Service Set | Tools | Description |
|---|---|---|
| Connection | GetEndpoints, Connect, Disconnect, GetConnectionStatus |
Endpoint discovery and session lifecycle management |
| Attribute | Read, Write, HistoryRead, HistoryUpdate |
Read/write node attributes and historical data |
| View | Browse, BrowseNext, TranslateBrowsePaths, RegisterNodes, UnregisterNodes, QueryFirst, QueryNext |
Navigate and query the address space |
| Node Management | AddNodes, AddReferences, DeleteNodes, DeleteReferences |
Modify the address space |
| Method | Call |
Invoke OPC UA methods |
| Subscription | CreateSubscription, ModifySubscription, SetPublishingMode, Publish, Republish, DeleteSubscriptions, TransferSubscriptions |
Manage notification subscriptions |
| MonitoredItem | CreateMonitoredItems, ModifyMonitoredItems, SetMonitoringMode, SetTriggering, DeleteMonitoredItems |
Monitor data changes and events |
| Discovery | FindServers, FindServersOnNetwork, RegisterServer, RegisterServer2 |
Discover servers and register |
| PKI Management | ListCertificates, TrustCertificate, RemoveCertificate, GetPkiStorePaths |
Manage certificate trust lists |
| Configuration | GetConfiguration, SetTransportConfiguration, SetClientConfiguration, SetSecurityConfiguration, SetConfiguration |
View/modify in-memory client settings; SetConfiguration is the full-profile compatibility tool |
| NodeSet Export | ExportNodeSet, ExportNodeSetPerNamespace |
Export address space to NodeSet2 XML |
| Convenience | ReadValue, ReadValues, WriteValue, BrowseAll, CallMethod, ReadNode, Cancel |
Simplified high-level operations |
| Packet Capture | list_interfaces, start_capture, stop_capture, list_captures, get_capture, capture_now, list_active_channels, dump_keys, decode_pcap_with_keys, summarize_service_calls, replay_pcap, stop_replay, list_replays |
OPC UA-aware packet capture, offline decode, service-call summaries, replay |
All OPC UA types (NodeId, DataValue, Variant, StatusCode, etc.) are represented as JSON for LLM-friendly interaction. Variant serialization dispatches by BuiltInType, so scalar defaults such as Boolean false and numeric 0 remain JSON false / 0 instead of being confused with Variant.Null.
The packet-capture tools are described in detail in Diagnostics. For convenience the per-tool surface is:
| Tool | Description | Parameters |
|---|---|---|
list_interfaces |
Enumerates NICs available to SharpPcap; linkType may be null because enumeration does not open adapters. |
None |
start_capture |
Starts a capture session. | source: nic | inproc-client | inproc-server | replay; optional interface, filter, endpoint, limits, folder |
stop_capture |
Stops an active session and finalizes artifacts. | sessionId |
list_captures |
Lists capture sessions. | Optional state |
get_capture |
Returns an artifact or formatted analysis. | sessionId; format: pcap | pcapng | json | csv | text | service-timeline; optional packet/partial controls |
capture_now |
Starts, waits, stops, and returns output. | Capture options plus the same output format values |
list_active_channels |
Lists in-process secure channels with current tokens. | None |
dump_keys |
Emits keylog data. | Optional sessionId, format, includeExpired |
decode_pcap_with_keys |
Decodes an existing pcap and keylog offline. | pcapPath, keylogPath, format, optional maxFrames |
summarize_service_calls |
Reports service counts, latency, and errors. | sessionId or pcapPath + keylogPath, optional top |
replay_pcap |
Replays as a mock server or mock client. | pcapPath, keylogPath, mode, endpoints, speed |
stop_replay |
Stops an active replay session. | sessionId |
list_replays |
Lists active and recently-completed replay sessions. | None |
The canonical hyphenated values above are emitted on output. CLR enum
names such as InProcessClient and ServiceTimeline remain accepted
on input.
Tool Profiles
The server selects its tool catalog through a tool profile — a bounded set of tool classes registered at startup. Profiles let a client request only the tools it needs (smaller catalogs are easier for an LLM to reason about and reduce prompt size), while full preserves the complete surface for clients that want everything.
| Profile | Tool classes registered | Typical use case |
|---|---|---|
core |
Configuration, Connection, Convenience | Minimal footprint: connect, read/write values, adjust settings |
services |
Attribute, Configuration, Connection, Convenience, Discovery, Method, MonitoredItem, Node Management, Subscription, View | Full OPC UA Part 4 client workflows without PKI/PubSub/packet capture |
administration |
Configuration, Connection, NodeSet Export, PKI Management | Certificate trust management and NodeSet export |
pubsub |
PubSub runtime, discovery, action, and capture tools (plus PubSub decode when diagnostics tools are enabled) | Part 14 PubSub publish/subscribe, discovery, and capture workflows |
diagnostics |
Connection, Packet Capture (plus decode/replay when diagnostics tools are enabled) | OPC UA-aware packet capture, offline decode, and replay |
robotics |
Connection plus Robot Intent discovery, paged monitoring, control, mission and Vision-guided Pick tools | Commanding and monitoring a Robot Intent controller |
vision |
Connection plus the Vision discovery, monitoring, seeing, inference, feedback and geometry tools | Perception-driven agents that need to see through a Vision server, compose poses across the §5.12 frame graph, run or submit inference, and (when composed with robotics) act on what they see — see the Vision developer guide |
full (default) |
Every tool class above | Unrestricted access; the current-major default so existing integrations keep working unchanged |
full is the default for the current major version — core and the other bounded profiles are opt-in. Select a profile with:
- The
--profileCLI option, e.g.opcua-mcp --profile core - The
McpServer:ToolProfileconfiguration value - The
OPCUA_MCP_TOOL_PROFILEenvironment variable
Profiles compose. A --profile value can name more than one bounded profile at a time — the BinPickingClient sample runs --profile vision,robotics and exposes both catalogs from the same MCP host, deduplicating the shared Connection tools. The composed set uses the WithOpcUaCoreTools(McpToolProfileSet) / WithOpcUaVisionTools(McpToolProfileSet) / WithOpcUaRoboticsTools(McpToolProfileSet) overloads, and the core-tools overload owns the single ConnectionTools registration across every package that references the same MCP server. See the Vision developer guide for the composed 64-tool example and the BinPickingClient sample for the running catalog.
Because the exact number of tools in each profile (and in full) changes as tools are added or removed, this document intentionally does not hard-code a tool count. Use the tables above (or tools/list) to enumerate the tools actually exposed by a running server.
Vision-guided Robotics
robotics_vision_pick closes the common perception-to-action path without
making an agent copy a result NodeId and several resource NodeIds between tool
calls. It runs one detection inference through Opc.Ua.Vision.Client, on the
same named OPC UA session as the Robot Intent controller, then submits either
one Pick or a two-step Pick/Place mission:
{
"request": {
"controller": "BinPickingController",
"pipeline": "BinPickingPipeline",
"source": "Bin",
"tool": "ParallelGripper",
"destination": "Fixture",
"classLabel": "RedCube",
"minimumConfidence": 0.9,
"missionId": "place-red-cube"
}
}
Detection selection is deterministic: exact DetectionId/ClassLabel filters and the confidence threshold are applied first, then highest confidence wins with ordinal DetectionId and original result order as tie-breakers. The result contains Vision result/pipeline/sensor/model/frame provenance, the selected pose, and the authoritative intent or mission handle. The helper does not request authority, wait, retry, cancel, or reinterpret a server refusal.
Resources
The MCP server exposes connected sessions as MCP resources, enabling the LLM to discover, inspect, and subscribe to session state.
| Resource URI | Type | Description |
|---|---|---|
opcua://sessions |
Direct | List all active sessions with connection status |
opcua://sessions/{name} |
Template | Full details of a named session (endpoint, security, namespaces) |
opcua://sessions/{name}/namespaces |
Template | Server namespace table for a session |
Multi-Session Support
The server supports multiple simultaneous sessions to different OPC UA servers. Each session is identified by a name.
Tool: Connect
endpointUrl: "opc.tcp://server1:62541/ReferenceServer"
name: "refserver" (optional — auto-generated from hostname if omitted)
autoAcceptCerts: true
Tool: Connect
endpointUrl: "opc.tcp://plc1:4840"
name: "plc1"
Tool: Browse
nodeId: "i=85"
sessionName: "refserver" (optional — uses the only session if there's just one)
Tool: ReadValue
nodeId: "ns=2;s=Temperature"
sessionName: "plc1"
Sessions are listed via resources/list and detailed via resources/read.
Installation
Option 1: Install as a .NET global tool (recommended)
dotnet tool install --global OPCFoundation.NetStandard.Opc.Ua.Mcp
After installation, the opcua-mcp command is available globally.
Option 2: Run from source
cd tools/Opc.Ua.Mcp
dotnet run -c Release
Option 3: Install from local build
dotnet pack tools/Opc.Ua.Mcp/Opc.Ua.Mcp.csproj -c Release
dotnet tool install --global --add-source tools/Opc.Ua.Mcp/bin/Release OPCFoundation.NetStandard.Opc.Ua.Mcp
Configuration
Claude Desktop
Add to your claude_desktop_config.json (typically at %APPDATA%\Claude\claude_desktop_config.json on Windows or ~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"opcua": {
"command": "opcua-mcp"
}
}
}
VS Code / GitHub Copilot
Add to your workspace .vscode/mcp.json:
{
"servers": {
"opcua": {
"command": "opcua-mcp"
}
}
}
Cursor
Add to your Cursor MCP settings:
{
"mcpServers": {
"opcua": {
"command": "opcua-mcp"
}
}
}
HTTP Transport (for remote clients)
By default, the server uses stdio transport for local tool integration. For remote clients, use the Streamable HTTP transport, exposed only at the /mcp path (there is no root route):
opcua-mcp --transport http --port 5100
The server listens at http://localhost:5100/mcp. --transport sse is a deprecated alias for http kept for the current major version only — prefer http in new configurations.
Usage
Typical Workflow
1. Discover endpoints (no session required):
Tool: GetEndpoints
endpointUrl: "opc.tcp://localhost:62541/Quickstarts/ReferenceServer"
2. Connect to an OPC UA server (auto-select most secure, anonymous):
Tool: Connect
endpointUrl: "opc.tcp://localhost:62541/Quickstarts/ReferenceServer"
autoAcceptCerts: true
Or connect with specific security and authentication:
Tool: Connect
endpointUrl: "opc.tcp://localhost:62541/Quickstarts/ReferenceServer"
securityMode: "SignAndEncrypt"
securityPolicy: "Basic256Sha256"
authType: "Username"
username: "admin"
password: "password"
autoAcceptCerts: true
2. Explore the address space:
Tool: BrowseAll
nodeId: "i=85" (Objects folder)
maxDepth: 2
maxResults: 50
3. Read values:
Tool: ReadValue
nodeId: "ns=2;s=MyTemperatureSensor"
4. Write values:
Tool: WriteValue
nodeId: "ns=2;s=MySetpoint"
value: "72.5"
dataType: "Double"
5. Call a method:
Tool: CallMethod
objectId: "ns=2;s=MyMachine"
methodId: "ns=2;s=StartProcess"
inputArguments: ["fast", "true"]
6. Monitor changes:
Tool: CreateSubscription
publishingInterval: 1000
Tool: CreateMonitoredItems
subscriptionId: <from above>
nodeIds: ["ns=2;s=Temperature", "ns=2;s=Pressure"]
Tool: Publish
(retrieves queued notifications)
7. Manage PKI (trust rejected certificates):
Tool: ListCertificates
store: "Rejected"
Tool: TrustCertificate
thumbprint: "A1B2C3..." (from ListCertificates results)
Tool: GetPkiStorePaths
(shows where certificate stores are located on disk)
8. Adjust configuration for current session:
Tool: GetConfiguration
(view current settings)
Tool: SetConfiguration
operationTimeout: 60000
maxArrayLength: 131072
autoAcceptUntrustedCertificates: true
9. Export the server's address space to NodeSet2 XML:
Tool: ExportNodeSet
filePath: "C:\\export\\server-nodeset.xml"
startingNodeId: "i=85" (Objects folder)
exportMode: "Complete" (includes values)
Or export split by namespace (one file per companion spec):
Tool: ExportNodeSetPerNamespace
outputDirectory: "C:\\export\\namespaces"
10. Disconnect:
Tool: Disconnect
NodeId Formats
The MCP server accepts NodeIds in standard OPC UA string format:
| Format | Example | Description |
|---|---|---|
| Numeric | i=2258 |
Numeric identifier in namespace 0 |
| Numeric with namespace | ns=2;i=1001 |
Numeric identifier in namespace 2 |
| String | ns=2;s=MyVariable |
String identifier |
| GUID | ns=2;g=12345678-1234-1234-1234-123456789abc |
GUID identifier |
| Opaque | ns=2;b=Base64EncodedData |
ByteString identifier |
Common Well-Known NodeIds
| NodeId | Description |
|---|---|
i=84 |
Root node |
i=85 |
Objects folder |
i=86 |
Types folder |
i=87 |
Views folder |
i=2253 |
Server object |
i=2258 |
Server/ServerStatus/CurrentTime |
Error Handling
When an OPC UA service returns an error, tools return a structured JSON response:
{
"error": true,
"statusCode": "BadNodeIdUnknown",
"message": "The node id refers to a node that does not exist in the server address space."
}
This is normal behavior — not all servers support all services. Common status codes:
| Status Code | Meaning |
|---|---|
BadServiceUnsupported |
Server doesn't implement this service |
BadNodeIdUnknown |
NodeId doesn't exist |
BadNotWritable |
Node attribute is read-only |
BadMethodInvalid |
Method not found on the specified object |
BadUserAccessDenied |
Insufficient permissions |
PubSub Tools
In addition to the client services above, the server exposes OPC UA PubSub
(Part 14) tools, backed by Opc.Ua.PubSub and
Opc.Ua.PubSub.Diagnostics. See
Diagnostics.md §5 for
the capture / dissection details.
Configuration and Security Key Service methods. PubSub configuration
(AddConnection, AddWriterGroup, AddReaderGroup, AddDataSetWriter,
AddDataSetReader, Status.Enable / Disable) and the Security Key Service
(GetSecurityKeys, AddSecurityGroup / RemoveSecurityGroup) are standard
server-side PublishSubscribe object methods, so they are invoked with the
generic Call tool rather than dedicated wrappers — pass the
PublishSubscribe object NodeId (or the target connection / group NodeId) and
the corresponding method NodeId (e.g. i=14443 for
PublishSubscribe_AddConnection, i=15215 for
PublishSubscribe_GetSecurityKeys).
In-process publish/subscribe runtime:
| Tool | Purpose |
|---|---|
pubsub_runtime_start_publisher / pubsub_runtime_start_subscriber |
Start an in-process UDP publisher / subscriber |
pubsub_runtime_publish |
Publish a DataSet update |
pubsub_runtime_read_received |
Read DataSets received by the subscriber |
pubsub_runtime_status / pubsub_runtime_stop |
Status / stop the runtime |
Discovery (Part 14 §7.2.4.6 — send a discovery request from the active runtime and collect publisher responses):
| Tool | Purpose |
|---|---|
pubsub_discover_metadata |
Learn the field-level schema of a DataSetWriter (names, field count) |
pubsub_discover_writer_config |
Learn a publisher's WriterGroupId and DataSetWriterIds |
pubsub_discover_publisher_endpoints |
Learn a publisher's transport endpoint URLs |
Actions (Part 14 §7.2.5.6 — request/response over PubSub):
| Tool | Purpose |
|---|---|
pubsub_invoke_action |
Invoke an action target and await the correlated response |
pubsub_register_action_responder |
Register a demo/echo responder for round-trip testing |
pubsub_bind_action_method |
Bind an action to a server method (ObjectId/MethodId) |
pubsub_list_action_targets / pubsub_list_action_responders |
List known targets / registered responders |
Capture and dissection:
| Tool | Purpose |
|---|---|
pubsub_start_capture / pubsub_stop_capture / pubsub_capture_status |
Manage an in-process PubSub capture session |
pubsub_write_pcap |
Flush captured frames to .pcap / .pcapng |
pubsub_dissect_capture |
Dissect captured frames (decrypts encrypted UADP when a key log is supplied) |
pubsub_decode_pcap |
Decode a libpcap file of UDP PubSub traffic |
pubsub_load_keylog |
Load a PubSub key log for offline decryption |
Architecture
The MCP tools ship as six libraries plus the executable that composes them. The executable owns only transport, logging and CLI plumbing; every tool lives in a library that an application can reference on its own.
tools/
├── Opc.Ua.Mcp.Core/ # Part 4 service tools, session manager, options, filters
│ ├── OpcUaMcpCoreExtensions.cs # AddOpcUaMcpCore, WithOpcUaCoreTools, WithOpcUaMcpFilters
│ ├── OpcUaSessionManager.cs # OPC UA client session lifecycle
│ ├── McpCapturePath.cs # Path-traversal guard shared by the capture packages
│ ├── Tools/
│ │ ├── ConnectionTools.cs # GetEndpoints, Connect, Disconnect, GetConnectionStatus
│ │ ├── AttributeServiceTools.cs # Read, Write, HistoryRead, HistoryUpdate
│ │ ├── ViewServiceTools.cs # Browse, BrowseNext, TranslateBrowsePaths, etc.
│ │ ├── NodeManagementServiceTools.cs# AddNodes, AddReferences, DeleteNodes, etc.
│ │ ├── MethodServiceTools.cs # Call
│ │ ├── SubscriptionServiceTools.cs # CreateSubscription, Publish, etc.
│ │ ├── MonitoredItemServiceTools.cs # CreateMonitoredItems, etc.
│ │ ├── DiscoveryServiceTools.cs # FindServers, RegisterServer, etc.
│ │ ├── PkiTools.cs # ListCertificates, TrustCertificate, etc.
│ │ ├── ConfigurationTools.cs # Full-profile compatibility configuration tools
│ │ ├── ConfigurationReadTools.cs # Profile-safe configuration reader
│ │ ├── ConfigurationUpdateTools.cs # Focused transport/client/security setters
│ │ ├── NodeSetExportTools.cs # ExportNodeSet, ExportNodeSetPerNamespace
│ │ └── ConvenienceTools.cs # ReadValue, BrowseAll, CallMethod, etc.
│ └── Serialization/
│ └── OpcUaJsonHelper.cs # OPC UA ↔ JSON type conversion
├── Opc.Ua.Mcp.PubSub/ # PubSub runtime, actions and discovery
│ ├── PubSubRuntimeManager.cs
│ └── Tools/{PubSubRuntime,PubSubAction,PubSubDiscovery}Tools.cs
├── Opc.Ua.Mcp.Diagnostics/ # UA-TCP capture, decode and replay
│ └── Tools/{PacketCapture,PacketDecode,PacketReplay}Tools.cs
├── Opc.Ua.Mcp.PubSub.Diagnostics/ # PubSub capture and decode
│ └── Tools/{PubSubCapture,PubSubDecode}Tools.cs
├── Opc.Ua.Mcp.Robotics/ # Robot Intent plus same-session Vision-guided picking
│ ├── RoboticsIntentManager.cs
│ ├── VisionGuidedRoboticsManager.cs
│ └── Tools/Robotics{Discovery,Monitoring,Control,Mission,Vision}Tools.cs
├── Opc.Ua.Mcp.Vision/ # Vision discovery, monitoring, seeing, inference, feedback, geometry
│ ├── VisionClientAccessor.cs
│ └── Tools/Vision{Discovery,Monitoring,Seeing,Inference,Feedback,Geometry}Tools.cs
└── Opc.Ua.Mcp/ # .NET 10 project, packaged as dotnet tool
├── Program.cs # Entry point, stdio + Streamable HTTP transport (/mcp)
├── McpHostBuilder.cs # Composes the six libraries
├── Opc.Ua.Mcp.Config.xml # OPC UA client application config
└── .mcp/server.json # MCP server manifest for NuGet discovery
Packages
| Package | Tools | Depends on |
|---|---|---|
OPCFoundation.NetStandard.Opc.Ua.Mcp.Core |
Part 4 services, connection, configuration, PKI, NodeSet export | Opc.Ua.Core, .Configuration, .Client |
OPCFoundation.NetStandard.Opc.Ua.Mcp.PubSub |
PubSub runtime, actions, discovery | Core + Opc.Ua.PubSub |
OPCFoundation.NetStandard.Opc.Ua.Mcp.Diagnostics |
UA-TCP capture, decode, replay | Core + Opc.Ua.Core.Diagnostics |
OPCFoundation.NetStandard.Opc.Ua.Mcp.PubSub.Diagnostics |
PubSub capture, decode | Core + Opc.Ua.PubSub.Diagnostics |
OPCFoundation.NetStandard.Opc.Ua.Mcp.Robotics |
Robot Intent discovery, typed control/missions, paged monitoring, Vision-guided Pick | Core + Opc.Ua.Robotics.Client + Opc.Ua.Vision.Client |
OPCFoundation.NetStandard.Opc.Ua.Mcp.Vision |
Vision discovery, monitoring, seeing (vision_get_frame returns an MCP ImageContentBlock), inference, off-server feedback, §5.12 pose composition |
Core + Opc.Ua.Vision.Client |
OPCFoundation.NetStandard.Opc.Ua.Mcp |
the ready-to-run opcua-mcp tool |
all of the above |
The libraries multi-target net8.0;net9.0;net10.0; the executable targets
net10.0.
Embedding the tools in your own MCP server
An application that wants OPC UA tools and its own application-level tools
composes them rather than shelling out to opcua-mcp:
using Microsoft.Extensions.DependencyInjection;
using Opc.Ua.Mcp;
builder.Services.AddOpcUaMcpCore();
builder.Services.AddMcpServer()
.WithStdioServerTransport()
.WithOpcUaMcpFilters()
.WithOpcUaCoreTools(McpToolProfile.Services)
.WithTools<MyApplicationTools>();
Add any of the other packages the same way — each contributes a service registration and a tool registration:
builder.Services.AddOpcUaMcpPubSub();
builder.Services.AddOpcUaMcpDiagnostics();
builder.Services.AddOpcUaMcpPubSubDiagnostics();
builder.Services.AddOpcUaMcpRobotics();
builder.Services.AddOpcUaMcpVision();
mcp.WithOpcUaPubSubTools(profile)
.WithOpcUaDiagnosticsTools(profile, diagnosticsEnabled)
.WithOpcUaPubSubDiagnosticsTools(profile, diagnosticsEnabled)
.WithOpcUaRoboticsTools(profile)
.WithOpcUaVisionTools(profile);
WithOpcUaMcpFilters registers the request and schema filters that make tool
errors actionable and tool schemas explicit. Call it once per server, even when
several OPC UA tool packages are composed.
McpToolProfile is shared vocabulary that lives in Core, and each package maps
the profile to its own tools. A profile a package does not own contributes
nothing rather than failing, so the same profile value can be passed to every
package a host references — Full in a host that never referenced
Opc.Ua.Mcp.Diagnostics simply yields no capture tools.
Bounded profiles that own their own connection tools — Vision in the
example above — carry ConnectionTools themselves in the single-profile
overload of WithOpcUa...Tools. When two or more bounded profiles are
composed through the McpToolProfileSet overloads (for example the
vision,robotics composition the BinPickingClient
sample runs), the corresponding WithOpcUaCoreTools(McpToolProfileSet)
overload owns and deduplicates ConnectionTools across every package.
Each Vision or Robotics package's McpToolProfileSet overload never
registers ConnectionTools directly, so the composed catalog contains
one Connection surface, not several.
The capture tool classes stay internal and are reachable only through their
registration extensions.
Security Notes
- The
autoAcceptCertsparameter is for testing only. In production, configure proper certificate trust using the OPC UA certificate stores under%LocalApplicationData%/OPC Foundation/pki/. - The server manages a single OPC UA session at a time. Disconnect before connecting to a different server.
- Application certificates are automatically created on first use and stored in the local certificate store.
- Logs are written to
%LocalApplicationData%/OPC Foundation/Logs/McpServer.log.txt.
Agent-Usability Quality Gate
Contributors can run the same deterministic static and live-probe grading used in CI:
./tools/Opc.Ua.Mcp/Test-McpGrade.ps1
The script builds the server, checks out mcpgrade at the reviewed commit pinned in the script,
grades the core and full Streamable HTTP catalogs, and probes the full stdio catalog. Reports
are written under artifacts/mcpgrade by default.
The repository .mcpgraderc.json disables N002 after descriptions have been disambiguated.
RegisterServer/RegisterServer2 are OPC UA standard service names, while
ReadValue/ReadValues and GetConfiguration/SetConfiguration are compatibility-sensitive
singular/plural and get/set pairs. These names must not be changed solely to satisfy edit-distance
heuristics.
Requirements
- .NET 10 SDK or later
- An OPC UA server to connect to