# Node SDK

Write nodes for AgenticMind. Manifests, typed config, ports and branches, permissions, secrets, documents, handles, tools, memory, errors, events and testing.

Source: https://glamorous-boar.cloudvent.net/architecture/node-sdk/

---

A node is a **manifest** (a machine-readable contract) bound to an async **handler**. Nodes are testable without the UI, API or scheduler.

## Minimal node

<CodeBlock language="python" filename="reverse.py" showCopy={true}>

```
from typing import Literal
from pydantic import Field
from agenticmind_node_sdk import (
    InputPort, NodeConfig, NodeContext, NodeResult, OutputPort, PortType, define_node, ui,
)

class ReverseConfig(NodeConfig):
    mode: Literal["chars", "words"] = "chars"
    keep_case: bool = Field(default=True, json_schema_extra=ui(advanced=True))

@define_node(
    type="acme.text.reverse",          # stable ID: <publisher>.<family>.<name>
    version="1.0.0",                   # semver of the contract
    display_name="Reverse",
    category="transform",
    package="acme-nodes",
    description="Reverses text.",
    inputs=[InputPort(name="text", type=PortType.STRING)],
    outputs=[OutputPort(name="text", type=PortType.STRING)],
    config=ReverseConfig,
)
async def reverse(ctx: NodeContext, inputs, config: ReverseConfig) -> NodeResult:
    text = inputs["text"]
    out = " ".join(reversed(text.split())) if config.mode == "words" else text[::-1]
    return NodeResult(outputs={"text": out})
```

</CodeBlock>

## Contract fields

| Field | Notes |
|---|---|
| Identity | `type`, `version`, `display_name`, `category`, `package` |
| Configuration | A `NodeConfig` subclass (unknown keys rejected). Its JSON Schema is published in the manifest and drives the inspector form. UI hints via `ui(widget="textarea", advanced=True, placeholder=..., show_when=...)`; hints never change semantics. |
| Inputs | `InputPort(name, type, required=True, cardinality=SINGLE or MULTIPLE, type_from_config=None)` |
| Outputs | `OutputPort(name, type, type_from_config=None)`. All declared outputs must be returned. |
| Branches | Control outputs; default `["done"]`. Return `NodeResult(branches=frozenset({...}))`. |
| Dynamic branches | `branches_from_config="routes"` adds one branch per configured item (Router). |
| Control join | `"any"` (default, OR) or `"all"` (Join). |
| Can suspend | `can_suspend=True` lets a handler raise `SuspendNode(request, response_schema)`; on resume it is called again with `ctx.resume_value`. |
| Runtime role | `"loop_start"` / `"loop_end"` for the Loop pair. |
| Execution | `ExecutionPolicy(timeout_seconds, max_attempts, idempotent)` |
| Permissions | `Permissions(network, filesystem, database, subprocess, credentials, artifacts, memory)` |
| Compatibility | `Compatibility(ir_versions, adapters)` |
| Modes | Which experiences (`no_code`, `low_code`, `developer`) can safely represent the node |

`type_from_config` lets a port's type follow a config field (Manual Input's output type is its `value_type`). Validator, runtime and UI resolve it the same way.

## Documents and handles

`Document` and `RetrievedDocument` live in `agenticmind_node_sdk.documents`; use `parse_documents(...)` / `to_values(...)` to convert. IDs are deterministic (`<artifact>:p<page>#c<chunk>`).

Shared resources travel as handles (`EmbeddingModelHandle`, `VectorStoreHandle`, `ToolHandle`) in `agenticmind_node_sdk.handles`: plain config plus secret references. A consumer with `credentials` may call `ctx.secret(handle.api_key)`.

## Writing a tool for agents

<CodeBlock language="python" filename="weather_tool.py" showCopy={true}>

```
from agenticmind_node_sdk import NodeResult, OutputPort, PortType, ToolHandle, define_node
from agenticmind_node_sdk.handles import handle_value
from agenticmind_nodes_agents.tools import ToolError, implementation

@define_node(type="acme.tools.weather", version="1.0.0", display_name="Weather Tool", category="tools",
             package="acme-nodes", outputs=[OutputPort(name="tool", type=PortType.TOOL)])
async def weather_tool(ctx, inputs, config):
    return NodeResult(outputs={"tool": handle_value(ToolHandle(
        tool_type="acme_weather", name="get_weather",
        description="Current weather for a city.",
        parameters={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
        permissions=["network"],
    ))})

@implementation("acme_weather")
async def run_weather(ctx, tool, args):
    if not args["city"].strip():
        raise ToolError("city must not be empty")   # shown to the model, which can retry
    return {"city": args["city"], "temp_c": 3}
```

</CodeBlock>

Arguments are validated against `parameters` (JSON Schema 2020-12) before the implementation runs. Return JSON-serialisable data; raise `ToolError` for problems the model should see (`permanent=True` for failures that will not succeed on retry). `permissions` must be a subset of what the Agent declares. Third-party implementations register through the `agenticmind.tools` entry point.

## Secrets

<CodeBlock language="python" filename="Using a secret" showCopy={true}>

```
from agenticmind_node_sdk import Permissions, SecretRef, secret_field

class Cfg(NodeConfig):
    api_key: SecretRef | None = secret_field("Provider key")

@define_node(..., config=Cfg, permissions=Permissions(network=True, credentials=True))
async def handler(ctx, inputs, config):
    key = ctx.secret(config.api_key)   # allowed only for refs in this node's own config
```

</CodeBlock>

## Context services

| Call | Needs |
|---|---|
| `ctx.secret(ref)` | `credentials` |
| `ctx.read_artifact(id)`, `ctx.artifact_info(id)` | `artifacts` |
| `ctx.storage_path("vectors", "qdrant")` | `filesystem` |
| `ctx.memory.recent_turns / append_turns / remember / search` | `memory` (writes of user facts must be gated by explicit consent) |
| `await ctx.emit("tool_call", {...})` | custom trace events (redacted by the runtime) |
| `ctx.streaming`, `ctx.stream_text(delta)` | streaming text |

Do CPU-heavy work with `await asyncio.to_thread(...)` so other runs keep flowing.

## Errors

Raise `NodeError(code, message)` for permanent failures and `TransientNodeError(code, message)` for retryable ones. Codes are stable `UPPER_SNAKE_CASE`. Any other exception becomes `NODE_UNHANDLED_EXCEPTION` and is not retried. Return `usage=ModelUsage(...)` for model calls.

## Testing

<CodeBlock language="python" filename="test_reverse.py" showCopy={true}>

```
from agenticmind_node_sdk.testing import invoke_node

async def test_reverse():
    r = await invoke_node(reverse, inputs={"text": "abc"}, config={"mode": "chars"})
    assert r.outputs == {"text": "cba"}
```

</CodeBlock>

`invoke_node` parses config, enforces secret permissions and checks outputs against the manifest. Pass `memory=InMemoryMemory()` or `artifacts=MemoryArtifacts({...})` to test those services. Use the mock provider for model calls; live provider tests must be opt-in.

## Packaging

Expose `register(registrar)` and declare the `agenticmind.nodes` entry point. Build, validate and install with the `agenticmind-node` CLI; see [Node packages](/node-packages/).
