Skip to content

Server

Canonical path: o6.server.Server

Root shortcut: o6.Server

Server

Bases: _NativeServer

High-level OPC UA server.

server = o6.Server(port=4840)
with server:
    temperature = server.addVariable("Temperature", server.objectsNode, 22.5)
    print(temperature())

Return behavior depends on the operation and caller loop. Node creation returns handles directly except for async tasks calling a running worker from another loop, which receive awaitables; see MaybeAwaitable.

See the Server guide for the whole picture, and Server callbacks for behaviour implementation.

Attributes

roles instance-attribute

roles = _RoleRegistry(self)

ns instance-attribute

ns = _ServerNamespaces(self)

root instance-attribute

root = cast(
    ObjectNode, _server_node(self, "i=84", ObjectNode)
)

Canonical handle for the Root folder (i=84), available without awaiting.

objects instance-attribute

objects = cast(
    ObjectNode, _server_node(self, "i=85", ObjectNode)
)

Canonical handle for the Objects folder (i=85), available without awaiting.

types instance-attribute

types = cast(
    ObjectNode, _server_node(self, "i=86", ObjectNode)
)

Canonical handle for the Types folder (i=86), available without awaiting.

views instance-attribute

views = cast(
    ObjectNode, _server_node(self, "i=87", ObjectNode)
)

Canonical handle for the Views folder (i=87), available without awaiting.

emitEvent class-attribute instance-attribute

emitEvent = createEvent

T class-attribute instance-attribute

T = TypeVar('T')

objectsNode property

objectsNode

The Objects folder (i=85).

typesNode property

typesNode

The Types folder (i=86).

serverNode property

serverNode

The Server object (i=2253).

loop property

loop

The server's owning asyncio loop, fixed at construction time.

Supplied or detected running loops remain caller-owned. Otherwise the server creates and manages its loop; callers must not close it directly. waitReady() must be awaited on this loop.

endpointUrl property

endpointUrl

The local endpoint URL, built from the configured port.

onLifecycleNotification property writable

onLifecycleNotification

Registry of server-lifecycle notification handlers.

See Lifecycle.

onSecureChannelNotification property writable

onSecureChannelNotification

Registry of secure-channel opened/closed notification handlers.

See Secure Channel.

onSessionNotification property writable

onSessionNotification

Registry of session created/activated/deactivated/closed notification handlers.

See Session.

onServiceNotification property writable

onServiceNotification

Registry of service-call begin/end notification handlers.

Fires around every individual service request the server processes, so a handler here is on the hot path.

See Service.

onSubscriptionNotification property writable

onSubscriptionNotification

Registry of subscription created/modified/publishing-mode/transferred/deleted notification handlers.

See Subscription.

onMonitoredItemNotification property writable

onMonitoredItemNotification

Registry of monitored-item created/modified/monitoring-mode-changed/deleted notification handlers.

See MonitoredItem.

onDiscoveryRegisterServerNotification property writable

onDiscoveryRegisterServerNotification

Registry of discovery RegisterServer notification handlers.

A separate category from onDiscoveryServerOnNetworkNotification; the two payloads are disjoint.

See Discovery: RegisterServer.

onDiscoveryServerOnNetworkNotification property writable

onDiscoveryServerOnNetworkNotification

Registry of discovery ServerOnNetwork notification handlers.

A separate category from onDiscoveryRegisterServerNotification; the two payloads are disjoint.

See Discovery: ServerOnNetwork.

onAuditNotification property writable

onAuditNotification

Registry of audit notification handlers.

Opt-in: open62541 drops audit notifications unless server.config.auditingEnabled is True. notification.auditEventType names the specific standardized AuditEventType subtype.

See Audit.

Functions

__init__

__init__(
    port=4840,
    logger=None,
    loop=None,
    *,
    certificate=None,
    privateKey=None,
    trustList=None,
    issuerList=None,
    revocationList=None,
    secureOnly=False,
    acceptAllCertificates=False,
    applicationUri=None,
    accessControl=None,
    allowNonePolicyPassword=False,
    rbacForAnonymous=False
)

Create a server. It is not listening until start() is called.

Parameters:

Name Type Description Default
port int

TCP port to bind.

4840
logger Logger | None

Logger for server output. Defaults to the o6.server logger.

None
loop AbstractEventLoop | None

Event loop to schedule non-blocking iterations on. When given, or when a running loop is detected, the server does not spawn a background thread; otherwise it creates its own loop and drives it from a daemon thread.

None
certificate str | Path | bytes | None

Server certificate, as a path or raw DER or PEM bytes. Must be provided together with a nonempty private key.

None
privateKey str | Path | bytes | None

Matching private key, as a path or raw bytes. Both credential files or byte strings must be nonempty.

None
trustList list[str | Path | bytes] | None

Client certificates the server trusts.

None
issuerList list[str | Path | bytes] | None

Issuer certificates for chain validation.

None
revocationList list[str | Path | bytes] | None

Certificate revocation lists.

None
secureOnly bool

Refuse unencrypted connections. Requires a certificate and private key.

False
acceptAllCertificates bool

Trust every client certificate. For development only.

False
applicationUri str | None

Override the advertised application URI. It must match the URI inside the server certificate on secured endpoints.

None
accessControl AccessControl | None

An AccessControl subclass instance that authenticates and authorizes sessions.

None
allowNonePolicyPassword bool

Permit username/password tokens on an unencrypted channel.

False
rbacForAnonymous bool

Enforce role permissions for anonymous sessions. Off by default, which leaves anonymous sessions permissive.

False

Raises:

Type Description
TypeError

accessControl is not an o6.AccessControl instance.

ValueError

Credentials are incomplete or empty, or secureOnly is requested without a certificate and private key.

PermissionError

This build has no server feature entitlement.

implement

implement(
    declaration: type, implementation: type | None
) -> None
implement(target: MethodNode, behavior: None) -> None
implement(target: VariableNode, behavior: Any) -> None
implement(
    target: MethodNode | NodeIdLike,
    /,
    *,
    call: Callable[..., Any] | None,
) -> None
implement(
    target: (
        VariableNode | VariableTypeNode | type | NodeIdLike
    ),
    /,
    *,
    read: (
        VariableReadCallback | None | object
    ) = _CALLBACK_UNSET,
    write: (
        VariableWriteCallback | None | object
    ) = _CALLBACK_UNSET,
) -> None
implement(
    target,
    implementation=_CALLBACK_UNSET,
    /,
    *,
    call=_CALLBACK_UNSET,
    read=_CALLBACK_UNSET,
    write=_CALLBACK_UNSET,
)

Install server-local Python behaviour on a UA type or concrete node.

implement(DeclarationType, ImplementationType) binds an undecorated Python behaviour subclass to an existing ObjectType or VariableType on this server alone. Future instances created through native APIs or an AddNodes request receive that implementation, without modifying or subclassing the UA information model. Their implementation-selected children are created before the native Mandatory children, and their ordinary Python initializer runs once, after the complete subtree exists. Because AddNodes supplies no Python arguments, that initializer must be callable without required arguments. Passing None restores the declaration's own Python type for future instances.

Passing None positionally for a concrete Method or Variable restores the callback resolution performed during construction. A concrete value positionally supplied for a Variable removes both callbacks and installs that value in native storage.

call=, read=, and write= replace or clear one callback slot on a Method, Variable, or VariableType. Existing concrete instances are never changed by a type-level update.

Parameters:

Name Type Description Default
target MethodNode | VariableNode | VariableTypeNode | NodeIdLike | type

The declared type to implement, or a concrete Method, Variable, VariableType, or NodeId-like value.

required
implementation Any

An implementation class for a type target, None to reset, or a value to store for a Variable target. Cannot be combined with the keyword slots.

_CALLBACK_UNSET
call Callable[..., Any] | None | object

Method implementation, or None to clear the slot.

_CALLBACK_UNSET
read VariableReadCallback | None | object

Variable value-read implementation, or None to clear the slot.

_CALLBACK_UNSET
write VariableWriteCallback | None | object

Variable value-write implementation, or None to clear the slot.

_CALLBACK_UNSET

Raises:

Type Description
TypeError

An implementation class is combined with call=, read=, or write=; a Method is given a positional value other than None; or a positional value targets something that is neither a Method nor a Variable.

See Implementing behaviour and Server callbacks.

createEvent

createEvent(
    eventType=None,
    *,
    source=ns0.instances.server,
    message="",
    severity=1,
    fields=None,
    eventInstance=None
)

Emit an event and return its generated EventId.

Matches C's UA_Server_createEvent: this emits immediately. Construct o6.Event(server, ...) for a reusable draft. emitEvent is an alias.

An explicit eventType wins; otherwise use eventInstance's type when supplied, then source's declared GeneratesEvent target. Without an instance, no declared target falls back to BaseEventType; ambiguous targets or a source without a type definition raise ValueError.

eventInstance optionally supplies fields from an existing Object instance of BaseEventType or a subtype. Node handles must belong to this server; NodeIds are resolved locally. Explicit fields take precedence over instance properties, then standard defaults apply. Stored EventType and SourceNode properties also override emission arguments, including when their values are null NodeIds, matching C. The instance is read without being updated or deleted.

Returns the EventId directly for synchronous callers, or an awaitable for asynchronous callers on another event loop.

__getitem__

__getitem__(key)

Resolve a node ID to its canonical typed Node handle.

Repeated lookup returns the same server-owned Python object, preserving its modeled type and application state. Deleted nodes cannot be looked up; reusing their ID resolves to the replacement object.

Parameters:

Name Type Description Default
key NodeIdLike

A NodeId-like value accepted by NodeId, including a string, numeric namespace-zero ID, NodeId, or node handle.

required

Returns:

Type Description
MaybeAwaitable[Node]

The matching Node subclass synchronously, or an awaitable in async

MaybeAwaitable[Node]

tasks, before startup and on either the server or a foreign loop.

MaybeAwaitable[Node]

The root, objects, types, and views handles are available

MaybeAwaitable[Node]

immediately in every mode and support normal child/path navigation.

Raises:

Type Description
StatusCodeError

Lookup failed; an unknown or deleted ID has code StatusCode.BAD_NODE_ID_UNKNOWN.

RuntimeError

The server has been cleaned up or its worker loop is no longer running.

node = server["ns=1;s=Temperature"]        # sync
node = await server["ns=1;s=Temperature"]  # async

start

start()

Start the server networking layer.

Synchronous callers wait until the listeners are ready, using a background thread to drive I/O. On the server's running asyncio loop, await waitReady() afterwards, or use async with server. Listener creation failures are raised by the readiness wait.

waitReady async

waitReady()

Wait for a started server's listeners, raising any bind failure.

Call on server.loop after start(). Cancelling this wait shuts down startup and closes any listeners already opened.

stop

stop()

Shut down the server.

Calls from a background server's own loop initiate shutdown and return a Task that can be awaited. Other callers block until shutdown finishes. The server's worker is stopped after the shutdown task completes.

__enter__

__enter__()

Start the server and return it.

__exit__

__exit__(exc_type, exc_val, exc_tb)

Stop the server on leaving the block, including on an exception.

__aenter__ async

__aenter__()

Start the server and return it.

__aexit__ async

__aexit__(exc_type, exc_val, exc_tb)

Stop the server on leaving the block, including on an exception.

__del__

__del__()

addReverseConnect

addReverseConnect(url, callback=None)

Register a reverse connect to a client listening at url.

The server will periodically attempt to establish a connection to the given client endpoint (e.g. opc.tcp://localhost:4841).

Parameters:

Name Type Description Default
url str

The OPC UA endpoint URL of the listening client.

required
callback Callable[[int, int], None] | None

Called with (handle, state) on every state change.

None

Returns:

Type Description
MaybeAwaitable[int]

A handle that can be passed to removeReverseConnect.

removeReverseConnect

removeReverseConnect(handle)

Remove a reverse connect registration.

Parameters:

Name Type Description Default
handle int

The handle returned by addReverseConnect.

required

addVariable

addVariable(
    name,
    parent,
    value=None,
    *,
    nodeId=None,
    dataType=None,
    typeDefinition=o6.NodeId(
        ns0.vartypes.BaseDataVariableType
    ),
    writable=True,
    historizing=False,
    ns=1,
    parentReference=ns0.reftypes.Organizes
)

Add a variable node to the address space.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the Variable.

required
parent NodeIdLike

Parent node, typically server.objectsNode.

required
value Any

Initial value. Its OPC UA DataType is inferred unless dataType is given explicitly. Empty NumPy arrays retain their datatype and ValueRank; empty Python sequences require dataType. Empty values are read back as flat arrays because OPC UA Binary omits dimension sizes for them.

None
nodeId NodeIdLike | None

Requested NodeId. The server assigns one when omitted.

None
dataType NodeIdLike | None

Explicit DataType. Inferred from value when omitted.

None
typeDefinition NodeIdLike

VariableType of the new node.

NodeId(BaseDataVariableType)
writable bool

Whether clients may write the Variable.

True
historizing bool | History

Whether to record this Variable's history. Registers immediately on a running server, which requires a configured history database. Before startup, registration is deferred to start() so the database can be configured after creation.

False
ns int

Namespace index for the BrowseName.

1
parentReference NodeIdLike

Reference linking the parent to the new node. Defaults to Organizes, matching the client convenience.

Organizes

Returns:

Type Description
MaybeAwaitable[VariableNode]

A handle to the new Variable node, or an awaitable resolving to it

MaybeAwaitable[VariableNode]

for every async task, including before startup and on the owning

MaybeAwaitable[VariableNode]

loop. Ordinary synchronous callers receive the handle directly.

MaybeAwaitable[VariableNode]

Cancellation does not roll back a native creation already completed.

Raises:

Type Description
StatusCodeError

Node creation or history registration failed.

RuntimeError

Runtime historizing was requested without a database.

TypeError

An empty value has no usable datatype.

historize

historize(
    target, *, capacity=0, strategy="on-write", interval=1.0
)

Record the history of an existing Variable.

addVariable(..., historizing=...) covers Variables this server creates. This is for the ones it does not: nodes loaded from a nodeset, declared instances, or nodes a client added. It sets the Historizing attribute and the history access bits as well as registering the node, so a Variable that was not marked historizing becomes one.

This takes effect immediately and needs a history database already configured. Variables created with historizing= register immediately when running, or during start() when created before startup. Await this method from async code; synchronous callers block until it completes. Failed registration restores the original node attributes.

server.config.setHistoryDatabase(capacity=5000)
server.historize("ns=1;s=Level")
server.historize(sensorNode, strategy="poll", interval=0.2)

Parameters:

Name Type Description Default
target NodeIdLike

The Variable to historize.

required
capacity int | None

Samples kept for this node; 0 takes the database default, None grows the store instead of evicting.

0
strategy str

"on-write" or "poll".

'on-write'
interval float

Seconds between samples, for "poll" only.

1.0

Raises:

Type Description
RuntimeError

No history database is configured.

ValueError

The strategy or the interval is not usable.

StatusCodeError

The node's store could not be allocated.

unhistorize

unhistorize(target)

Stop recording a Variable's history and release its store.

The inverse of historize: it clears the Historizing attribute and the history access bits, drops the registration, and frees the samples. Nothing is kept — registering the node again starts from an empty store. Await this method from async code; synchronous callers block until it completes.

server.unhistorize("ns=1;s=Level")

Parameters:

Name Type Description Default
target NodeIdLike

The Variable to stop historizing.

required

Raises:

Type Description
RuntimeError

No history database is configured.

StatusCodeError

The node does not exist.

addObject

addObject(
    name,
    parent,
    *,
    nodeId=None,
    typeDefinition=o6.NodeId(ns0.objtypes.BaseObjectType),
    ns=1,
    parentReference=ns0.reftypes.Organizes
)

Add an object node to the address space.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the Object.

required
parent NodeIdLike

Parent node.

required
nodeId NodeIdLike | None

Requested NodeId. The server assigns one when omitted.

None
typeDefinition NodeIdLike

ObjectType of the new node. Defaults to BaseObjectType (i=58).

NodeId(BaseObjectType)
ns int

Namespace index for the BrowseName.

1
parentReference NodeIdLike

Reference linking the parent to the new node. Defaults to Organizes, matching the client convenience.

Organizes

Returns:

Type Description
MaybeAwaitable[ObjectNode]

A handle to the new Object node, or an awaitable resolving to it

MaybeAwaitable[ObjectNode]

for every async task, including before startup and on the owning

MaybeAwaitable[ObjectNode]

loop. Ordinary synchronous callers receive the handle directly.

MaybeAwaitable[ObjectNode]

Cancellation does not roll back a native creation already completed.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addObjectType

addObjectType(
    name,
    parent=o6.NodeId(ns0.objtypes.BaseObjectType),
    *,
    nodeId=None,
    ns=1
)

Add an object type node.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the ObjectType.

required
parent NodeIdLike

The HasSubtype parent. Defaults to BaseObjectType (i=58).

NodeId(BaseObjectType)
nodeId NodeIdLike | None

Requested NodeId. The server assigns one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
MaybeAwaitable[ObjectTypeNode]

A handle to the new ObjectType node, or an awaitable resolving to it

MaybeAwaitable[ObjectTypeNode]

for every async task, including before startup and on the owning

MaybeAwaitable[ObjectTypeNode]

loop. Ordinary synchronous callers receive the handle directly.

MaybeAwaitable[ObjectTypeNode]

Cancellation does not roll back a native creation already completed.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addVariableType

addVariableType(
    name,
    parent=o6.NodeId(ns0.vartypes.BaseVariableType),
    *,
    dataType=o6.NodeId(o6.Double),
    valueRank=-1,
    nodeId=None,
    ns=1
)

Add a variable type node.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the VariableType.

required
parent NodeIdLike

The HasSubtype parent. Defaults to BaseVariableType (i=62).

NodeId(BaseVariableType)
dataType NodeIdLike

DataType of the value. Defaults to Double (i=11).

NodeId(Double)
valueRank int

ValueRank of the value. Defaults to -1, a scalar.

-1
nodeId NodeIdLike | None

Requested NodeId. The server assigns one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
MaybeAwaitable[VariableTypeNode]

A handle to the new VariableType node, or an awaitable resolving to it

MaybeAwaitable[VariableTypeNode]

for every async task, including before startup and on the owning

MaybeAwaitable[VariableTypeNode]

loop. Ordinary synchronous callers receive the handle directly.

MaybeAwaitable[VariableTypeNode]

Cancellation does not roll back a native creation already completed.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addReferenceType

addReferenceType(
    name,
    parent=ns0.reftypes.NonHierarchicalReferences,
    *,
    inverseName=None,
    symmetric=False,
    abstract=False,
    nodeId=None,
    ns=1
)

Add a ReferenceType node to the address space.

Parameters:

Name Type Description Default
name LocalizedTextLike

DisplayName of the node, also used as its BrowseName.

required
parent NodeIdLike

The HasSubtype parent. Defaults to NonHierarchicalReferences.

NonHierarchicalReferences
inverseName LocalizedTextLike | None

InverseName attribute, the name of the reverse direction. OPC UA requires it for a non-symmetric, non-abstract ReferenceType.

None
symmetric bool

Declare the reference symmetric, so it reads the same in both directions and needs no InverseName.

False
abstract bool

Declare the ReferenceType abstract, so only its subtypes may be used in references.

False
nodeId NodeIdLike | None

NodeId of the node. The server allocates one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
MaybeAwaitable[ReferenceTypeNode]

A handle to the new ReferenceType node, or an awaitable resolving to it

MaybeAwaitable[ReferenceTypeNode]

for every async task, including before startup and on the owning

MaybeAwaitable[ReferenceTypeNode]

loop. Ordinary synchronous callers receive the handle directly.

MaybeAwaitable[ReferenceTypeNode]

Cancellation does not roll back a native creation already completed.

Raises:

Type Description
StatusCodeError

The AddNodes call failed, for example because the NodeId is taken or the parent does not exist.

addView

addView(
    name,
    parent=ns0.instances.views,
    *,
    eventNotifier=0,
    containsNoLoops=True,
    nodeId=None,
    ns=1
)

Add a View node to the address space.

The View starts out empty; add its members with addReference. For the declarative route, use o6.view instead.

Parameters:

Name Type Description Default
name LocalizedTextLike

DisplayName of the node, also used as its BrowseName.

required
parent NodeIdLike

Node that organizes the View. Defaults to the standard ViewsFolder.

views
eventNotifier int

EventNotifier attribute of the node.

0
containsNoLoops bool

ContainsNoLoops attribute, asserting that browsing the View cannot revisit a node.

True
nodeId NodeIdLike | None

NodeId of the node. The server allocates one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
MaybeAwaitable[ViewNode]

A handle to the new View node, or an awaitable resolving to it

MaybeAwaitable[ViewNode]

for every async task, including before startup and on the owning

MaybeAwaitable[ViewNode]

loop. Ordinary synchronous callers receive the handle directly.

MaybeAwaitable[ViewNode]

Cancellation does not roll back a native creation already completed.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addMethod

addMethod(
    name,
    parent,
    callback,
    *,
    inputArgs=None,
    outputArgs=None,
    nodeId=None,
    ns=1
)

Add a method node to the address space.

Parameters:

Name Type Description Default
name LocalizedTextLike

BrowseName, and DisplayName, of the Method.

required
parent NodeIdLike

Parent node, typically an Object.

required
callback MethodCallback

Called when a client invokes the Method. See MethodCallback for the signature.

required
inputArgs list[Argument] | None

InputArguments descriptors.

None
outputArgs list[Argument] | None

OutputArguments descriptors.

None
nodeId NodeId | None

Requested NodeId. The server assigns one when omitted.

None
ns int

Namespace index for the BrowseName.

1

Returns:

Type Description
MaybeAwaitable[MethodNode]

The unbound server Method node. Invoke it with object=parent, or

MaybeAwaitable[MethodNode]

reach it through the parent Object's dot syntax to obtain a bound

MaybeAwaitable[MethodNode]

call. Every async task receives an awaitable resolving to the

MaybeAwaitable[MethodNode]

configured handle, including before startup and on the owning loop.

MaybeAwaitable[MethodNode]

Ordinary synchronous callers receive the handle directly. Cancellation does not roll back

MaybeAwaitable[MethodNode]

a native creation that has already completed.

Raises:

Type Description
StatusCodeError

The AddNodes call failed.

addReferenceLegacy

addReferenceLegacy(
    source, target, referenceType, *, forward=True
)

Add a reference using the legacy server argument order.

Parameters:

Name Type Description Default
source NodeIdLike

Source node id.

required
target NodeIdLike | ExpandedNodeId

Target node id, including an expanded target.

required
referenceType NodeIdLike

Reference type id.

required
forward bool

Whether the reference points forward.

True

Returns:

Type Description
MaybeAwaitable[None]

None for synchronous callers; awaitable in async tasks.

Raises:

Type Description
StatusCodeError

The individual mutation failed.

deleteReferenceLegacy

deleteReferenceLegacy(
    source,
    target,
    referenceType,
    *,
    forward=True,
    bidirectional=True
)

Delete a reference using legacy server arguments and errors.

Parameters:

Name Type Description Default
source NodeIdLike

Source node id.

required
target NodeIdLike | ExpandedNodeId

Target node id, including an expanded target.

required
referenceType NodeIdLike

Reference type id.

required
forward bool

Whether to delete the forward reference.

True
bidirectional bool

Whether to also delete the reverse reference.

True

Returns:

Type Description
MaybeAwaitable[None]

None for synchronous callers; awaitable in async tasks.

Raises:

Type Description
StatusCodeError

The individual mutation failed.

addReference

addReference(
    source,
    reftype,
    target,
    forward=True,
    targetNodeClass=ns0.datatypes.NodeClass.UNSPECIFIED,
    targetServerUri="",
)

Add a reference with administrative privileges.

Parameters:

Name Type Description Default
source NodeIdLike

Source node id.

required
reftype NodeIdLike

Reference type id.

required
target NodeIdLike | ExpandedNodeId

Target node id or expanded id, including remote metadata.

required
forward bool

Whether to create a forward reference.

True
targetNodeClass NodeClass

Local creation supports only UNSPECIFIED; other values return BAD_NOT_SUPPORTED.

UNSPECIFIED
targetServerUri str

Nonempty URIs return BAD_NOT_IMPLEMENTED. Use an expanded target to identify a remote node.

''

Returns:

Type Description
MaybeAwaitable[StatusCode]

The individual StatusCode, or an awaitable resolving to it.

MaybeAwaitable[StatusCode]

Rejected mutations, including duplicate local edges, return bad statuses.

Raises:

Type Description
TypeError

An argument has an invalid Python type.

ValueError

An argument cannot be converted to a node id or enum.

Use addReferenceLegacy for the old server positional order and errors.

deleteReference

deleteReference(
    source,
    reftype,
    target,
    forward=True,
    deleteBidirectional=True,
)

Delete a reference with administrative privileges.

Parameters:

Name Type Description Default
source NodeIdLike

Source node id.

required
reftype NodeIdLike

Reference type id.

required
target NodeIdLike | ExpandedNodeId

Target node id or expanded id, including remote metadata.

required
forward bool

Whether to delete the forward reference.

True
deleteBidirectional bool

Whether to also delete the reverse reference.

True

Returns:

Type Description
MaybeAwaitable[StatusCode]

The individual StatusCode, or an awaitable resolving to it.

MaybeAwaitable[StatusCode]

Rejected deletions return non-Good statuses, including

MaybeAwaitable[StatusCode]

UNCERTAIN_REFERENCE_NOT_DELETED for an absent edge.

Raises:

Type Description
TypeError

An argument has an invalid Python type.

ValueError

An argument cannot be converted to a node id.

Use deleteReferenceLegacy for the old order and bidirectional flag.

deleteNode

deleteNode(
    nodeId: list[NodeIdLike],
    deleteTargetReferences: bool = True,
) -> MaybeAwaitable[list[o6.StatusCode]]
deleteNode(
    nodeId: NodeIdLike, deleteTargetReferences: bool = True
) -> MaybeAwaitable[o6.StatusCode]
deleteNode(nodeId, deleteTargetReferences=True)

Delete one or more nodes with administrative privileges.

Parameters:

Name Type Description Default
nodeId NodeIdLike | list[NodeIdLike]

A node, node id, or list of these targets.

required
deleteTargetReferences bool

If True (default), remove incoming references from remaining nodes. False leaves dangling references.

True

Returns:

Type Description
MaybeAwaitable[StatusCode | list[StatusCode]]

One StatusCode for a scalar target, otherwise a list in input order,

MaybeAwaitable[StatusCode | list[StatusCode]]

including one-element batches. All targets are attempted despite

MaybeAwaitable[StatusCode | list[StatusCode]]

per-target failures. An empty list returns [] without a deletion.

MaybeAwaitable[StatusCode | list[StatusCode]]

Async callers must await the result.

Raises:

Type Description
TypeError

An argument has an invalid Python type.

ValueError

A target cannot be converted to a node id.

Migrate deleteReferences to deleteTargetReferences. Individual failures return statuses; call status.check() to retain exception handling.

call

call(objectId, methodId, inputArgs=[])

Call a method node server-side with admin privileges.

Matches client.call() — returns (StatusCode, *output_arguments).

Parameters:

Name Type Description Default
objectId NodeIdLike

The Object that owns the Method.

required
methodId NodeIdLike

The Method to invoke.

required
inputArgs list[Any]

InputArguments values, in declaration order.

[]

Returns:

Type Description
MaybeAwaitable[tuple[StatusCode, *(tuple[Any, ...])]]

(statusCode, output1, output2, ...), including bad method statuses

MaybeAwaitable[tuple[StatusCode, *(tuple[Any, ...])]]

and any available outputs. Invalid method selection and argument

MaybeAwaitable[tuple[StatusCode, *(tuple[Any, ...])]]

validation also produce method results. A zero-output result is

MaybeAwaitable[tuple[StatusCode, *(tuple[Any, ...])]]

(statusCode,).

Raises:

Type Description
StatusCodeError

Submission failed; code retains the original status. Method-result failures do not raise.

TypeError

An argument cannot be converted to an OPC UA value.

addPublishedDataSet

addPublishedDataSet(configuration)

Create published items with their complete metadata and source mapping.

Field count, data types and ranks must match the source variables. Folder paths and event datasets are currently unsupported. Await this operation in async tasks, including on the owning loop.

addSubscribedDataSet

addSubscribedDataSet(name, metadata, targets)

Create a native standalone subscribed DataSet in SubscribedDataSets.

Field metadata and target mappings must have the same order and count. This defines the dataset without creating or enabling a DataSetReader. Await this operation in async tasks, including on the owning loop.

removeSubscribedDataSet

removeSubscribedDataSet(dataSetId)

Remove a native standalone subscribed DataSet and its representation.

read

read(
    target,
    *,
    attr=o6.AttributeId.VALUE,
    timestampsToReturn=None,
    valueOnly=True,
    range=None
)

Read one attribute from a node or a list of nodes.

Parameters:

Name Type Description Default
target NodeIdLike | list[NodeIdLike]

One NodeId-like target (including a Node) or a list of targets.

required
attr AttributeId | str

AttributeId or case-insensitive attribute name; keyword-only.

VALUE
timestampsToReturn TimestampsToReturn | None

SOURCE (the default), SERVER, BOTH, or NEITHER.

None
valueOnly bool

Return values for all Good-severity statuses when True, discarding status and timestamps. False returns DataValues for the caller to interpret, including Uncertain and Bad statuses.

True
range IndexRange | list[IndexRange]

Inclusive OPC UA range string, stop-exclusive slice or tuple of slices, or one range per target. A scalar range broadcasts. None or an empty string reads the entire attribute.

None

Returns:

Type Description
MaybeAwaitable[Any]

A scalar for one target, or a list in input order. An empty target

MaybeAwaitable[Any]

list returns []. Raw DataValues retain per-target statuses and

MaybeAwaitable[Any]

supported timestamp metadata, including failed reads.

Raises:

Type Description
StatusCodeError

A service failure or an Uncertain/Bad value-only status. The code property preserves the status; batch errors include the failed index in an exception note. Nonempty ranges on non-Value attributes return BAD_INDEX_RANGE_NO_DATA.

TypeError

An argument has an unsupported Python type.

ValueError

An attribute name, slice, or range-list length is invalid.

Local reads run with administrative privileges. Remote client permissions still apply to Client.read. Use attr= for the attribute argument.

write

write(
    target,
    value=_WRITE_UNSET,
    *,
    attr=o6.AttributeId.VALUE,
    range=None
)

Write one attribute using a scalar, parallel lists, or a mapping.

Parameters:

Name Type Description Default
target NodeIdLike | list[NodeIdLike] | Mapping[NodeIdLike, Any]

One NodeId-like target (including a Node), a list of targets, or a target-to-value mapping.

required
value Any

Value for one target, or an equal-length list for target lists. Omit for mappings. A list for a scalar target is an array value. Explicit None writes a null value where the target permits it; omitting a scalar value raises ValueError. DataValues retain supported status and timestamp metadata.

_WRITE_UNSET
attr AttributeId | str

AttributeId or case-insensitive attribute name; keyword-only.

VALUE
range IndexRange | list[IndexRange]

Inclusive OPC UA range string, stop-exclusive slice or tuple of slices, or one range per target. A scalar range broadcasts. None or an empty string writes the entire attribute. Nonempty ranges require Value; mappings do not accept ranges.

None

Returns:

Type Description
MaybeAwaitable[StatusCode | list[StatusCode]]

One StatusCode for a scalar target, otherwise a list in input order,

MaybeAwaitable[StatusCode | list[StatusCode]]

including one-element batches. Empty lists/mappings return []. Every

MaybeAwaitable[StatusCode | list[StatusCode]]

target is attempted despite per-target status failures; check results.

Raises:

Type Description
StatusCodeError

A service-level failure; code preserves its status.

TypeError

An argument has an unsupported Python type.

ValueError

Input shapes, attribute names, or ranges are invalid. Shapes and ranges are validated before any writes.

Local writes use administrative privileges and execute sequentially, without rollback. DataValue payloads honor attr; non-Value status and timestamp metadata is unsupported. Non-Value payloads must have the attribute's expected datatype; no attribute-specific coercion is applied. Replace broadcast calls with parallel values or a mapping, and check statuses to retain exception-based handling.

translateBrowsePaths

translateBrowsePaths(request)

Server-side translate browse paths to node ids.

Parameters:

Name Type Description Default
request Any

A TranslateBrowsePathsToNodeIdsRequest instance.

required

Returns:

Type Description
MaybeAwaitable[Any]

The corresponding response.

serviceTranslateBrowsePathsToNodeIds

serviceTranslateBrowsePathsToNodeIds(request)

Execute a raw path-translation request, preserving the response status.

This matches the client service method. translateBrowsePaths remains an alias with its existing request/response contract.

findDataType

findDataType(nodeId)

Look up a DataType by NodeId and return the Python type or metadata.

Parameters:

Name Type Description Default
nodeId NodeIdLike

The DataType node id to look up.

required

Returns:

Type Description
MaybeAwaitable[Any]

Python type or DataType metadata for the requested NodeId.

browse

browse(
    target,
    *,
    direction=ns0.datatypes.BrowseDirection.FORWARD,
    reftype=ns0.reftypes.HierarchicalReferences,
    refsubtypes=True,
    nodeClassMask=ns0.datatypes.NodeClass.UNSPECIFIED,
    resultMask=ns0.datatypes.BrowseResultMask.ALL
)

Collect all references from one node.

Parameters:

Name Type Description Default
target NodeIdLike

The node to browse from.

required
direction BrowseDirection

FORWARD, INVERSE, or BOTH.

FORWARD
reftype NodeIdLike

Only follow this ReferenceType. Defaults to HierarchicalReferences.

HierarchicalReferences
refsubtypes bool

Also follow subtypes of reftype.

True
nodeClassMask int

Only return nodes of these NodeClasses, as the UInt32 the service takes. Compose the NodeClass members you want with |. UNSPECIFIED returns all.

UNSPECIFIED
resultMask int

Which reference fields to fill in, as the UInt32 the service takes. Compose the BrowseResultMask members you want with |. Defaults to ALL; NONE returns only the target NodeIds.

ALL

Returns:

Type Description
MaybeAwaitable[list[ReferenceDescription]]

A complete flat list of ReferenceDescription objects, following

MaybeAwaitable[list[ReferenceDescription]]

continuation points until exhausted. Synchronous callers receive it

MaybeAwaitable[list[ReferenceDescription]]

directly. Async tasks must await the call, on either the server's

MaybeAwaitable[list[ReferenceDescription]]

loop or another loop. This applies to both Node and NodeId targets.

Raises:

Type Description
StatusCodeError

Browse or BrowseNext failed. Outstanding continuation points are released on failure where the backend permits release.

browsePage

browsePage(
    target,
    *,
    maxReferences=0,
    direction=ns0.datatypes.BrowseDirection.FORWARD,
    reftype=ns0.reftypes.HierarchicalReferences,
    refsubtypes=True,
    nodeClassMask=ns0.datatypes.NodeClass.UNSPECIFIED,
    resultMask=ns0.datatypes.BrowseResultMask.ALL
)

Fetch one page of references.

Parameters:

Name Type Description Default
target NodeIdLike

The node to browse from.

required
maxReferences int

Cap on returned references. 0 means no cap, and any cap can leave a continuation point for browseNext.

0
direction BrowseDirection

FORWARD, INVERSE, or BOTH.

FORWARD
reftype NodeIdLike

Only follow this ReferenceType. Defaults to HierarchicalReferences.

HierarchicalReferences
refsubtypes bool

Also follow subtypes of reftype.

True
nodeClassMask int

Only return nodes of these NodeClasses, as the UInt32 the service takes. Compose the NodeClass members you want with |. UNSPECIFIED returns all.

UNSPECIFIED
resultMask int

Which reference fields to fill in, as the UInt32 the service takes. Compose the BrowseResultMask members you want with |. Defaults to ALL; NONE returns only the target NodeIds.

ALL

Returns:

Type Description
MaybeAwaitable[BrowseResult]

The BrowseResult, holding the references and a continuation point

MaybeAwaitable[BrowseResult]

when the result was truncated. Synchronous callers receive it

MaybeAwaitable[BrowseResult]

directly. Async tasks must await the call, on either the server's

MaybeAwaitable[BrowseResult]

loop or another loop. This applies to both Node and NodeId targets.

Raises:

Type Description
StatusCodeError

The Browse call failed.

browseNext

browseNext(releaseContinuationPoint, continuationPoint)

Continue or release pages obtained from browsePage.

Parameters:

Name Type Description Default
releaseContinuationPoint bool

Discard the continuation point instead of fetching the next batch.

required
continuationPoint bytes | list[bytes] | tuple[bytes, ...]

One token or a list/tuple of tokens from previous pages. Tokens belong to this server and must be released when paging is abandoned.

required

Returns:

Type Description
MaybeAwaitable[list[BrowseResult]]

A list of BrowseResult pages, one per token, including when only

MaybeAwaitable[list[BrowseResult]]

one token was supplied. A release returns empty pages. Sync callers

MaybeAwaitable[list[BrowseResult]]

receive the list directly; async tasks must await it.

Raises:

Type Description
StatusCodeError

The BrowseNext call failed, for example because the continuation point expired.

browseRecursive

browseRecursive(
    target,
    *,
    direction=ns0.datatypes.BrowseDirection.FORWARD,
    reftype=ns0.reftypes.HierarchicalReferences,
    refsubtypes=True,
    nodeClassMask=ns0.datatypes.NodeClass.UNSPECIFIED,
    resultMask=ns0.datatypes.BrowseResultMask.NONE
)

Browse a whole subtree in one native traversal.

The arguments match browse, and the traversal is depth-unbounded, so scope it with reftype and nodeClassMask on a large address space.

Returns:

Type Description
MaybeAwaitable[Any]

Every reachable node as a flat list of ExpandedNodeId values.

Raises:

Type Description
StatusCodeError

The traversal failed.

translateBrowsePathsToNodeIds

translateBrowsePathsToNodeIds(
    browsePath: list[BrowsePath],
) -> MaybeAwaitable[list[ns0.datatypes.BrowsePathResult]]
translateBrowsePathsToNodeIds(
    browsePath: BrowsePath,
) -> MaybeAwaitable[ns0.datatypes.BrowsePathResult]
translateBrowsePathsToNodeIds(browsePath)

Resolve one BrowsePath or a list of paths.

Parameters:

Name Type Description Default
browsePath BrowsePath | list[BrowsePath]

A BrowsePath or list of BrowsePaths to resolve.

required

Returns:

Type Description
MaybeAwaitable[BrowsePathResult | list[BrowsePathResult]]

One BrowsePathResult for a scalar input, or a list in input order.

MaybeAwaitable[BrowsePathResult | list[BrowsePathResult]]

Each result retains its status, including partial/unresolved paths;

MaybeAwaitable[BrowsePathResult | list[BrowsePathResult]]

an empty list returns an empty list. Await in async code.

Raises:

Type Description
StatusCodeError

The service failed. Use serviceTranslateBrowsePathsToNodeIds for raw requests/responses.

browseSimplifiedBrowsePaths

browseSimplifiedBrowsePaths(origin, browsePath)

Resolve a BrowseName chain through forward hierarchical references.

Parameters:

Name Type Description Default
origin NodeIdLike

Node at which the path starts.

required
browsePath QualifiedName | str | list[QualifiedName | str] | tuple[QualifiedName | str, ...]

One QualifiedName/string or a list/tuple forming one path.

required

Returns:

Type Description
MaybeAwaitable[BrowsePathResult]

One BrowsePathResult, retaining unresolved-path status. Await in

MaybeAwaitable[BrowsePathResult]

async code. Unlike browseRecursive, this follows a specified path.

forEachChildNode

forEachChildNode(nodeId, callback)

Visit every reference of one node without building a result list.

The cheapest way to walk a node's references, because nothing is allocated per reference. The callback runs on the server's event loop while the node is locked, so it must not block or call back into the server.

Parameters:

Name Type Description Default
nodeId NodeIdLike

The node whose references are visited.

required
callback Callable[[NodeId, bool, NodeId], Any]

Called as (childId, isInverse, referenceTypeId) for each reference.

required

registerDiscovery

registerDiscovery(url, semaphoreFilePath=None)

Register this server at a Discovery Server (LDS).

Parameters:

Name Type Description Default
url str

The LDS endpoint URL, e.g. "opc.tcp://localhost:4840".

required
semaphoreFilePath str | Path | None

Path to a semaphore file used to coordinate shutdown across several instances. None sends an empty path.

None

Raises:

Type Description
StatusCodeError

The registration failed.

deregisterDiscovery

deregisterDiscovery(url)

Deregister this server from a Discovery Server (LDS).

Should be called once during server shutdown.

Parameters:

Name Type Description Default
url str

The LDS endpoint URL that was passed to registerDiscovery.

required

Raises:

Type Description
StatusCodeError

The deregistration failed.

setRegisterServerCallback

setRegisterServerCallback(callback)

Install / remove the callback invoked when another server registers with this LDS.

The callback receives a single dict argument with keys: server_uri, product_uri, discovery_urls (list of str), last_discovery_timestamp.

Pass None to remove the callback.

setServerOnNetworkCallback

setServerOnNetworkCallback(callback)

Install / remove the callback invoked when another server is detected on the network (via mDNS).

The callback receives a single dict argument with keys: record_id, server_name, discovery_url, server_capabilities (list of str), last_announce_time, next_announce_time, last_online_time, is_server_announce (bool), is_txt_received (bool).

Pass None to remove the callback. Requires UA_ENABLE_DISCOVERY_MULTICAST in the open62541 build.

createDataChangeMonitoredItem

createDataChangeMonitoredItem(
    nodeId,
    callback,
    *,
    timestamps=None,
    context=None,
    samplingInterval=0.0,
    monitoringMode=None
)

Create a local DataChange o6.subscription.MonitoredItem.

callback is called as::

callback(monitoredItemId, nodeId, attributeId, data_value, context)

It may be a regular function or an async def. The returned handle exposes the Value target, initial mode, requestedParams, and backend revisions in params. Local items support deletion; modify, setMonitoringMode, and setTriggering raise NotImplementedError.

deleteMonitoredItem

deleteMonitoredItem(monitoredItemId)

Delete a local monitored item by ID or handle.

Repeated deletion of a handle is a no-op. Async callers must await every call, including repeated deletion.

createEventMonitoredItem

createEventMonitoredItem(
    nodeId,
    callback,
    *,
    context=None,
    selectClauses=None,
    whereClause=None,
    eventFilter=None,
    monitoringMode=None,
    clientHandle=0,
    samplingInterval=0.0,
    queueSize=0,
    discardOldest=True
)

Create a local Event o6.subscription.MonitoredItem on nodeId.

Build the filter either piecemeal with selectClauses=/whereClause=, or pass a complete eventFilter= — not both. monitoringMode=, queueSize= and discardOldest= control the local notification queue. clientHandle= is retained but is not used to route local callbacks. Events are driven by emission, so samplingInterval= does not set an event polling period. The handle exposes the EventNotifier target, filter, initial mode, requestedParams, and backend revisions in params. Local items support deletion; modify, setMonitoringMode, and setTriggering raise NotImplementedError.

callback(monitoredItemId, event_fields, context) where event_fields is a dict[str, Any] keyed by selected event-filter paths, such as "/Message" or "/ConditionName/Id".

Raises:

Type Description
TypeError

Both eventFilter and selectClauses/whereClause were given.

ValueError

The effective filter has no select clauses. The server would otherwise reject an empty EventFilter with BadEventFilterInvalid.

addRepeatedCallback

addRepeatedCallback(callback, intervalMs)

Register callback to be called every intervalMs milliseconds.

Returns an opaque integer callback ID that can be passed to changeRepeatedCallbackInterval or removeCallback.

changeRepeatedCallbackInterval

changeRepeatedCallbackInterval(callbackId, intervalMs)

Change the interval of an existing repeated callback.

removeCallback

removeCallback(callbackId)

Remove a repeated callback by ID.