Skip to main content

hdp-langchain

HDP (Human Delegation Provenance) middleware for LangChain — attach a cryptographic audit trail to any chain, agent, or tool with a single callback handler.

Every tool call in a LangChain agent is recorded in a tamper-evident chain of Ed25519 signatures, verifiable offline with a single public key.

pip install hdp-langchain

Quick start — LangChain

from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
from langchain_core.tools import tool
from langchain.agents import AgentExecutor, create_react_agent
from hdp_langchain import HdpMiddleware, HdpPrincipal, ScopePolicy, verify_chain

# 1. Your signing key (store in a secrets manager, never in code)
private_key = Ed25519PrivateKey.generate()

# 2. Define what the human is authorising
scope = ScopePolicy(
    intent="Research agent to summarise recent papers",
    authorized_tools=["web_search", "file_reader"],
    max_hops=10,
)

# 3. Create the middleware
middleware = HdpMiddleware(
    signing_key=private_key.private_bytes_raw(),
    session_id="research-2026-q1",
    principal=HdpPrincipal(id="researcher@lab.edu", id_type="email"),
    scope=scope,
)

# 4. Build your agent as normal
agent_executor = AgentExecutor(agent=..., tools=[...])

# 5. Attach HDP — one line, zero agent changes
handler = middleware.get_callback_handler()
agent_executor.invoke(
    {"input": "Summarise recent LLM papers"},
    config={"callbacks": [handler]},
)

# 6. Verify the delegation chain offline
result = verify_chain(middleware.export_token(), private_key.public_key())
print(result.valid, result.hop_count, result.violations)

Quick start — LangGraph

from langgraph.graph import StateGraph, END
from hdp_langchain import HdpMiddleware, HdpPrincipal, ScopePolicy, verify_chain
from hdp_langchain.graph import hdp_node

middleware = HdpMiddleware(
    signing_key=private_key.private_bytes_raw(),
    session_id="graph-session-1",
    principal=HdpPrincipal(id="user@example.com", id_type="email"),
    scope=ScopePolicy(intent="Multi-node research pipeline"),
)

# Wrap node functions — each execution records a delegation hop
@hdp_node(middleware, agent_id="planner")
def planner_node(state):
    return {**state, "plan": "step 1, step 2"}

@hdp_node(middleware, agent_id="executor")
def executor_node(state):
    return {**state, "result": "done"}

# Build and run the graph
graph = StateGraph(dict)
graph.add_node("planner", planner_node)
graph.add_node("executor", executor_node)
graph.add_edge("planner", "executor")
graph.add_edge("executor", END)
graph.set_entry_point("planner")

app = graph.compile()
app.invoke({})

# Verify the full delegation chain
result = verify_chain(middleware.export_token(), private_key.public_key())
print(result.valid, result.hop_count)  # True, 2

Five design considerations

# Consideration How it's handled
1 Scope observation Tool calls are compared with declared authorized_tools; out-of-scope attempts are recorded without gating the call.
2 Recording depth ScopePolicy(max_hops=N) caps the recorded chain. LangChain actions continue after the chain is full.
3 Token size / performance Ed25519 signatures are 64 bytes each (~2.6 KB for a 10-hop run). Recording failures are logged as warnings.
4 Verification verify_chain(token, public_key) checks record integrity offline. valid covers integrity only; recorded_after_period lists hop sequence numbers at or after expires_at.
5 Callback integration get_callback_handler() returns an HdpCallbackHandler compatible with LangChain's RunnableConfig. For LangGraph, use hdp_node() to wrap node functions.

API reference

HdpMiddleware

HdpMiddleware(
    signing_key: bytes,          # Ed25519 private key (raw 32 bytes)
    session_id: str,             # unique ID for this run
    principal: HdpPrincipal,     # the human delegating authority
    scope: ScopePolicy,          # what is authorised
    key_id: str = "default",     # label stored in the token header
    expires_in_ms: int = 86400000,
    strict: bool = False,        # Deprecated; True raises ValueError at construction
)
Method Description
get_callback_handler() Return an HdpCallbackHandler for use with LangChain's RunnableConfig
export_token() Return the token dict (or None before first run)
export_token_json() Return the token as a JSON string

HdpCallbackHandler

A langchain_core.callbacks.BaseCallbackHandler subclass. Attach via RunnableConfig:

config = {"callbacks": [middleware.get_callback_handler()]}
chain.invoke(input, config=config)

hdp_node(middleware, node_fn=None, *, agent_id=None)

Wraps a LangGraph node function to record a delegation hop on each invocation:

@hdp_node(middleware, agent_id="researcher")
def researcher_node(state):
    ...
    return state

verify_chain(token, public_key)

result = verify_chain(token_dict, public_key)  # Ed25519PublicKey or raw bytes
result.valid        # bool
result.hop_count    # int
result.violations   # list[str]
result.hop_results  # list[HopVerification]
result.recorded_after_period  # list[int] of hop seq values at or after expires_at

HDP tokens are records and cannot gate actions. authorized_tools records a declaration and does not authorize or block tool use. Expiry does not affect valid. The strict option remains for compatibility; setting it to True raises ValueError during construction. HDPScopeViolationError remains importable but is deprecated and never raised.

ScopePolicy

ScopePolicy(
    intent: str,
    data_classification: str = "internal",   # "public" | "internal" | "confidential" | "restricted"
    network_egress: bool = True,
    persistence: bool = False,
    authorized_tools: list[str] | None = None,
    authorized_resources: list[str] | None = None,
    max_hops: int | None = None,
)

Record-only behavior

Out-of-scope tool calls are recorded in the signed chain and LangChain callbacks do not gate tool execution. strict=True is retained for compatibility and raises ValueError during construction. The deprecated HDPScopeViolationError remains importable but is never raised.


Cross-language compatibility

Python and TypeScript HDP tokens use the same wire format (RFC 8785 canonical JSON + Ed25519). A token issued by hdp-langchain (Python) can be verified by @helixar_ai/hdp (TypeScript) and vice versa.

# Python: export token
token_json = middleware.export_token_json()
# → pass to TypeScript service via API, message queue, etc.
// TypeScript: verify a token issued by Python
import { verifyChain } from "@helixar_ai/hdp";
const result = verifyChain(JSON.parse(tokenJson), publicKey);

Spec

This package follows draft-helixar-hdp-agentic-delegation-03 (latest revision).

License

Apache License 2.0 — Helixar Limited

Metadata

Release files for hdp-langchain 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for hdp-langchain 0.2.0
File Size Uploaded
hdp_langchain-0.2.0.tar.gz 29.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for hdp-langchain 0.2.0
File Interpreter ABI Platform
hdp_langchain-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 45.6 kB

Release files / hdp_langchain-0.2.0.tar.gz

Download URL hdp_langchain-0.2.0.tar.gz
Size 29.5 kB
Tags Source
SHA-256 checksum
How to use checksums
b8652cec9801cd1fa0ee1768fb3d1110be58d3586df71089b89d91fc4518cd6f
BLAKE2b-256 checksum
How to use checksums
3f8aefd2ea9bfc3f66ee44f320d6e590c0ec1705c16dc4d9140fd8f29e14ca17
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 7, 2026.

Transparency log

Release files / hdp_langchain-0.2.0-py3-none-any.whl

Download URL hdp_langchain-0.2.0-py3-none-any.whl
Size 16.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
8f9934fd38a6dc40d2c26b0d005215fd7c5ca4e6092d07631f931853b69d0f84
BLAKE2b-256 checksum
How to use checksums
c72ef43d1796e6796305468de8c87b7d377d67324604c4652cf03fbbec63e423
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Oct 7, 2026.

Transparency log

Release history Release notifications | RSS feed

This release

0.2.0 This release

2 release files

0.1.1

2 release files

0.1.0

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page