SDK Manual
Official clients for Go, Python, and TypeScript. All three expose the same enforcing authorize() contract and are released together at matching versions.
Latest published release: v0.8.0. Matching SDK and adapter artifacts have been verified. Publication does not upgrade your deployment or consumers; follow the coordinated upgrade guidance below.
| Language | Package | Install |
|---|---|---|
| Go | github.com/OpenProdkt/governance-sdk-go | go get github.com/OpenProdkt/governance-sdk-go@v0.8.0 |
| Python | openprodkt-governance-sdk | pip install https://github.com/OpenProdkt/governance-sdk-python/releases/download/v0.8.0/openprodkt_governance_sdk-0.8.0-py3-none-any.whl |
| TypeScript | @openprodkt/governance-sdk | npm install https://github.com/OpenProdkt/governance-sdk-typescript/releases/download/v0.8.0/openprodkt-governance-sdk-0.8.0.tgz |
Release pages: Go, Python and TypeScript. The Python wheel and TypeScript tarball above are verified GitHub release assets; this is not a claim of publication to PyPI or npm. For Docker-based enforcement, see the public Envoy PEP image and digest.
0.8.0 release
Changes from 0.7.0 are grouped below by the component that implements them;
publishing SDKs or adapters does not deploy control-plane or Console changes.
SDKs and enforcement adapters
- Go, Python and TypeScript SDKs add bounded exact-number handling and distinguish invalid evaluation context from malformed requests. Unsupported numeric values are rejected rather than silently rounded.
- SDK policy creation supports an explicit draft status while preserving the published default when status is omitted.
- MCP stdio returns invalid context as a denied tool result, not a JSON-RPC
invalid-params error. Envoy preserves the
invalid_contextcode on HTTP 400. Neither adapter calls the upstream for this rejection.
Published SDK source comparisons: Go, Python and TypeScript.
Control plane and Console
- Exact bounded decimal comparison and payload binding, with explicit request versus context errors; unsupported values are rejected rather than rounded.
- Current-schema policy authoring, presence tests, case-sensitive prefix matching, exact list membership and restricted single-leaf negation.
- Draft/published/archived policies. Console creates drafts; API creation without status preserves published behavior. Published edits remain immediately live.
- Definition validation and simulation without decisions, usage charges, approval creation/redemption or execution permission.
See Policy Engine, API Reference and Reason Codes for supported inputs, limits, defaults and errors. The existing no-policy, no-match and unknown-key ALLOW defaults are unchanged. An unknown explicit asset ID fails closed instead.
Upgrade and rollback
Upgrade the control plane, SDKs and relevant enforcement adapters as one coordinated version. Pause approval-bearing operations first, then complete, expire or explicitly revoke old pending and redeemable approvals through the normal approval workflow. Reconcile uncertain executions instead of replaying them. Keep traffic paused while upgrading and verifying the coordinated stack. The same preparation is required before rollback.
The supported upgrade is additive and preserves existing policy activation. An unsupported legacy installation may refuse startup rather than silently convert its data; obtain an approved migration path instead of deleting data. Before rollback, review and, where necessary, revert policies through normal management controls: an earlier evaluator must not be assumed to support the new operators or lifecycle behavior.
Exact numeric canonicalization changes some approval bindings. Do not rewrite
stored bindings, retry with an old hash fallback or replay a consumed operation.
A mismatched retry returns 409 approval_retry_mismatch; start a new operation.
Adding lifecycle status alone preserves existing bindings, but publishing a
revision or archiving a live policy can invalidate a pending retry.
Existing policies retain published status and existing activation; the lifecycle upgrade does not silently stage them as drafts. Review policies against their current asset schema before activation or publication. Archived policies are read-only except deletion or cloning; cloning creates a published, active policy. See Approvals & Delivery.
Before resuming traffic, verify that matching SDK releases and adapter artifacts exist, inspect their integrity information, and confirm the upgraded deployment. Publication and deployment are distinct checks; a release tag alone proves neither. MCP checksum/SBOM limits are described in Install the MCP Adapter.
Authentication
Every SDK client takes a base URL and an API key. Create a key in the Console under API Keys, and grant it the decision:run scope to authorize operations. Applications that poll one approval also need approvals:read.
Every key must have an expiresAt time when it is created. It must be in the future and no more than 365 days out. Expired keys are rejected with 401, so rotate a key before it expires. See API key lifecycle.
The secret is shown once at creation. Store it in your secret manager and never commit it or ship it to a browser.
Evaluate a decision
The core call asks whether an action may proceed. It sends one /v1/evaluate request per operation attempt. Allow and lifecycle pass-through return normally; denial and other non-allow outcomes are typed errors. Every call requires a stable operation_id.
Go
package main
import (
"context"
"errors"
"fmt"
"time"
"github.com/OpenProdkt/governance-sdk-go/governance"
)
func main() {
client := governance.NewClient("https://api.sandbox.openprodkt.com", "opk_live_xxx", 5*time.Second)
resp, err := client.Authorize(context.Background(), governance.AuthorizationRequest{
AssetKey: "billing.invoice-agent.production",
OperationID: "invoice-2026-001",
Metadata: map[string]interface{}{"amount": 9000, "environment": "production"},
})
if err != nil {
var pending *governance.PendingApprovalError
if errors.As(err, &pending) {
fmt.Println(pending.OperationID, pending.ApprovalID, pending.PayloadHash, pending.StatusURL, pending.ExpiresAt)
return
}
panic(err)
}
fmt.Println(resp.Decision, resp.DecisionID)
}
Python
from openprodkt_governance import GovernanceClient, PendingApproval
client = GovernanceClient("https://api.sandbox.openprodkt.com", "opk_live_xxx")
try:
decision = client.authorize(
asset_key="billing.invoice-agent.production",
operation_id="invoice-2026-001",
metadata={"amount": 9000, "environment": "production"},
)
except PendingApproval as pending:
print(pending.operation_id, pending.approval_id, pending.payload_hash, pending.status_url, pending.expires_at)
else:
print(decision.decision, decision.decision_id)
TypeScript
import { AuthorizationDeniedError, GovernanceClient, PendingApproval } from "@openprodkt/governance-sdk";
const client = new GovernanceClient("https://api.sandbox.openprodkt.com", "opk_live_xxx");
try {
const result = await client.authorize({
assetKey: "billing.invoice-agent.production",
operationId: "invoice-2026-001",
metadata: { amount: 9000, environment: "production" },
});
console.log(result.decision, result.decisionId);
} catch (error) {
if (!(error instanceof PendingApproval)) throw error;
console.log(error.operationId, error.approvalId, error.payloadHash, error.statusUrl, error.expiresAt);
}
Handle all three outcomes
authorize() returns normally only for allow and lifecycle pass-through. HTTP 202 throws PendingApproval, which carries the stable operation ID, approval ID, canonical payload hash, asset reference, status URL, and expiry. Denial, rejection, expiry, revocation, consumed redemption, identity collision, operation conflict, quota, invalid input/configuration, and PDP failure have distinct typed outcomes.
try {
await client.authorize({ assetId: "ast_invoice", operationId: "invoice-2026-001" });
await executePayment();
} catch (error) {
if (error instanceof PendingApproval) await parkForReview(error.operationId, error.approvalId);
else if (error instanceof AuthorizationDeniedError) await rejectWithReason(error.response.reason);
else throw error;
}
Persist the stable operation_id with your business operation. Policy-evaluated outcomes may also include a decisionId. Unknown-asset pass-throughs create no decision record or ID. A registered asset with no policies returns a decisionId but is not billed.
Handling approval_required
See Approvals & Delivery for the full picture: async webhook delivery is the recommended default, with app-managed retry, a short-wait option, and polling available for other integration shapes.
Async + webhook (recommended). Register a webhook endpoint once; your app resumes the
original operation when the approval.approved event arrives, independent of any SDK call.
App-managed retry. Store the pending error's operationId, approvalId, payloadHash, asset identity, and normalized context. After approval, retry the same authorize() call with the tuple. The PDP returns normally only after atomically consuming the approval.
Short wait. For interactive UX, block briefly for resolution instead of returning immediately:
const result = await client.authorizeAndWait(
{ assetId: "ast_invoice", operationId: "invoice-2026-001", metadata: { amount: 9000 } },
{ timeoutMs: 10_000, initialIntervalMs: 250, maxIntervalMs: 1_000 },
);
result = client.authorize(asset_id="ast_invoice", operation_id="invoice-2026-001", metadata={"amount": 9000}, wait_for_approval_seconds=10)
resp, err := client.AuthorizeAndWait(ctx, governance.AuthorizationRequest{
AssetID: "ast_invoice", OperationID: "invoice-2026-001",
Metadata: map[string]interface{}{"amount": 9000},
}, 10*time.Second, 1*time.Second)
Short wait never replaces async delivery for production workloads — it exists for cases where a user is actively waiting on the result.
Limits and defaults. Wait values are bounded in every SDK:
| SDK | Synchronous wait | Status wait limit | Polling defaults |
|---|---|---|---|
| Python | wait_for_approval_seconds 0 to 30 | timeout_seconds 0 to 300 | Initial 1.0 s, maximum 5.0 s, 0.1 jitter |
| Go | AuthorizeAndWait up to 30 s | Wait options up to 300 s | Initial 1 s, maximum 5 s |
| TypeScript | timeoutMs up to 30,000 | Status timeoutMs up to 300,000 | Initial 250 ms, default timeout 10 s |
Status polling reads one approval and creates no usage.
Polling. getApprovalStatus(approvalId) / get_approval_status(approval_id) / GetApprovalStatus(ctx, id) reads one scoped approval. API keys require approvals:read; a decision-only key receives a typed scope error rather than a PDP outage.
Trace context and proxy outcomes
Availability. These calls and fields exist only in SDK builds that include trace and outcome correlation. They are additive: existing calls keep working unchanged. Check the release notes of the version you install, and use them only against a control plane that supports them (see API Reference).
The SDKs let you pass trace context and execution identifiers explicitly. They never create them.
- Trace context. Pass your current W3C
traceparentvalue toauthorizeorevaluate_proxy. It is sent only as an HTTP header, never in the request body. A value that is not a validtraceparentis silently omitted from the request and does not raise an error, so the control plane starts a new trace. The control plane's responsetraceparentis available on the result. - Proxy evaluation.
EvaluateProxy/evaluate_proxy/evaluateProxyis for enforcement adapters. It posts the canonical request to/v1/proxy/evaluate, requires an explicit principal and never falls back to the client API key. Application code should keep usingauthorize. - Typed outcome.
ReportOperationOutcome/report_operation_outcome/reportOperationOutcomeposts to/v1/proxy/outcomeswith an explicit principal.execution_id,attemptandupstream_request_idare optional and validated before sending (see formats and bounds); an invalid value raises the SDK's invalid-input error without a request. - Rejected outcomes. A definitive client error (
4xxother than408and429) raisesOperationOutcomeRejectedError. Do not retry that report. Other failures may be transient. Retry the identical report, including the sameexecution_id, and never re-run the operation because a report failed. - Transport safety. The SDK rejects raw MCP
argumentsin the transport and rejectsAuthorization,Proxy-Authorization,CookieandSet-Cookiein HTTP headers or gRPC metadata. Send a payload digest instead of arguments.
Go
principal := &governance.PrincipalContext{BearerToken: proxyPrincipalToken}
resp, err := client.EvaluateProxy(ctx, governance.EvaluateRequest{
Traceparent: "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
Version: "v1",
Asset: governance.EvaluateAsset{Key: "billing.refund-api.production"},
OperationID: "refund-123",
Transport: governance.TransportContext{Kind: "http"},
}, principal)
if err != nil {
return err
}
fmt.Println(resp.Decision, resp.Traceparent) // response header, not JSON
executionID := "0196f111-1234-7123-8123-123456789abc"
attempt := 1
_, err = client.ReportOperationOutcome(ctx, governance.OperationOutcomeRequest{
OperationID: "refund-123",
Status: "succeeded",
CompletedAt: time.Now().UTC(),
ExecutionID: &executionID,
Attempt: &attempt,
}, principal)
AuthorizationRequest also has a Traceparent field for Authorize.
Python
from datetime import datetime, timezone
from openprodkt_governance import GovernanceClient, PrincipalContext
client = GovernanceClient("https://api.sandbox.openprodkt.com", "opk_live_xxx")
principal = PrincipalContext(bearer_token=proxy_principal_token)
result = client.evaluate_proxy(
{
"version": "v1",
"asset": {"key": "billing.refund-api.production"},
"operation_id": "refund-123",
"transport": {"kind": "http"},
},
principal_context=principal,
traceparent="00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
)
print(result.decision, result.traceparent) # response header, not a serialized field
client.report_operation_outcome(
{
"operation_id": "refund-123",
"status": "succeeded",
"completed_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
"execution_id": "0196f111-1234-7123-8123-123456789abc",
"attempt": 1,
},
principal_context=principal,
)
authorize(..., traceparent=...) accepts the same value.
TypeScript
import { GovernanceClient } from "@openprodkt/governance-sdk";
const client = new GovernanceClient("https://api.sandbox.openprodkt.com", "opk_live_xxx");
const principal = { bearerToken: proxyPrincipalToken };
const result = await client.evaluateProxy(
{
version: "v1",
asset: { key: "billing.refund-api.production" },
operation_id: "refund-123",
transport: { kind: "http" },
},
principal,
"00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01",
);
console.log(result.decision, result.traceparent); // non-enumerable: not in JSON.stringify output
await client.reportOperationOutcome(
{
operation_id: "refund-123",
status: "succeeded",
completed_at: new Date().toISOString(),
execution_id: "0196f111-1234-7123-8123-123456789abc",
attempt: 1,
},
principal,
);
authorize({ ..., traceparent }) accepts the same value.
AI inventory on assets
The asset write calls (createAsset / create_asset / CreateAsset and the matching update calls) take the optional ai_inventory object described in AI inventory on assets. They need the same scope and role as any asset write. In Python it is the ai_inventory keyword argument; in Go and TypeScript it is the AIInventory / ai_inventory member of the request.
client.create_asset(
"support-assistant", "production", "support",
ai_inventory={"intended_purpose": "Drafts replies for support agents", "risk_tier": "limited"},
)
These SDK features do not add telemetry export, automatic ID generation or retries.
One-shot outcome guard
Availability. The guard exists only in SDK builds that include it. It is additive:
evaluateProxyandreportOperationOutcomekeep working unchanged. Check the release notes of the version you install, and use it only against a control plane that accepts proxy evaluation and outcome reports (see API Reference).
The guard wraps one call to your own code. It asks for a decision, runs your code once if the decision is allow, then reports what happened. It is a convenience over EvaluateProxy followed by ReportOperationOutcome, not a new contract: the reports use the same endpoint, the same format and the same first-report rule.
| SDK | Call | Result |
|---|---|---|
| Go | governance.Guard(ctx, client, request, principal, options, execute), a package function. options is governance.GuardOptions{ExecutionID, Attempt, UpstreamRequestID} (optional *string, *int, *string). execute is func(context.Context) (T, error). | GuardResult[T] with Value, Report (an OperationOutcomeRequest) and ReportingError, plus the error return |
| Python | client.guard(request, callback, *, principal_context, options=None). options is a dict with optional execution_id, attempt, upstream_request_id and traceparent. callback takes no arguments and must be synchronous. | GuardResult with value, report and reporting_error |
| TypeScript | await client.guard(request, callback, principal, options?). options has optional execution_id, attempt, upstream_request_id and traceparent. callback may be synchronous or return a promise. | { value, report, reportingError? } |
How it behaves in all three SDKs:
- Explicit principal. Like
evaluateProxy, the guard requires an explicit principal and never falls back to the client API key. The principal that receives theallowis the one that reports the outcome. - Checked before anything is sent. A missing principal or an invalid
execution_id,attemptorupstream_request_id(see formats and bounds) raises the SDK's invalid-input error. No request is sent and your code does not run. - One decision, at most one execution. The guard evaluates the request once, using proxy evaluation. Your code runs only when the decision is
allowand anyoperation_idin the response matches the one you sent. Fordeny,approval_required, a mismatched response or a failed evaluation call, the guard returns or raises an error, your code does not run and nothing is reported. The guard does not wait for an approval, redeem one or poll for one; handleapproval_requiredas described in Handlingapproval_required. - What it reports.
succeededwhen your code returns normally.unknownwhen it raises, returns an error or panics, because the SDK cannot tell whether the operation took effect. The guard never reportsfailed. If you need to reportfailedor send aresult_hash, callreportOperationOutcomeyourself instead of using the guard. The report carriesoperation_id, the status, a UTC completion time taken after your code finishes, and the optional identifiers you passed inoptions. The guard does not create anexecution_id; pass one if you want it correlated. - Nothing from your code is sent. The return value and the error text are not serialized, hashed, logged or sent. The options and the principal are copied before your code runs, so changing them inside the callback does not change the report.
- Your errors are not masked. An error raised or returned by your code reaches you unchanged. In Go a panic is reported as
unknownand then re-panicked. - Report delivery never changes the result. The guard makes one report attempt and does not retry. When your code succeeds but the report cannot be delivered, you still receive the value, and the delivery error is in
ReportingError/reporting_error/reportingError. In Go,ReportingErroris also set when your code failed and the report failed. In Python and TypeScript, when your code raises, your exception propagates and a failure to deliver theunknownreport is not surfaced.
Report-only retries
If delivery failed, retry only the report. Take the report from the result (Report / report), which is a detached snapshot with the same completion time and identifiers, and send it again with ReportOperationOutcome / report_operation_outcome / reportOperationOutcome. An identical retry is accepted as idempotent, and a late first report is still accepted (see late reports). Do not call the guard again: that would ask for a new decision and run your code a second time. Do not retry a report rejected with OperationOutcomeRejectedError.
Go
principal := &governance.PrincipalContext{BearerToken: proxyPrincipalToken}
executionID := "0196f111-1234-7123-8123-123456789abc"
attempt := 1
result, err := governance.Guard(ctx, client, governance.EvaluateRequest{
Version: "v1",
Asset: governance.EvaluateAsset{Key: "billing.refund-api.production"},
OperationID: "refund-123",
Transport: governance.TransportContext{Kind: "http"},
}, principal, governance.GuardOptions{ExecutionID: &executionID, Attempt: &attempt},
func(ctx context.Context) (string, error) {
return issueRefund(ctx) // runs once, only after allow
})
if err != nil {
return err // not allowed, invalid input, or the error from issueRefund
}
if result.ReportingError != nil {
// Retry only the report. Never call Guard again.
_, _ = client.ReportOperationOutcome(ctx, result.Report, principal)
}
Python
result = client.guard(
{
"version": "v1",
"asset": {"key": "billing.refund-api.production"},
"operation_id": "refund-123",
"transport": {"kind": "http"},
},
lambda: issue_refund(), # runs once, only after allow
principal_context=principal,
options={"execution_id": "0196f111-1234-7123-8123-123456789abc", "attempt": 1},
)
if result.reporting_error is not None:
# Retry only the report. Never call guard again.
client.report_operation_outcome(result.report, principal_context=principal)
TypeScript
const result = await client.guard(
{
version: "v1",
asset: { key: "billing.refund-api.production" },
operation_id: "refund-123",
transport: { kind: "http" },
},
() => issueRefund(), // runs once, only after allow
principal,
{ execution_id: "0196f111-1234-7123-8123-123456789abc", attempt: 1 },
);
if (result.reportingError !== undefined) {
// Retry only the report. Never call guard again.
await client.reportOperationOutcome(result.report, principal);
}
Not provided
- No async callbacks in Python. A coroutine function is rejected with the invalid-input error before any request is sent. A callback that returns an awaitable is rejected after it ran, and the outcome is reported
unknown. - No streaming, context-manager or decorator form. The guard wraps one synchronous or promise-returning call. A long-running or streaming operation needs
ReportOperationOutcomecalled by your code when it finishes. - No automatic
failed, result hash, retries, approval waiting or ID generation. - No automatic reporting on other paths. The guard does not make the transparent proxy report outcomes. See Transparent Proxy and MCP Adapter.
Method reference
The same operations are available in all three SDKs. Naming follows each language's convention — authorize / Authorize, listAssets / list_assets / ListAssets.
| Area | Operations |
|---|---|
| Decisions | authorize, playgroundCheck |
| Enforcement adapters | evaluateProxy, reportOperationOutcome, getOperationStatus (see Trace context and proxy outcomes), guard / Guard (see One-shot outcome guard) |
| Assets | listAssets, createAsset, updateAsset, deleteAsset |
| Discovery | ingestAssetDiscovery, listAssetDiscoveries, deleteAssetDiscovery |
| Groups | listGroups, createGroup, updateGroup, deleteGroup |
| Policies | listPolicies, createPolicy, deletePolicy |
| Approvals | listApprovals, getApprovalStatus, waitForApproval, rejectApproval (requires a user JWT) |
| API keys | listApiKeys, createApiKey, rotateApiKey, revokeApiKey |
| History | listDecisionExplorer, listAuditEvents, usage |
| Account | requestCode, verifyCode, register, me, settings |
Each call requires the matching API key scope, except rejectApproval, which requires a user JWT. See Auth and Access for the full scope list.
Reporting detected assets
If you run a detection point that observes AI tools in your infrastructure, use the discovery ingest call. It requires the asset_discovery:write scope.
client.ingest_asset_discovery({
"discovery_id": "dsc_01J...",
"asset": {
"key": "billing.refund-api",
"displayName": "Billing Refund API",
"kind": "rest_api",
"environment": "production",
},
"metadata": {"operation": "refund", "amount": 250},
})
Discovery is observation only. It does not evaluate a policy and does not return a decision. Observations appear in the Console for a human to review and promote.
Protocol adapters
HTTP and gRPC adapters normalize their own transport context into the same /v1/evaluate contract. gRPC streams are authorized once, at stream establishment; messages on an established stream are not authorized individually. A stream retried after an approval challenge must carry the stored approval tuple (approval_id, payload_hash, and the same operation_id). MCP is a first-class adapter (MCP -> MCP PEP -> PDP), not a generic HTTP wrapper. The stdio PEP normalizes tools/call, tool and server identity, and tool arguments. The Envoy adapter applies the same normalization to Streamable HTTP MCP endpoints. See MCP Adapter.
Framework setup
Install the optional extras when you use a framework integration:
- Python FastAPI:
pip install "openprodkt-governance-sdk[fastapi] @ https://github.com/OpenProdkt/governance-sdk-python/releases/download/v0.8.0/openprodkt_governance_sdk-0.8.0-py3-none-any.whl". Usecreate_authorization_dependencyto authorize routes andinstall_fastapi_exception_handlers(app)to map non-allow outcomes to HTTP responses: denial to403, pending approval to202, quota to402, and PDP failure to503. - Python gRPC:
pip install "openprodkt-governance-sdk[grpc] @ https://github.com/OpenProdkt/governance-sdk-python/releases/download/v0.8.0/openprodkt_governance_sdk-0.8.0-py3-none-any.whl". The client and server interceptors authorize each call or stream once, before the handler runs. - Go
net/http: wrap your handler withClient.HTTPMiddleware, which authorizes each request and passes non-allow outcomes to your handler callback. Read the allow decision inside the handler withDecisionFromHTTPRequest. - TypeScript:
authorizeFetchRequestfor Fetch-based runtimes andauthorizeNodeRequestfor Node. For gRPC, usecreateGrpcClientInterceptororcreateGrpcServerInterceptor.
Framework adapters take the operation ID from an explicit argument or the Idempotency-Key header. They never read identity from metadata.actor.
Versioning
All three SDKs have verified 0.8.0 releases. Pin an exact version in production and upgrade deliberately; matching versions do not remove language-specific numeric limits.
Next steps
- Developer Guide for errors, pagination, and retries
- API Reference for the raw HTTP surface
- Swagger UI to try calls in the browser