helixid-sdk-py
Python SDK for HelixID -- decentralized agent identity via DID/VC standards (did:hedera, did:key, did:web), delegation, and KYA-OS request proofs verified in-process.
This is the Python counterpart to
helix-sdk-js, following the same
SDK-API-only architecture: every
SDK, in every language, depends only on the HelixID API -- never on a shared
"core" package -- except for private-key operations that must stay local:
keygen, sign and canonical-hash, which issuers and Service Providers use to sign
with their own keys. Delegation-VC construction and status checks are API calls
made through HelixClient.
Every call carries a request proof (KYA-OS story C-C). An agent signs each
MCP request with its own Signer (kyaos.with_request_proof()): an
org.kya-os/proof.v1 bound to that request's body and the service's DID, with
its delegation chain beside it in params._meta. A service verifies it
in-process (helix_sdk.verifier, helix_mcp_middleware). The Helix VP
(sign_vp(), verify_vp(), VPBuilder, X-Helix-VP) is gone, with no
backward compatibility.
Documentation
Full documentation is at docs.helixid.dev — concepts, guides, and reference. This README covers only what is specific to this repository.
| Start here | Introduction |
| Concepts | The Trust Stack · Two-Issuer Model · Delegation · Revocation |
| Get started | Quick Start · Installation & Modes |
| Contributing | How to Contribute · CONTRIBUTING.md |
| Security | Reporting a Vulnerability · SECURITY.md |
Install
pip install helixid-sdk-py
A service that verifies calls also installs the gate:
pip install "helixid-sdk-py[mcp-middleware]"
Python >=3.9 (the gate's mcp extra needs 3.10+). Or from source:
pip install -e .
Quick example
An agent signs every MCP request it sends. The proof is bound to that request's body and to the service's DID, and lives 60 seconds at most.
By default Helix holds the agent's key, so the agent asks Helix to sign
(HelixCustodialSigner). There is no private key on your side. Set two
variables, both from the console when you created the agent:
HELIX_AGENT_DID and HELIX_API_KEY (this agent's API key).
import os, uuid, requests
from helix_sdk import HelixCustodialSigner, kyaos
# Reads HELIX_AGENT_DID and HELIX_API_KEY; signs at https://api.helixid.dev.
signer = HelixCustodialSigner()
signed = kyaos.with_request_proof(
{"name": "search_books", "arguments": {"query": "dune"}},
signer,
audience=os.environ["TARGET_SERVICE"],
)
reply = requests.post(
"https://your-server.example/mcp",
json={"jsonrpc": "2.0", "id": uuid.uuid4().hex, **signed},
headers={"accept": "application/json, text/event-stream"},
timeout=30,
)
TARGET_SERVICE is the service's DID. Set HELIX_API_URL to sign at
another Helix deployment. Pass chain=hops to carry a delegation chain (root to leaf) beside the
proof.
If you hold your own key
Create the agent with helix init (the key is generated on your machine and
only its public half is sent; this package installs the same helix init
command). It writes signing-key.env with two variables, HELIX_AGENT_DID
and HELIX_SIGNING_KEY; keep that file secret and load it where the agent
runs. Then sign with EnvSigner. Nothing else changes:
import os
from helix_sdk import EnvSigner, kyaos
# Reads HELIX_AGENT_DID and HELIX_SIGNING_KEY, and finds the key's id in the agent's DID document.
signer = EnvSigner.from_env()
signed = kyaos.with_request_proof(call, signer, audience=os.environ["TARGET_SERVICE"])
The service
The service side is one line, HelixMcpGate in helix_mcp_middleware. It
verifies each call in-process and sends audit by itself:
from helix_mcp_middleware import HelixMcpGate, LocalVerifierOptions
app = HelixMcpGate(
mcp_app, # the MCP Streamable HTTP app
resource="https://orders.example.com/mcp",
verifier=LocalVerifierOptions(service_did="did:web:orders.example.com"),
tool_scopes={"lookup_order": ["orders:read"]},
tools={"lookup_order": {"minimum_level": "L2"}}, # default L3
)
examples/request_proof_demo.py runs the sign / verify / replay / tamper cycle offline.
Agents written in code: the signing transport
With the official MCP client, connect through helix_transport and write
nothing else for HelixID:
from mcp import Client
from helix_sdk import helix_transport
async with Client(helix_transport("https://orders.example/mcp")) as client:
result = await client.call_tool("lookup_order", {"orderId": "o-1"})
helix_transport(url) is an MCP client transport, like the MCP SDK's own
streamable_http_client(url), so it also works with a ClientSession:
async with helix_transport(url) as (read, write), ClientSession(read, write) as session:.
- The agent's identity comes from the environment:
HELIX_AGENT_DIDwithHELIX_SIGNING_KEYorHELIX_API_KEY. - The service's DID is read from its
/.well-known/mcp, whichHelixMcpGateserves. There is noTARGET_SERVICEto set. - When the service says it signs its answers, each answer is checked. An answer whose signature does not hold is an error, never handed to your code.
- When the service needs a user's consent, the call returns a normal tool result asking the user to open the link and approve, then ask again. A chat agent's model shows it. The next call carries the grant.
It needs the mcp package (the mcp-middleware extra). Frameworks that only
take a URL cannot use it: they never hand over a transport.
Acting for a user
When a service needs the user's consent it answers the call with a link to
Helix's consent page. The user chooses there how long to allow the agent
for, and signs one grant with their own key. call_with_consent runs that
whole loop: it checks the service's signature on the answer, hands you the
link, waits for the user, and sends the call again with the grant.
import os, uuid, requests
from helix_sdk import kyaos
class Refused(Exception):
def __init__(self, status: int) -> None:
super().__init__(f"refused: {status}")
self.status = status
def send(request):
reply = requests.post(
"https://your-server.example/mcp",
json={"jsonrpc": "2.0", "id": uuid.uuid4().hex, **request},
headers={"accept": "application/json, text/event-stream"},
timeout=30,
)
if not reply.ok:
raise Refused(reply.status_code)
return reply.json()["result"]
result = kyaos.consent.call_with_consent(
{"name": "place_order", "arguments": {"item": "tea"}},
signer=signer,
service_did=os.environ["TARGET_SERVICE"],
send=send,
resolve_did=resolve_did, # resolves the service's DID document
for_user="ada", # your own label for the user: required once the service asks for consent
on_authorization_required=lambda prompt: print(f"Open {prompt.authorization_url} to allow this"),
)
There is no chain file to create or keep. The grant is held in memory per
user and service, and filed at Helix under for_user when the agent picks it
up. After a restart the SDK reads it back from Helix, under that label, the
first time the service asks. Calls a service accepts without consent need no
for_user; once a service asks for user consent, a call without one raises
ConsentFlowError with reason for_user_required. A grant is never renewed: when it ends, or the user
withdraws it, the user is asked again. Pass wait_for_user=False to get a
result with status == "authorization_required" and the authorization_url
back at once; the next call picks the grant up after the user approved.
Cross-language parity
The local-signing primitives (keys.py, crypto/common.py, proof.py) are
verified byte-for-byte against the same
fixtures/golden-vectors/*.json fixtures that helix-sdk-js and
helix-core assert against -- same private key, same payload, same
signature, same base58btc-encoded proof value, in every language. See
tests/test_golden_vectors.py and fixtures/golden-vectors/README.md.
If you regenerate the vectors in helix-server (pnpm generate:golden-vectors),
re-copy the three JSON files here too, the same way helix-sdk-js does.
Local verifier (KYA-OS story F-2)
helix_sdk.verifier.verify(proof, seams, options, chain=..., request=..., card=...) verifies a KYA-OS request proof
(org.kya-os/proof.v1) and the delegation chain the request carries, in-process, from the presented artifacts and
what its seams answer (resolve_did, resolve_did_keys, fetch_status_list, resolve_card, nonce_store, clock,
trusted_issuers). It never reads a Helix database, and a missing seam fails closed with its reason code
(helix_sdk.verifier.ReasonCodes). It is the port of helix-sdk-js's kyaos.verifier.verify: same seams, same codes,
same results, which tests/test_verifier.py proves over the fixture set helix-core generates
(fixtures/verifier/*.json, read from the sibling checkout or HELIX_CORE_FIXTURES_DIR).
helix_sdk.verifier.verify_request_proof(proof, request, seams, options) checks the request proof alone in the exact
SPEC-ENTITY-CARD section 11.2 order (story C-C), stopping at the first broken binding: schema, kid of did, the key,
its RFC 7638 thumbprint among the DID's keys, audience, requestHash, the window (+/-5 s, at most 60 s), the nonce,
the detached JWS, the cnf fusion (L3 with a token cnf, L3-minus without). verify() runs it first; with
require_proof=False a chain without a proof verifies at L2 at most, and the result names agent_did and
proof_floor. tests/test_request_proof_fixtures.py runs helix-core's fixtures/kya-os-helix/request-proof.json.
python -m helix_sdk.conformance [vectors_dir] runs the KYA-OS vector categories signed-proof, delegation-chain,
status-list, did-key, did-web, card-proof and entity-card through helix_sdk.conformance.HelixConformanceAdapter.
Status lists and revocation (KYA-OS story L3-C)
helix_sdk.verifier reads status lists as SPEC.md §6.6 says, exactly as helix-sdk-js does:
read_bitstring_status_list/read_status_list_2021verify the list's own proof (eddsa-jcs-2022, or the §6.2Ed25519Signature2020) by its issuer'sassertionMethodkey before decoding any bit;create_status_list_fetcherfetches through the host's (Safe)fetch. Unreachable, malformed, unsigned, badly signed, wrong-purpose and out-of-range lists read as revoked.create_revocation_checker(thecheck_revocationseam, fail-closed) applies the keeper rules and caches lists and verdicts in aStatusCache(status_cache_ttl,high_privilege_scopesat most 60 s,max_stale_seconds,invalidate(credential_id)); a cached read isfresh=False, which demotes a Card L3 request to L2. Its Redis keys and JSON match the JavaScript cache, so both can share one store.check_chain_revocationwalks a chain root to leaf.verify_revocation_signalchecks Helix's revocation SET (RFC 8417): a trusted issuer and its signature, one credential.- The conformance
status-listcategory runs through these production readers, both list formats.
helix_mcp_middleware uses them the way @helixid/mcp-middleware does:
create_local_verifierreads every list throughcreate_status_list_fetcherand a fail-closed revocation checker, and exposesstatus_cache. Options:status_cache(aStatusCache, or a dict of its options),status_list_issuers,check_revocation. The default fetch iscreate_resolution_fetch: https only, a host written as an IP must be public unicast, same-origin redirects, 5 s, 1 MiB. Pass your SafeFetch asfetchto pin the connection too.- An agent card's own
revocationentry is read too (SPEC-ENTITY-CARD section 10.3): a set bit refuses the call (status_revoked). The entry is the agent's identity credential's, which the agent's account issues, so the list must be signed by thecontrollerthe agent's DID document names (its account's DID), or by the agent's own DID when the document names no controller; any other signer refuses the call (status_list_mismatch). A HelixID-hosted agent needs no configuration here: its document names its account, and the account signs the list. (helix_sdk.verifier.card_list_issuersis that rule; astatus_list_issuersbinding you configure still decides first.) RedisStatusCacheStoreshares the cache between instances (any client with redis-py'sget/set(px=)/delete/incr).RevocationSignalClient/create_revocation_signal_client(verifier, trusted_issuers, ...)receive Helix's SETs: over SSE by default (one outbound connection on a background thread, reconnecting with backoff andLast-Event-ID), or pushed (RFC 8935) throughasgi_webhook()or the framework-neutralhandle_push()(202, or 400{err, description}). A valid SET callsstatus_cache.invalidate(credential_id); a bad or foreign one is ignored and reported throughon_signal.
from helix_mcp_middleware import RedisStatusCacheStore, create_local_verifier, create_revocation_signal_client
verifier = create_local_verifier(
service_did="did:web:mcp.example.com",
status_cache={"store": RedisStatusCacheStore(redis.Redis()), "status_cache_ttl": 300, "high_privilege_scopes": ["orders:admin"]},
)
signals = create_revocation_signal_client(
verifier,
["did:web:api.helixid.example"], # the Helix issuer whose SETs are honoured
events_url="https://api.helixid.example/v1/events/revocations",
on_signal=lambda report: audit(report.to_dict()),
)
signals.start() # or mount signals.asgi_webhook() at the URL registered with Helix
Packages in this repo
helix_sdk-- core SDK (see Quick example above).helix_mcp_middleware-- Model Context Protocol integration, the same Phase 1 surface as@helixid/mcp-middleware:helixid_mcp_middleware()/async_helixid_mcp_middleware()gate every incoming tool call. A caller presents a KYA-OS request proof (MCP_meta["org.kya-os/request-proof"], with its delegation chain at_meta["org.kya-os/delegation-chain"]), which the gate verifies in-process withhelix_sdk.verifier(verifier=LocalVerifierOptions(...)orcreate_local_verifier(), story F-2; the Helix API is never asked), or an OAuth 2.1 bearer token. A bearer token sent with a proof is the proof's sender constraint (cnffusion, L3). The Helix VP is no longer read. The one-line HTTP gate,HelixMcpGate(same names and options as helix-sdk-js'shelixMcpGate), is an ASGI middleware in front of the MCP Streamable HTTP app (mcp2.xMCPServer.streamable_http_app(stateless_http=True, json_response=True)):app = HelixMcpGate(mcp_app, resource=..., verifier=..., tool_scopes=..., kyaos=...), orapp.add_middleware(HelixMcpGate, resource=..., ...)on Starlette/FastAPI. It serves the RFC 9728 metadata and reads each POST to the MCP path. It passes every request through the gate and answers refusals with 401 / 403 / 400 andWWW-Authenticate(503 withRetry-Afterwhen an authorization server is down). It runs the KYA-OS handshake, sessions,needs_authorizationand the response proof, and runs the call in the caller's delegation context and audit call. Leaveauditout and it sends audit by itself withHELIX_API_KEY(see Audit); or pass settings, a trail of your own, orFalse. It builds the verifier's replay store fromKYAOS_NONCE_STOREwhen you giveLocalVerifierOptionswithout one. Then it replays the body to the app behind it. The handshake tool reads the agent its credential identified atrequest.state.helix_mcp_authenticated_agent_did(AUTHENTICATED_AGENT_STATE_KEY). The[mcp-middleware]extra installsmcp>=2.3,<3. Pass every JSON-RPC request through the gate (itsmethod, or therequestas received, plusheadersandclientIp); it decides which need a caller.DEFAULT_OPEN_METHODS(initialize,notifications/initialized,tools/list) pass unchecked and unaudited, on purpose, so clients can see what the server offers; change them withopen_methods([]opens nothing). Every other method needs a verified caller:resources/read/resources/subscribe/resources/unsubscribeare checked againstresource_scopes(by URI) andprompts/getagainstprompt_scopes, both deny by default (RESOURCE_NOT_PERMITTED/PROMPT_NOT_PERMITTED, 403); list methods andpingneed the caller only. Every refusal is audited, including those of a caller the gate could not identify (no credential, a bad bearer, a proof naming no verified DID, a replay,CREDENTIAL_CONFLICT):authMethod: 'none', no actor, with the method and target,reasonCode,clientIp,userAgentand, markedclaimedVerified: False,oauthIssuer/claimedDid; in the typed trailauthorization.deniedwith that reason code.tool_scopesmaps each tool to the scopes it needs and denies unlisted tools; thenminimum_level(defaultL3),tools[name]["minimum_level"]andl3_minus_satisfies_l3set the Card level each tool demands (story C-C; a call below it raisesLevelError, 401insufficient_user_authenticationwithderivedLevel/requiredLevel); every decision goes toaudit_sink, whichHelixMcpGatesets by itself. A failing sink never blocks a call: it is a warning on standard error (oron_audit_error's to handle). The audit log holds typed producer events (KYA-OS AAP-1). A trail'stool_audit_sink()records each decision as typed events: a KYA-OS caller becomesproof.verified(verification codeKYAOS_PROOF_<level>,_CACHEDwhen a status was not read live; story C-C writes an L3 on an unfused proof asL3_MINUSand adds_CNF_UNFUSEDfor thecnfdiagnostic) thenauthorization.approved/authorization.denied(reasonproof_level_insufficientfor a level refusal), a refused request proofproof.rejectedby its first reason code, an OAuth caller the authorization event alone; each strictly validated, sequenced per source withpreviousSourceEventDigestand digested. The gate also records the lifecycle of each tool call (session.established, thentool.call.started/completed/failedthroughaudit_tool_handlers(server), ortool.call.denied, under one correlation id), asexamples/mcp_order_managementdoes. No event holds tool arguments, a response, a token or a credential; an OAuth subject is a keyed commitment; tool names only withinclude_tool_names=True. The typed events themselves (AuditTrail, the strict validator, digests, SPEC 7.8 references, the evidence vault) arehelix_sdk.audit.oauth=takes one trusted issuer or a list:OAuthIssuerOptions(issuer, audience)is enough (keys come from the issuer's metadata), or use the presetsentra(),auth0(),okta(),keycloak(); opaque tokens are checked by RFC 7662 introspection at the one issuer you run.to_http_error_response()andbuild_protected_resource_metadata()give the 401 / 403 challenges and the RFC 9728 document. A runnable server is inexamples/mcp_order_management. Install with themcp-middlewareextra:pip install "helixid-sdk-py[mcp-middleware]".helix_langchain-- LangChain integration:helix_id_tool_wrapper(tool, signer=..., audience=..., chain=...)runs the tool with the agent's Signer, and inside itsign_current_request(request)returns the MCP request with a fresh request proof (and the chain) inparams._meta. Tool input is untouched. Also scope-based tool filtering. Install withpip install helixid-sdk-py[langchain].helix_crewai-- CrewAI integration, following the same pattern ashelix_langchain. There is no CrewAI counterpart inhelix-sdk-js-- this is Python-only. Install withpip install helixid-sdk-py[crewai].
Install everything at once with pip install helixid-sdk-py[all].
Audit: the gate sends it by itself
Set HELIX_API_KEY (this service's API key, from the console) in the service's environment. There is nothing else to set up.
- Audit goes to
https://api.helixid.dev, always. - When
HELIX_API_URLis set to a different address (a self-hosted Helix server), audit goes there too, with the same key. When both are the same address there is one logger. DEFAULT_HELIX_API_URLreplaceshttps://api.helixid.dev, for local testing and development. It is used as written.- At startup the gate asks each address whether this key may write audit for this service and prints
HelixID: audit OK, or the exact reason it is not (HELIX_API_KEY is not set, the address could not be reached, the key was refused, the key is another service's).gate.audit_ready(aconcurrent.futures.Future) holds the result, oneGateAuditCheckper address; the check runs on a background thread and never delays or stops start-up. - A write that fails is a warning on standard error,
HelixID: audit write failed: <reason>(at most one line per 30 s). The tool call still runs.
Events go to the HelixID recorder (POST /v1/audit/submissions), which assigns sequence, epoch, predecessor and time and signs a receipt. The server never chooses any of those.
To change the defaults, pass audit settings to the gate (a dict or a GateAuditSettings: include_tool_names, delivery, outbox_dir, source_id, timeout_seconds, startup_check, log); pass audit=False for no audit, or an McpAuditTrail of your own to send it somewhere else:
app = HelixMcpGate(mcp_app, resource=resource, verifier=verifier, tool_scopes=tool_scopes, audit={"include_tool_names": True})
audit_tool_handlers(server) # the MCPServer, before its tools are registered: each tool records its own started / completed
audit["delivery"] |
What it means |
|---|---|
best-effort (default) |
Delivery is attempted before the call goes on; a failure is a warning and the call runs. |
required |
Fail closed. The intent's signed receipt is obtained before the handler runs; if it cannot be, the call answers audit_delivery_failed and the handler does not run. If the terminal append fails after the handler ran, the result is marked _meta["org.kya-os/audit"] = {"status": "degraded", "reason": ...} with isError. |
buffered |
Events go to a durable outbox (audit["outbox_dir"]) keyed by (sourceId, eventId) and are delivered in the background, in order per source; the outbox survives a restart. |
create_gate_audit(service_did=...) builds the same trail outside the gate (its check() prints the startup line), and
create_helix_audit_delivery(base_url, api_key) is one delivery to one address, for a trail you assemble yourself.
The tenant is the producer (the service DID) unless tenant_ref says otherwise; each tenant DID has its own ledger.
audit_tool_handlers takes the call explicitly, as the JS one does, or uses the tool call the gate opened in the
current context, since a Python server is usually built once. run_audited_tool / async_run_audited_tool wrap a
single handler. HelixClient.get_audit_log(cursor=...) reads the log one page at a time
({"items": [...], "nextCursor": ...}). The order-management sample reads AUDIT_DELIVERY and AUDIT_OUTBOX_DIR.
KYA-OS session, replay store and response proof (helix_mcp_middleware, story L2-A)
The Python twin of @helixid/mcp-middleware's KYA-OS layer, with the same wire format, error codes and replay-store
keys, so JS and Python instances serve one DID side by side:
from helix_sdk import kyaos
from helix_mcp_middleware import KyaOsOptions, create_kyaos
kya = create_kyaos(KyaOsOptions(
signer=kyaos.EnvSigner("did:web:mcp.example.com", env_var="SERVICE_SIGNING_KEY"), # the key stays in the environment
public_origin="https://mcp.example.com",
))
# The handshake tool: await kya.handshake_tool_result(args). Every other tool call:
started = await kya.start({"name": name, "arguments": args, "_meta": meta}, authorize=lambda: gate.authorize(tool_call))
if started.outcome == "denied":
... # to_http_error_response(started.error, metadata_url, proof=started.proof)
result = await started.finish(await handler(started.arguments)) # the result with _meta["org.kya-os/response-proof"]
The client side is helix_sdk.kyaos (create_handshake_request(), verify_response_proof(), which recomputes both
hashes against the server DID). The replay store is the one the environment names unless nonce_store= is passed
(nonce_store_from_env()):
| Variable | Values | Default |
|---|---|---|
KYAOS_NONCE_STORE |
memory, redis, dynamo |
memory |
KYAOS_REDIS_URL |
redis:// or rediss:// URL; required for redis |
|
KYAOS_NONCE_KEY_PREFIX |
Redis key prefix | kyaos:nonce: |
KYAOS_DYNAMO_TABLE |
table name; required for dynamo |
|
KYAOS_DYNAMO_KEY_ATTRIBUTE |
partition key attribute (string) | pk |
KYAOS_DYNAMO_TTL_ATTRIBUTE |
the table's TTL attribute (Unix seconds) | expiresAt |
KYAOS_DYNAMO_REGION |
AWS region | boto3's own |
KYAOS_DYNAMO_ENDPOINT |
endpoint URL, for DynamoDB Local | boto3's own |
AWS credentials come from boto3's standard chain, never from these variables. The clients are optional extras,
imported only when chosen: pip install 'helixid-sdk-py[redis]' (redis-py, used through redis.asyncio) and
pip install 'helixid-sdk-py[dynamo]' (boto3, called from a worker thread). It fails closed: an unknown store, a
missing required variable or a missing package raises NonceStoreConfigError when the runtime is built, and nothing
falls back to memory. One startup line on the helix_mcp_middleware.kyaos logger names the store without secrets (a
Redis password is shown as ***); memory with ENV or NODE_ENV set to production also warns that it covers one
process only.
KYA-OS signed needs_authorization and resume (story L3-E)
Server side (helix_mcp_middleware): when a caller is identified but its delegation does not cover the tool's scopes, the gate answers with the SPEC §9.2 challenge instead of a plain 403: {"error": "needs_authorization", "message", "authorizationUrl", "resumeToken", "expiresAt", "scopes", "display"?}. Under the KYA-OS runtime it is the call's tool result, signed with outcome: needs_authorization and a responseHash over the whole result, so authorizationUrl is covered by the service signature.
from helix_mcp_middleware import MCPMiddlewareOptions, NeedsAuthorizationOptions, create_needs_authorization
needs_authorization = create_needs_authorization(NeedsAuthorizationOptions(
authorization_url=lambda c: f"https://consent.example/authorize?tool={c.tool}",
ttl_seconds=600, # resume-token lifetime
# store: default follows KYAOS_NONCE_STORE (resume_token_store_from_env: Redis on KYAOS_REDIS_URL, else memory)
authorizer=verify_delegation, # the seam stories F-2 and L3-H implement; default refuses every retry
audit_sink=audit_sink, # every challenge: AUTHZ_DENIED, reason "needs_authorization"
))
options = MCPMiddlewareOptions(..., needs_authorization=needs_authorization)
The resume token is opaque, bound to the agent, tool and scopes, single-use and gone at expiresAt; a retry carries it as the _kyaos_resume control argument and the new DelegationCredential as _kyaos_delegation. Completing consent alone never authorises the call. With async_helixid_mcp_middleware the store, authorizer and audit sink may be async. Client side (helix_sdk.needs_authorization): handle_needs_authorization(response, service_did, resolve_did, request=...) verifies the challenge's proof, recomputing both hashes, before it surfaces the URL; retry_with_resume(resume_token, hop, call=..., send=...) retries with the token and the credential.
Forwarding delegation downstream (helix_mcp_middleware, story L3-D)
When a tool calls another service on the agent's behalf (SPEC.md §8), with_delegation(request, signer) wraps any request(method, url, headers=..., **kw) (requests.request, httpx.Client().request, httpx.AsyncClient().request) and sends, on every call, the chain the agent presented (KYA-OS-Delegation-Credential), a JWT this service signs for the target host (mint_delegation_proof_jwt: iss the service, sub the root hop's issuer, aud the host, 60 s, jti, delegation_id, delegation_chain, scope), KYA-OS-Agent-DID and KYA-OS-Session-Id; advisory_headers=True adds the advisory chain and scope headers. The context is delegation_context_of(await gate.authorize(call)), made current with with run_with_delegation(context):. redelegate appends the service's own hop, refused (RedelegationError) unless it attenuates the chain; audit=trail.outbound_audit() records delegation.outbound_attached.
The gate verifies inbound delegation headers with verify_inbound_delegation_headers (inbound_delegation=InboundDelegationSettings(forwarders=..., audience=...), on by default; forwarders defaults to "*", [] for none): the proof's signature, aud, window and jti; sub = the chain's root issuer; the forwarder bound to the chain; KYA-OS-Agent-DID = the agent the chain names; the chain itself by the local verifier, at most L2. Advisory headers never decide. Chain verdicts are cached by credential id (VerificationCache, no longer than the status cache, ≤ 60 s for high-privilege scopes, bypassed for L3 tools) and dropped at once by a revocation signal; DelegationGraph covers L3.14 to L3.19. Same names and reason codes as helix-sdk-js.
The /.well-known/mcp discovery document (helix_mcp_middleware, story L1-D)
create_well_known_mcp() builds the KYA-OS discovery document from config, validates it against the vendored
well-known-mcpi.json schema at startup (raising WellKnownMcpError with the schema's complaints) and serves it over
ASGI; for the same config it is byte for byte the document @helixid/mcp-middleware's createWellKnownMcp() serves.
from helix_mcp_middleware import create_well_known_mcp
well_known = create_well_known_mcp(
public_origin="https://mcp.example.com", # the origin agents connect to; required, never the bind address
server_did="did:web:mcp.example.com", # did:web or did:key; required
tools_endpoint="/mcp", # path at public_origin, or an absolute URL there
kyaos=kya.describe(), # proofs, the handshake and the skew from the L2-A layer
status_list_credential="https://mcp.example.com/credentials/status/1", # optional
capabilities={"delegation": False, "statusList": False, "crisp": False}, # each true only while that feature is on
)
async def app(scope, receive, send):
if await well_known.handle(scope, receive, send): # GET / HEAD /.well-known/mcp; False for anything else
return
...
# any other host: well_known.respond() is (status, headers, body)
HelixMcpGate serves this document by itself whenever it knows its DID (service_did, or the verifier's): the
DID, the MCP endpoint (resource) and whether it signs its answers (from kyaos). well_known=False turns that off
(a host serving its own document, as examples/mcp_order_management does); a dict such as
{"status_list_credential": ...} sets the document's other members. gate.well_known is the document.
enabled=False answers 404. Validation needs jsonschema (in the mcp-middleware and all extras); the uri,
uri-reference and email formats are checked with ajv-formats' own expressions, so both languages refuse the same
documents with the same messages. Route /.well-known/mcp at your origin root to the middleware: helix-sdk-js's
mcp-middleware/docs/well-known.md has the nginx, ALB and API Gateway rules and the public_origin rule. The client
side is helix_sdk.kyaos.fetch_well_known_mcp(origin) / read_well_known_mcp(document), which fill
clockSkewSeconds with 120 when absent and resolve relative endpoints, for create_handshake_request() timing and
verify_response_proof(..., skew_seconds=document["clockSkewSeconds"]).
Examples
See examples/:
request_proof_demo.py-- an agent signs one MCP call withkyaos.with_request_proof()and a service verifies it in-process in the section 11.2 order; a replay, another body and another service are refused. Runs offline:
python examples/request_proof_demo.py
CLI
Platform-operator workflows (DID/wallet/status-list/VC lifecycle) are covered
by helix-sdk-js's cli package -- the CLI has a single canonical
implementation rather than one per SDK language.
The one exception is custody: this package installs a helix command with
helix init, helix activate and helix custody take (take alone also
works; or python -m helix_sdk.custody). They do and print what the
helix-sdk-js commands of the same names do, with the same options, for
Python-only hosts. init and custody take end with what to do next: which
file is secret and the one line that loads it. --json prints the result as
JSON instead. They exit 0
when the command ran, an agent still waiting for its documents included, and
1 with the error on stderr. The same steps are functions: helix_init,
activate_agent, change_to_self_custody.
With own hosting you do not have to run activate: Helix re-checks an agent
waiting for its documents in the background and activates it once they are
live.
A self-custody agent's key is generated on its host and never sent. A
custodial agent signs through HelixCustodialSigner, which calls the Helix
API. Both are Signers, so helix_sdk.verifier.sign_request_proof and sign_jws work
the same with either. Custodial agents are labelled custody: helix and are
not counted in KYA-OS conformance claims; their proofs still verify.
Testing
pip install -e ".[dev,all]"
pytest
pytest always runs with coverage ([tool.pytest.ini_options] in
pyproject.toml) and fails under 60% -- the measured baseline as of
2026-09-03, not a target. helix-sdk-js/helix-api enforce 90%
lines/statements, 85% branches, 90% functions; closing this gap (some
modules, like did.py, currently have no direct unit tests at all) is
real follow-up work, not something this tooling change did on its own.
tests/test_golden_vectors.py-- cross-language crypto parity (no network).tests/test_wallet.py--AgentWalletencrypted persistence, credential storage/queries, and a local-signing round trip. (delegate()and its mocked-HTTP tests were removed.)tests/test_mcp_middleware.py-- the middleware's Phase 1 cases (credentials, scopes, JWT / introspection / several issuers / discovery / presets, HTTP challenges, audit);tests/test_mcp_order_management_example.pyruns the sample behind the MCP SDK's HTTP transport (Python 3.10+).tests/test_framework_adapters.py-- exerciseshelix_mcp_middleware,helix_langchain, andhelix_crewaiagainst the real installedlangchain-coreandcrewaipackages (not mocks of them), so a real interface drift in either framework would fail these tests. Skips gracefully on Python < 3.10, since both frameworks require it.
There is currently no automated live integration test against a real
helix-api instance in this repo's CI (see Known gaps) -- if you have a
running instance, you can exercise the real network path with the
delegation example above.
Known gaps
- No live network integration test yet. The mocked tests above verify
the SDK's logic faithfully, but nothing here has been run against a real,
live
helix-apiprocess end-to-end. (The sandbox used to build this SDK could not start one --helix-api'sserver.tsimports the generated Prisma client unconditionally, even in SQLite storage mode, andprisma generateneeds network access tobinaries.prisma.sh, which was outside that environment's egress allowlist. This is a sandbox-only limitation, not a code issue, and shouldn't block real CI or local development where Prisma can actually run.) Running the two example scripts against a real instance is the recommended way to close this gap. HttpAdapteris synchronous (built onrequests), unlikehelix-sdk-js's asyncfetch-based adapter. This was a deliberate v0 choice -- most Python agent/automation call sites are synchronous -- not an oversight; an async variant can be added later without breaking this one.- No
did:hederapackage yet. DID resolution generally is always an API call in this architecture, so this is really about offline Hedera anchoring specifically, whichhelix-sdk-js'sclipackage supports via a separatedid-hederapackage this repo hasn't ported. Since the CLI itself is JS-only, this gap only matters if this SDK's own local-signing primitives grow adid:hederacreation path. - No
widgetpackage (helix-sdk-js's browser-embeddable consent widget has no obvious Python equivalent and hasn't been attempted). HelixIDCallbackHandlerinhelix_langchainis a no-op. LangChain Python'son_tool_startcallback is a notification hook, not an interceptor. Request signing happens inhelix_id_tool_wrapper(), which hands the toolsign_current_request(); the callback handler is kept only for observability use. (The JS SDK has dropped its callback form,HelixIDMiddleware, entirely.)- Version numbering does not yet track
helix-sdk-js's version. This SDK's version should track the JS SDK's; that mapping strategy hasn't been decided yet, so this starts at0.1.0independently.
The HelixID ecosystem
| Repository | What it is |
|---|---|
| helixid | HelixID API — the issuer and verifier service |
| helix-core | @helixid/core — crypto, schemas, resolver, verification primitives |
| helix-sdk-js | JS/TS SDK, CLI, LangChain + MCP middleware, consent widget |
| helix-sdk-py — you are here | helixid-sdk-py — the Python SDK |
| helix-console | Operator Console SPA |
| helix-wiki | Source for docs.helixid.dev |
License
Apache-2.0
Metadata
Release files for helixid-sdk-py 5.0.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| helixid_sdk_py-5.0.0.tar.gz | 655.8 kB | With provenance | Details for helixid_sdk_py-5.0.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| helixid_sdk_py-5.0.0-py3-none-any.whl | Python 3 | none | any | Details for helixid_sdk_py-5.0.0-py3-none-any.whl |
Total release size: 1.1 MB
Release files / helixid_sdk_py-5.0.0.tar.gz
| Download URL | helixid_sdk_py-5.0.0.tar.gz |
|---|---|
| Size | 655.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
639e3aff5c6c57893ce3a0fcf91c245906a70c2fe171d9aec5d87cc03665f0ae
|
|
BLAKE2b-256 checksum How to use checksums |
8e45a273da753e8e05512468c8df5dcfa00faa683d3dfc633b0214f0af64074a
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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 Dec 1, 2026.
Transparency logRelease files / helixid_sdk_py-5.0.0-py3-none-any.whl
| Download URL | helixid_sdk_py-5.0.0-py3-none-any.whl |
|---|---|
| Size | 427.2 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
941fec539b9700e99fe2bfeeccc72ac4372ab0bbfa1536a244bb7da65acf606a
|
|
BLAKE2b-256 checksum How to use checksums |
4adb360c28bc5f818d2e441f839d46d0d822dd4fcb639e70012b5558352f35c3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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 Dec 1, 2026.
Transparency logSecurity for helixid-sdk-py 5.0.0
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for helixid_sdk_py-5.0.0.tar.gz
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 Dec 1, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.