Generated banner for Matlab Use Opcua Client
Generated logo for Matlab Use Opcua Client

Matlab Use Opcua Client

MathWorksOfficialCreated by MathWorks

  • Skill
  • Tool integration
  • Automation and integrations
  • BSD-2-Clause
  • No issues found

From the author

Discover OPC UA servers, connect MATLAB clients, and browse/navigate server nodes using opcuaserverinfo, the Local Discovery Service (LDS), opcua, connect, setSecurityModel, certificate-trust functions, findNodeById, opcuanode, and Namespace/Children traversal. Use when finding OPC UA servers on the network, querying endpoints and security policies, connecting to a server, authenticating with username/password or certificates, configuring security modes, handling certificate-trust or hostname-mismatch errors, troubleshooting failed connections or empty discovery, inspecting an OPC UA certificate (.der/.pem), browsing an address space, finding nodes by name or NodeId, navigating node hierarchies, invoking method nodes, or batch-processing large namespaces. Trigger on: opcuaserverinfo, LDS, opcua, opc.ua.Client, setSecurityModel, opc.ua.trustServerCertificate, OPC UA certificate, findNodeById, opcuanode, browse OPC UA, find node, OPC UA namespace, OPC UA method node, Industrial Communication Toolbox.
— the description by MathWorks

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured approach for using the Industrial Communication Toolbox to interact with OPC UA servers. It covers the full lifecycle of OPC UA communication, including network discovery via the Local Discovery Service (LDS), secure client-server connection establishment, certificate management, and programmatic navigation of complex server address spaces. The skill emphasizes robust error handling, security best practices, and efficient node traversal patterns to ensure reliable data access in industrial environments.

What it does

  • Discovers OPC UA servers on a network using LDS or direct endpoint URLs.
  • Establishes secure client connections with support for username/password or certificate-based authentication.
  • Configures message security modes and channel policies for encrypted communication.
  • Provides workflows for resolving common certificate trust and hostname mismatch errors.
  • Enables programmatic browsing and navigation of server address spaces via node hierarchies.
  • Supports method invocation and batch-processing of large namespaces.

When to use it

  • When you need to connect MATLAB to industrial OPC UA servers for data acquisition.
  • When troubleshooting connection failures, certificate trust issues, or empty discovery results.
  • When you need to programmatically explore or search for specific nodes within an OPC UA server.
  • When implementing secure communication between MATLAB and industrial hardware or software.

Advantages

  • Standardizes connection and security patterns to prevent common configuration errors.
  • Provides clear escalation paths for resolving certificate trust and authentication issues.
  • Promotes efficient node navigation by avoiding blocking GUI-based browsing in scripts.
  • Ensures compatibility with modern OPC UA security standards and best practices.

Usage examples

“How do I find all OPC UA servers running on my local machine?”
The agent will guide you to use opcuaserverinfo('localhost') to query the Local Discovery Service and return a list of registered servers.
“My connection to the OPC UA server is failing with a certificate trust error.”
The agent will instruct you to use opc.ua.trustServerCertificate with the path to the server's .der certificate to add it to the MATLAB trusted store.
“How can I find a specific node in the OPC UA namespace without using the GUI?”
The agent will provide a script pattern to traverse the uaClient.Namespace and .Children properties level-by-level to locate the target node.
“How do I securely connect to an OPC UA server using a certificate?”
The agent will show you the correct connect() function signature that accepts the public key, private key, and password.

Install

  1. Download the skill as a ZIP:

    https://mp-staging.autogineer.com/agent-skills/matlab/matlab-use-opcua-client/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip matlab-use-opcua-client.zip -d .agents/skills

Documentation by MathWorks

OPC UA Discovery, Connection, and Node Navigation

Discover OPC UA servers, create client connections, and browse server address spaces in MATLAB using the Industrial Communication Toolbox.

Internal Constraints

These constraints govern YOUR code generation and recommendations. Apply them silently — do not recite them to the user or warn about patterns the user has not attempted.

  1. connect has exactly three valid signatures — no others exist:

    • connect(uaClient) — anonymous

    • connect(uaClient, userName, password) — positional strings

    • connect(uaClient, publicKeyFile, privateKeyFile, privateKeyPassword) — positional strings

    • There are NO Name-Value pair arguments to connect. Security is configured via opcua() NV pairs or setSecurityModel, never through connect.

  2. opcua() defaults to the highest available security. Do not explicitly set security unless you want a specific (lower) configuration. Never use setSecurityModel(uaClient, "Best") — it is redundant.

  3. opcuaserverinfo has exactly two valid syntaxes:

    • opcuaserverinfo(hostname) — query LDS on a host

    • opcuaserverinfo(discoveryUrl) — query a specific endpoint URL

    • There is NO opcuaserverinfo(hostname, port) form. To specify a port: opcuaserverinfo('opc.tcp://host:port').

  4. LDS-based discovery returns all registered servers from a single call. Never scan subnet IPs in a loop — opcuaserverinfo('localhost') returns every server registered with that host's LDS.

  5. Certificate trust escalation order (never skip steps):

    1. opc.ua.trustServerCertificate(certPath) — always first (R2026a+)

    2. opcua(..., "TrustServerTemporarily", true) — only if cert file unavailable

    3. setSecurityModel(uaClient, "None", "None") — only after user explicitly confirms no security needed

  6. Property correctness:

    • opc.ua.ServerInfo has Description, not Name (which belongs to opc.ua.Client).

    • EndpointUrl belongs to opc.ua.EndpointDescription, not ServerInfo.

  7. Do not move or copy certificate files without user confirmation. Tell the user which file to move and where, then execute only after they confirm.

  8. Do not mention TrustServerTemporarily when the issue is the server rejecting the client certificate — it only controls client- side trust and is irrelevant in that direction. Simply omit it.

  9. browseNamespace is GUI-only — never call it in scripts or agent workflows. It opens an interactive dialog that blocks the MATLAB session. Use uaClient.Namespace and .Children traversal instead.

  10. opcuanode does NOT accept browse paths. Passing a slash- separated string (e.g., 'Demo/Mass/Nested/7') silently creates a node with NodeType: 'Unknown'. Use .Children level-by-level.

  11. Check a method node's Parent property and signature before invoke(). If Parent is empty, invoke() fails with "Specified node has no parent information" — re-resolve the node via findNodeById, which retains parent info. If Parent is non-empty, invoke it directly. Do not unconditionally avoid opcuanode for method nodes; branch on whether the node has a parent. Before calling invoke, inspect NumInputs and NumOutputs to verify the argument count matches your intended call.

  12. Before iterating any .Children array, issue a separate tool call that only counts nodes. Never combine counting and processing in the same tool call. Process in batches of 200 with progress reporting.

  13. Never search the entire namespace. If the user does not provide a path or parent folder, ask them to specify one. List top-level nodes to help them narrow scope. Skip the Server folder (ns=0 infrastructure nodes) unless the user explicitly asks about server properties.

  14. opcua() caches endpoints at construction time. If the server's available policies change after client creation, the existing client object will not reflect them. Recreate the client with opcua(url) to re-discover endpoints. Explain this to the user when they ask about switching to a newly-available policy.

When to Use

  • Discovering OPC UA servers on the network (endpoint URL unknown, or user explicitly requests discovery given a hostname or discovery URL)

  • Getting server endpoint details and supported security policies

  • Creating an OPC UA client connection to a server

  • Authenticating with username/password or user certificates

  • Configuring message security mode and channel security policy

  • Handling "server certificate not trusted" errors

  • Handling "client certificate rejected by server" errors

  • Fixing hostname mismatch warnings

  • Troubleshooting OPC UA connection failures or empty discovery results

  • Inspecting an OPC UA certificate (.der/.pem) for compliance issues

  • Browsing an OPC UA server's address space programmatically

  • Searching for nodes by name, partial name, or NodeId

  • Navigating a node hierarchy to reach a specific node

  • Accessing a node directly by namespace index and identifier

  • Goal-driven node discovery (e.g., "find all temperature sensors")

  • Discovering nodes before reading, writing, invoking, or subscribing

When NOT to Use

  • OPC Classic (OPC DA / OPC HDA) connections

  • PI Data Archive / PI AF / OSIsoft / AVEVA PI systems

  • Non-OPC UA protocols (Modbus, MQTT)

  • OPC UA server-side development

References

Load the relevant reference file for detailed procedures:

TaskReference
Server discovery, LDS setup, empty discovery resultsreferences/lds-setup-and-troubleshooting.md
Server cert trust, client cert export, cert inspectionreferences/certificate-trust-workflows.md
Connection errors, server logs, diagnostic workflowreferences/troubleshooting-connection-errors.md
Node navigation patterns, batch processing, method invocationreferences/node-navigation.md
Function syntax for findNodeById, opcuanode, getNamespacereferences/node-functions-reference.md
Syntax pitfalls and invalid API patternsreferences/common-mistakes.md

Workflow

0. Discover servers (optional)

Use this step when the endpoint URL is not known, or when the user explicitly asks to discover servers given a hostname or discovery URL. Skip this step if the endpoint URL is already known.

Prerequisites — before calling opcuaserverinfo, ensure:

  1. The OPC UA Local Discovery Service (LDS) is installed and running

  2. The target server is registered with the LDS

  3. The server's certificate is trusted by the LDS certificate store at C:\ProgramData\OPC Foundation\UA\pki\trusted\certs\

See references/lds-setup-and-troubleshooting.md for details.

% TEMPLATE — not executable (shows alternative discovery forms)
% LDS-based discovery (preferred — finds all registered servers)
serverInfo = opcuaserverinfo('localhost');

% Direct endpoint discovery (when you know the server URL)
serverInfo = opcuaserverinfo('opc.tcp://myserver:53530/OPCUA/SimulationServer');

% Pass discovery result directly to opcua()
uaClient = opcua(serverInfo(1));
connect(uaClient);
1. Create the OPC UA client
serverUrl = "opc.tcp://hostname:port/path";
uaClient = opcua(serverUrl);

The opcua function also accepts a ServerInfo object directly from opcuaserverinfo.

2. Configure security (only if non-default needed)
% TEMPLATE — not executable (shows two alternative security-config forms)
% R2025a+ (preferred) — Name-Value pairs in constructor
uaClient = opcua(serverUrl, ...
    MessageSecurityMode="Sign", ...
    ChannelSecurityPolicy="Basic256Sha256");

% R2020a+ (backward-compatible) — setSecurityModel after construction
uaClient = opcua(serverUrl);
setSecurityModel(uaClient, "Sign", "Basic256Sha256");
3. Handle certificate trust (if needed)

If the server's certificate is not yet trusted by MATLAB, the connection will fail. Follow the escalation order in Internal Constraints. Load references/certificate-trust-workflows.md for details.

4. Connect
connect(uaClient);                                        % anonymous
connect(uaClient, "myuser", "mypassword");               % username/password
connect(uaClient, "cert.der", "key.pem", "keypass");     % certificate
5. Verify connection
if isConnected(uaClient)
    fprintf("Connected to %s\n", uaClient.EndpointUrl);
end
6. Find nodes (once connected)

Load references/node-navigation.md for full decision logic, workflows, batch processing, and method invocation patterns.

7. Disconnect
disconnect(uaClient);

Key Functions

FunctionPurposeAvailable From
opcuaserverinfoDiscover OPC UA servers via LDS or direct URLR2015b
opcuaCreate OPC UA client (from URL or ServerInfo)R2015b
connectConnect to serverR2015b
disconnectDisconnect from serverR2015b
isConnectedCheck connection statusR2015b
setSecurityModelConfigure security mode/policyR2020a
opc.ua.exportClientCertificateExport MATLAB client cert to fileR2020a
opc.ua.trustServerCertificateTrust a server cert (file path)R2026a
opc.ua.rejectServerCertificateReject a server cert (file path)R2026a
findDescriptionFilter ServerInfo array by description textR2015b
findAuthenticationFilter ServerInfo array by auth typeR2015b
findNodeByIdFind node by namespace index and identifier (retains parent)R2015b
opcuanodeCreate node directly from known NodeId (check Parent before invoke)R2015b
getNamespaceGet one layer of namespace tree (or use uaClient.Namespace)R2015b

Properties Quick Reference

opc.ua.Client
PropertyTypeDescription
HostnamestringServer hostname
PortdoubleServer port
NamestringClient name
EndpointUrlstringSelected endpoint URL
StatusstringConnection status
TimeoutdoubleConnection timeout (seconds)
MessageSecurityModeenumActive security mode
ChannelSecurityPolicyenumActive channel policy
UserAuthTypescellAvailable auth types on server
EndpointsarrayAvailable endpoint descriptions

Does NOT have: UserName, Password, IsConnected, Security, SecurityMode, SecurityPolicy, Certificate, PrivateKey.

Use isConnected(uaClient) (method) to check connection status.

opc.ua.ServerInfo
PropertyTypeDescription
HostnamecharHost name
PortdoubleTCP port
DescriptioncharHuman-readable server description
UserTokenTypescellSupported auth types
BestMessageSecurityenumHighest message security
BestChannelSecurityenumHighest channel security policy
Endpointsarrayopc.ua.EndpointDescription objects
opc.ua.EndpointDescription
PropertyTypeDescription
EndpointUrlcharFull endpoint URL
MessageSecurityModeenumSecurity mode for this endpoint
ChannelSecurityPolicyenumChannel security policy
UserAuthTypescellAuth types on this endpoint
opc.ua.Node
PropertyTypeDescription
NamecharNode display name
NodeTypechar'Object', 'Variable', 'Method', or 'Unknown'
NamespaceIndexdoubleNamespace index
IdentifiervariesNode identifier (numeric or string)
ChildrenarrayChild nodes (lazy-loaded from server)
ParentnodeParent node (may be empty for opcuanode-created nodes; check before invoke)
ServerDataTypecharData type for Variable nodes
NumInputsdoubleNumber of input arguments (Method nodes)
NumOutputsdoubleNumber of output arguments (Method nodes)

Patterns

Discovery
% TEMPLATE — not executable (shows discover-only vs discover-and-connect)
% Discover all servers via LDS
serverInfo = opcuaserverinfo('localhost');

% Discover and connect
serverInfo = opcuaserverinfo('localhost');
uaClient = opcua(serverInfo(1));
connect(uaClient);
Connection with authentication
% Default (highest) security, anonymous
uaClient = opcua("opc.tcp://myserver:53530/OPCUA/SimulationServer");
connect(uaClient);

% Username/password
connect(uaClient, "myuser", "mypassword");

% User certificate
connect(uaClient, "C:/certs/user.der", "C:/certs/user.key", "keypassword");
Hostname mismatch fix
% TEMPLATE — not executable (shows R2025a+ vs pre-R2025a forms)
% R2025a+
uaClient = opcua("opc.tcp://myserver:53530/OPCUA/SimulationServer", ...
    UseDiscoveryHostname=true);

% Pre-R2025a — resolve via discovery
serverInfo = opcuaserverinfo("myserver");
uaClient = opcua(serverInfo(1));
connect(uaClient);
Certificate inspection

Load references/certificate-trust-workflows.md, then run:

inspectOpcUaCertificate("path/to/server_cert.der");
Navigate a browse path
ns = uaClient.Namespace;
idx = arrayfun(@(n) strcmp(n.Name, 'Demo'), ns);
level1 = ns(idx);

children = level1.Children;
idx = arrayfun(@(n) strcmp(n.Name, 'Mass'), children);
level2 = children(idx);
Direct node lookup by NodeId
% TEMPLATE — not executable (shows two alternative lookup forms)
% Quick access from a known NodeId
node = opcuanode(3, 1002, uaClient);

% Always retains parent info
node = findNodeById(uaClient.Namespace, 3, 1002);
Find and invoke a method node

invoke requires parent information. Before invoking, check the node's Parent property — if it is empty, re-resolve the node via findNodeById (or .Children navigation) so parent info is populated; if it is non-empty, invoke directly.

methodNode = opcuanode(6, 'MyMethod', uaClient);

% Ensure parent info is present before invoking
if isempty(methodNode.Parent)
    methodNode = findNodeById(uaClient.Namespace, 6, 'MyMethod');
end

% Verify argument count before calling invoke
fprintf("Inputs: %d, Outputs: %d\n", methodNode.NumInputs, methodNode.NumOutputs);

[result, timestamp, quality] = invoke(uaClient, methodNode, arg1, arg2);

Troubleshooting Quick Reference

ErrorFix
opcuaserverinfo returns emptyCheck LDS prerequisites; see references/lds-setup-and-troubleshooting.md
"Server certificate not trusted"opc.ua.trustServerCertificate(certPath)
"Client certificate rejected"Export via opc.ua.exportClientCertificate, add to server
"BadIdentityTokenRejected"Check uaClient.UserAuthTypes
"Hostname mismatch" warningUseDiscoveryHostname=true (R2025a+)
"BadSecurityChecksFailed"Run inspectOpcUaCertificate; see references/troubleshooting-connection-errors.md
NodeType: 'Unknown' after opcuanodeNode doesn't exist or path passed as id; use .Children traversal
"Specified node has no parent information"Node's Parent is empty; re-resolve via findNodeById (or .Children) before invoke
browseNamespace blocks sessionNever use; replace with uaClient.Namespace + .Children

For detailed error-to-fix mapping, load references/troubleshooting-connection-errors.md.


Copyright 2026 The MathWorks, Inc.


Files

references/node-functions-reference.md

Node Functions Reference

Syntax, arguments, and usage guidelines for the primary OPC UA node discovery functions in the Industrial Communication Toolbox.

findNodeById

Search a node list for a node matching a specific namespace index and identifier.

Syntax
% TEMPLATE — not executable (syntax signature)
foundNode = findNodeById(nodeList, nsInd, id)
Input Arguments
ArgumentTypeDescription
nodeListArray of opc.ua.NodeNodes to search through. Use uaClient.Namespace to search the entire namespace.
nsIndIntegerNamespace index to match against the node's NamespaceIndex property.
idchar, string, or integerIdentifier to match against the node's Identifier property.
Output Arguments
ArgumentTypeDescription
foundNodeopc.ua.NodeThe node whose NamespaceIndex and Identifier match. Empty if not found.
Usage Guidelines
  • Returns a single node (not an array) — there is at most one node per (nsInd, id) pair.

  • Searches recursively; may query the server for further descendants.

  • The returned node retains parent information — safe to use with invoke.

  • Use when you know the namespace index and identifier but need the node in-context (with hierarchy info).

Examples
% Find the ServerCapabilities node (ns=0, id=2268)
uaClient = opcua("localhost", 51210);
connect(uaClient);
capNode = findNodeById(uaClient.Namespace, 0, 2268);
% Find a node with string identifier
node = findNodeById(uaClient.Namespace, 5, "StaticData");
Version History
VersionChange
R2015bIntroduced
R2024aEnhanced to find method nodes on OPC UA servers

opcuanode

Create OPC UA node objects directly from a known namespace index and identifier.

Syntax
% TEMPLATE — not executable (syntax signatures)
nodeList = opcuanode(index, id)
nodeList = opcuanode(index, id, uaClient)
Input Arguments
ArgumentTypeDescription
indexNumeric (scalar or array)Namespace index. Data types: single, double, int8–int64, uint8–uint64.
idNumeric, char, string, or cell arrayNode identifier. Use cell array for mixed types (e.g., {1001, 1002, 'BooleanDataItem'}).
uaClientopc.ua.ClientOPC UA client object. If connected, node properties are immediately retrieved from the server.
Behavior
FormWhat happens
opcuanode(index, id)Creates node without server association. Name is set to 'index:id'; other properties remain 'Unknown' until a server operation associates it.
opcuanode(index, id, uaClient)Immediately associates with the client. If connected, retrieves Name, NodeType, ServerDataType, etc. from the server.
Usage Guidelines
  • Use only when you know the exact namespace index and identifier.

  • The id argument must be a single identifier (numeric or string) — never a slash-separated path.

  • Passing a browse path (e.g., 'Demo/Mass/Nested/7') fails silently: creates a node with NodeType: 'Unknown'.

  • Nodes created via opcuanode may lack parent information (Parent empty):

    • When Parent is empty, invoke() fails with: "Specified node has no parent information".

  • For method invocation, check the node's Parent property first. If it is empty, re-resolve the node via findNodeById (or .Children navigation), which retains parent info; if it is non-empty, invoke directly.

  • Can create arrays of nodes in one call by passing arrays/cell arrays for index and id.

Examples
% Create a node with server association
uaClient = opcua("opc.tcp://localhost:53530/OPCUA/SimulationServer2");
connect(uaClient);
myNode = opcuanode(2, 10225, uaClient);
% Create multiple nodes at once
nodes = opcuanode([3, 3, 5], {1001, 1002, 'BooleanDataItem'}, uaClient);
values = readValue(uaClient, nodes);
Limitations
LimitationImpactAlternative
No browse path supportPassing 'A/B/C' creates invalid node silentlyWalk path with .Children level-by-level
Parent may be emptyinvoke() fails when Parent is emptyCheck Parent; if empty, re-resolve via findNodeById or .Children navigation
Version History
VersionChange
R2015bIntroduced
R2024aAdded ability to create method node objects (but still cannot invoke them)

getNamespace

Retrieve one layer of the OPC UA server namespace tree.

Syntax
% TEMPLATE — not executable (syntax signatures; ___ is doc placeholder)
nodes = getNamespace(uaClient)
nodes = getNamespace(uaClient, browseNode)
nodes = getNamespace(___, '-force')
Input Arguments
ArgumentTypeDescription
uaClientopc.ua.ClientConnected OPC UA client object.
browseNodeopc.ua.NodeNode whose children to retrieve. If empty or omitted, retrieves the top-level namespace.
'-force'FlagForces retrieval from the server, bypassing local cache.
Behavior
FormWhat happens
getNamespace(uaClient)Returns the top-level namespace nodes. Equivalent to uaClient.Namespace.
getNamespace(uaClient, browseNode)Retrieves only the children of browseNode. Stores them in browseNode.Children.
getNamespace(___, '-force')Re-fetches from the server even if nodes are already cached locally.
Caching
  • By default, returns cached nodes if they already exist locally (no server round-trip).

  • Use '-force' to refresh from the server when you suspect the namespace has changed.

  • The uaClient.Namespace property uses the same caching.

Usage Guidelines
  • Prefer uaClient.Namespace over getNamespace(uaClient) for cleaner syntax.

  • Use getNamespace(uaClient, node) to explicitly populate a node's children before iterating.

  • For large namespaces (thousands of children), scope queries to specific subtrees.

Examples
% Get top-level namespace
nodes = uaClient.Namespace;
% Get children of a specific node
idx = arrayfun(@(n) strcmp(n.Name, 'Server'), uaClient.Namespace);
serverNode = uaClient.Namespace(idx);
children = getNamespace(uaClient, serverNode);
% Force refresh from server
nodes = getNamespace(uaClient, '-force');
Version History
VersionChange
R2015bIntroduced

Quick Comparison

FunctionUse WhenReturnsHas Parent InfoCan Invoke
findNodeByIdKnow namespace index + identifier, need hierarchy contextSingle nodeYesYes
opcuanodeKnow exact namespace index + identifier, need quick accessSingle/array of nodesSometimes (check Parent)If Parent populated
getNamespaceNeed to browse/explore one layerArray of childrenYesYes
.ChildrenNavigate level-by-level, search by nameArray of childrenYesYes

Copyright 2026 The MathWorks, Inc.


Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs Node.js

Security

No issues found by our static scan· No issues found

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
MathWorks
Publisher
MathWorks (Official)
Source
matlab/matlab-agentic-toolkit · skills-catalog/test-and-measurement/matlab-use-opcua-client · commit 2a7f215
Licence
BSD 2-Clause License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE.md)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by MathWorks.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download matlab-use-opcua-client.zip