Skip to content

AI Framework Integration

RunTimeAdmin edited this page Oct 29, 2026 · 19 revisions

AI Framework Integration

**Referenced Files in This Document** - [ai-frameworks.md](https://github.com/RunTimeAdmin/Sigvara/blob/main/docs/ai-frameworks.md) - [index.ts](https://github.com/RunTimeAdmin/Sigvara/blob/main/packages/sdk/src/index.ts) - [agent.ts](https://github.com/RunTimeAdmin/Sigvara/blob/main/packages/sdk/src/agent.ts) - [verifier.ts](https://github.com/RunTimeAdmin/Sigvara/blob/main/packages/sdk/src/verifier.ts) - [gate.ts](https://github.com/RunTimeAdmin/Sigvara/blob/main/packages/sdk/src/gate.ts) - [challenge.ts](https://github.com/RunTimeAdmin/Sigvara/blob/main/packages/sdk/src/challenge.ts) - [types.ts](https://github.com/RunTimeAdmin/Sigvara/blob/main/packages/sdk/src/types.ts) - [server.mjs](https://github.com/RunTimeAdmin/Sigvara/blob/main/examples/mcp-gated-tool/server.mjs) - [index.js](https://github.com/RunTimeAdmin/Sigvara/blob/main/oracle/index.js) - [reputation-model.md](https://github.com/RunTimeAdmin/Sigvara/blob/main/docs/reputation-model.md)

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion
  10. Appendices

Introduction

This document explains how to integrate Sigvara with popular AI frameworks and build reputation-aware agents that verify counterparties before sensitive operations. It covers:

  • SDK patterns for identity, challenge-response authentication, and reputation checks
  • Patterns for LangChain, AutoGen, CrewAI, and TypeScript/Node.js integrations
  • Building gated toolchains where trust is enforced before execution
  • Configuration templates, environment variables, and deployment considerations
  • Performance optimization strategies for high-frequency reputation checks
  • Testing approaches and debugging techniques for reputation-related issues

The integration pattern is consistent across frameworks:

  • Create a deterministic agent identity at startup
  • Audit actions by including the agent DID in audit events
  • Verify signatures and reputation thresholds before trusting or delegating work

The SDK described here is 1.0.0-alpha.12, published to npm on 29 October 2026. New since 1.0.0-alpha.11: the agent's signChallenge is removed, so a call does not compile in TypeScript and throws in JavaScript, and signChallengeFor is the way to sign. New since 1.0.0-alpha.10: verifySignature requires the expected audience (see the changelog). SigvaraAgent.signChallengeFor, the read timeout, the parallel status and score read, the gate's bond check and optional maxScoreAgeSeconds limit, and the other items listed for 1.0.0-alpha.10 in the changelog are new since 1.0.0-alpha.9.

Section sources

Project Structure

At a high level, the repository provides:

  • A TypeScript SDK exposing identity, verification, gating, challenges, and types
  • Example MCP server demonstrating a reputation-gated tool
  • Oracle service computing and serving reputation data
  • Documentation describing the reputation model and framework integration patterns
graph TB
subgraph "SDK"
IDX["index.ts"]
AGT["agent.ts"]
VER["verifier.ts"]
GAT["gate.ts"]
CHA["challenge.ts"]
TYP["types.ts"]
end
subgraph "Examples"
MCP["server.mjs"]
end
subgraph "Oracle"
ORA["index.js"]
end
subgraph "Docs"
AF["ai-frameworks.md"]
RM["reputation-model.md"]
end
IDX --> AGT
IDX --> VER
IDX --> GAT
IDX --> CHA
IDX --> TYP
MCP --> GAT
MCP --> VER
ORA --> RM
AF --> IDX
AF --> VER
Loading

Diagram sources

Section sources

Core Components

The SDK exposes cohesive primitives for building reputation-aware agents:

  • Identity and signing: SigvaraAgent generates keys, derives DIDs, and signs challenges. signChallengeFor(payload, audience) signs only a challenge addressed to the audience the caller names. The agent's signChallenge(payload), which signed whatever it was handed, is removed in 1.0.0-alpha.12 (alpha.9 has only signChallenge)
  • Verification: SigvaraVerifier reads on-chain identity and reputation, verifies signatures, and checks thresholds
  • Gating: SigvaraGate issues nonces, enforces replay protection, validates proofs, and admits/refuses based on status and score
  • Challenge protocol: generateChallenge, signChallenge, verifyChallenge, payload parsing, and expiry checks
  • Types: shared interfaces for contracts, statuses, reputation data, challenges, and verifier configuration

Key responsibilities:

  • SigvaraAgent: deterministic DID derivation, Ed25519 key management, challenge issuance/signing
  • SigvaraVerifier: RPC provider, contract wrappers, signature verification, reputation queries
  • SigvaraGate: nonce store abstraction, audience binding, admission logic with clear refusal reasons
  • challenge.*: v1/v2 payloads, base58 signatures, expiration semantics
  • types.*: contract addresses, agent status, reputation fields, challenge structures

Section sources

Architecture Overview

The recommended architecture for reputation-aware AI agents:

  • Agents generate a DID and sign challenges when challenged by peers or services
  • Services gate access by verifying signatures and checking on-chain reputation thresholds
  • Auditing is performed per action, typically fire-and-forget, to preserve critical-path performance
  • Reputation is computed off-chain by the oracle and served via on-chain contracts
sequenceDiagram
participant Client as "AI Agent"
participant Service as "Gated Service"
participant Gate as "SigvaraGate"
participant Verifier as "SigvaraVerifier"
participant Chain as "On-chain Contracts"
Client->>Service : "tools/call restricted_search(did, query)"
Service->>Gate : "challenge(did)"
Gate-->>Service : "{payload, expiresAt, audience}"
Service-->>Client : "challenge response"
Client->>Client : "signChallengeFor(payload, audience)"
Client->>Service : "restricted_search(did, challenge, signature, query)"
Service->>Gate : "admit(did, challenge, signature)"
Gate->>Verifier : "verifySignature(...)"
Verifier->>Chain : "read identity + signature verify"
Verifier-->>Gate : "verified?"
Note over Gate,Verifier : status, bond and score are read together
Gate->>Verifier : "isActive(did) and hasMinimumStake(did)"
Verifier->>Chain : "read status and bond"
Verifier-->>Gate : "active and bonded?"
Gate->>Verifier : "getTotalScore(did)"
Verifier->>Chain : "read matured score"
Verifier-->>Gate : "score"
Gate-->>Service : "admit result (ok, reason, score)"
Service-->>Client : "work or refusal"
Loading

Diagram sources

Detailed Component Analysis

SDK Class Model

classDiagram
class SigvaraAgent {
-keyPair
-_agentAddress
-_chainId
-_challengeTtl
+constructor(options)
+static generate(options)
+agentAddress
+did
+didHash
+publicKeyBytes32
+issueChallenge(peerDid, ttlSeconds)
+signChallengeFor(payload, audience)
}
class SigvaraVerifier {
-provider
-addresses
-_chainId
-_identity
-_reputation
-_staking
+constructor(config)
+getIdentity(did)
+isActive(did)
+getReputation(did)
+getTotalScore(did)
+getScoreUpdatedAt(did)
+meetsThreshold(did, threshold)
+getStake(did)
+hasMinimumStake(did)
+verifySignature(did, challengePayload, signatureBase58, maxAgeSeconds, expectedAudience)
+buildDidDocument(did)
}
class SigvaraGate {
-verifier
-nonces
-ttl
-inFlight
+threshold
+audience
+constructor(config)
+challenge(did)
+admit(did, challenge, signatureBase58)
}
class Challenge {
+payload
+nonce
+timestamp
+expiresAt
+audience
}
SigvaraGate --> SigvaraVerifier : "uses"
SigvaraAgent --> Challenge : "issues"
Loading

Diagram sources

Section sources

LangChain Integration Pattern

  • Wrap tools so every call includes the agent DID and posts an audit event
  • Use a verifier to enforce minimum reputation before executing sensitive tasks
  • The Python examples are illustrative pseudocode; there is no Python SDK, and the sigvara package they import does not exist. Production Python agents should call the oracle HTTP API directly or run the TypeScript SDK in a sidecar
  • The oracle's /score is a preview, not the finalized score. To gate on a threshold, read getTotalScore or meetsThreshold from the reputation contract with a plain eth_call, which any language can make. Both read the matured score alone and ignore status and bond, so also check isActive and hasMinimumStake, or call SigvaraReader.isTrusted (deployed nowhere yet)

Implementation guidance:

  • Initialize SigvaraAgent from environment variables
  • For each tool execution, post an audit event asynchronously
  • Before running sensitive operations, check meetsThreshold with a policy-defined minimum score, together with isActive and hasMinimumStake (meetsThreshold ignores status and bond)

Section sources

AutoGen Integration Pattern

  • Extend the assistant to attach Sigvara identity and audit every reply
  • Include connector ID, agent DID, and message metadata in audit events
  • Keep auditing fire-and-forget to avoid blocking LLM generation

Section sources

CrewAI Integration Pattern

  • Attach Sigvara identity to crew members and audit task results via callbacks
  • Ensure the callback posts audit events with task name and result preview

Section sources

TypeScript / Node.js Integration Pattern

  • Use middleware to wrap async functions and emit audit events without blocking
  • Implement challenge-response for agent-to-agent authentication: answer an inbound challenge with signChallengeFor(payload, peerDid), where peerDid comes from the connection and not from the payload, and verify an inbound agent with verifySignature(did, payload, signature, 300, myAgent.did) so that a relayed response fails (signChallengeFor is in 1.0.0-alpha.10 and later)
  • Verify signatures and reputation thresholds before trusting peer output
flowchart TD
Start(["Start"]) --> Init["Initialize SigvaraAgent<br/>from private key and chain config"]
Init --> Wrap["Wrap async function with audit middleware"]
Wrap --> Call["Call wrapped function"]
Call --> Audit["Fire-and-forget audit POST"]
Audit --> Return(["Return result"])
Loading

Diagram sources

Section sources

Reputation-Gated Toolchain (MCP Example)

The MCP example demonstrates a two-step handshake:

  • Step 1: Request a challenge for the caller’s DID
  • Step 2: Submit the signed challenge along with the requested operation

The server enforces:

  • Signature verification against the registered public key
  • Audience binding to prevent cross-service replay
  • Nonce uniqueness to prevent replays
  • Active status and maturity-based score threshold
sequenceDiagram
participant Host as "MCP Host"
participant Server as "Gated MCP Server"
participant Gate as "SigvaraGate"
participant Verifier as "SigvaraVerifier"
participant Chain as "On-chain Contracts"
Host->>Server : "tools/list"
Server-->>Host : "sigvara_challenge, restricted_search"
Host->>Server : "sigvara_challenge{ did }"
Server->>Gate : "challenge(did)"
Gate-->>Server : "{ payload, expiresAt, audience }"
Server-->>Host : "challenge object"
Host->>Host : "signChallengeFor(payload, audience)"
Host->>Server : "restricted_search{ did, challenge, signature, query }"
Server->>Gate : "admit(did, challenge, signature)"
Gate->>Verifier : "verifySignature(...)"
Verifier->>Chain : "read identity + verify"
Verifier-->>Gate : "verified?"
Note over Gate,Verifier : status, bond and score are read together
Gate->>Verifier : "isActive(did) and hasMinimumStake(did)"
Verifier->>Chain : "read status and bond"
Verifier-->>Gate : "active and bonded?"
Gate->>Verifier : "getTotalScore(did)"
Verifier->>Chain : "read matured score"
Verifier-->>Gate : "score"
Gate-->>Server : "admit result"
Server-->>Host : "admitted or refusal"
Loading

Diagram sources

Section sources

Challenge Protocol Flow

flowchart TD
Issue["Generate challenge<br/>(prover DID, audience, TTL)"] --> Sign["Sign payload with agent private key"]
Sign --> Submit["Submit (did, payload, signature)"]
Submit --> Parse["Parse payload and validate version"]
Parse --> Expire{"Expired?"}
Expire --> |Yes| Reject["Reject as bad proof"]
Expire --> |No| Verify["Verify signature against on-chain public key"]
Verify --> Valid{"Valid?"}
Valid --> |No| Reject
Valid --> CheckNonce["Check nonce uniqueness"]
CheckNonce --> NonceOK{"Nonce used?"}
NonceOK --> |Yes| Replay["Reject as replayed"]
NonceOK --> |No| Status["Check active status and bond"]
Status --> Active{"Active and bonded?"}
Active --> |No| NotActive["Reject as not active"]
Active --> Score["Read matured score"]
Score --> Fresh{"Too old? Only if maxScoreAgeSeconds is set"}
Fresh --> |Yes| Stale["Reject as stale_score"]
Fresh --> |No| Threshold{"Meets threshold?"}
Threshold --> |No| Below["Reject as below_threshold"]
Threshold --> |Yes| Admit["Admit"]
Loading

Diagram sources

Section sources

Dependency Analysis

The SDK components have clear dependencies:

  • index.ts re-exports core classes and utilities
  • SigvaraAgent depends on cryptographic helpers and challenge generation
  • SigvaraVerifier depends on ethers RPC, ABIs, DID utilities, challenge verification, and key encoding
  • SigvaraGate depends on SigvaraVerifier and challenge utilities, plus a nonce store abstraction
  • The MCP example depends on SigvaraGate and environment configuration
graph LR
IDX["index.ts"] --> AGT["agent.ts"]
IDX --> VER["verifier.ts"]
IDX --> GAT["gate.ts"]
IDX --> CHA["challenge.ts"]
IDX --> TYP["types.ts"]
GAT --> VER
GAT --> CHA
VER --> CHA
VER --> TYP
MCP["server.mjs"] --> GAT
MCP --> VER
Loading

Diagram sources

Section sources

Performance Considerations

Optimization strategies for high-frequency reputation checks:

  • Use getTotalScore instead of full reputation tuples when only the total matters
  • Let SigvaraGate read the status, the bond and the score together, and keep the default 30 second read timeout or set timeoutMs, so a quiet RPC does not hold every admit for ethers' five minutes
  • Batch independent RPC calls using ethers’ built-in batching to reduce round trips
  • Cache contract instances and chain IDs to avoid repeated initialization
  • Prefer view calls and read-only operations for reputation checks
  • Use fire-and-forget auditing to keep critical paths fast
  • Employ a distributed nonce store for multi-instance deployments to prevent replays
  • Tune TTL and audience values to balance security and latency

Oracle-side optimizations include:

  • Chunked epoch processing to avoid releasing too many RPC requests at once
  • Concurrent reads within chunks to leverage JSON-RPC batching
  • Payer score caching per epoch to reduce repeated chain reads
  • Deterministic timekeeping using chain timestamps to ensure reproducibility

Section sources

Troubleshooting Guide

Common issues and diagnostics:

  • Bad proof: signature does not verify, wrong audience, or malformed payload
  • Replayed: valid signature but nonce already consumed
  • Not active: agent is unbonded (or bonded below the minimum stake in force now), suspended, or slashed
  • Stale score: only with maxScoreAgeSeconds: the score was written longer ago than the limit, or never
  • Below threshold: agent proved itself but matured score is insufficient

Debugging steps:

  • Validate challenge payload format and version
  • Confirm audience matches the service identifier
  • Check nonce lifecycle and storage backend
  • Inspect agent status and stake requirements
  • Compare matured score vs earned score to understand threshold behavior
  • Review oracle logs for epoch failures, payment scan errors, and divergence records

Environment and configuration checks:

  • Ensure required environment variables are set for RPC, addresses, and credentials
  • Verify chain ID consistency between SDK and oracle
  • Confirm threshold settings align with policy goals

Section sources

Conclusion

Sigvara enables reputation-aware AI agents through a consistent SDK pattern:

  • Establish deterministic identity and audit every action
  • Authenticate counterparties with challenge-response and audience binding
  • Enforce gates based on active status and matured reputation scores
  • Optimize for performance with batching, caching, and fire-and-forget auditing
  • Deploy with robust configuration, monitoring, and testing practices

These patterns apply uniformly across LangChain, AutoGen, CrewAI, and custom TypeScript/Node.js adapters, while the MCP example demonstrates a production-ready gated toolchain.

Appendices

Framework-Specific Configuration Templates

  • LangChain/AutoGen/CrewAI (Python): use environment variables for agent seed, address, chain ID, and CounterAudit API key; call oracle HTTP endpoints directly if no Python SDK exists
  • TypeScript/Node.js: initialize SigvaraAgent with private key, agent address, and chain ID; configure SigvaraVerifier and SigvaraGate with RPC URL, contract addresses, threshold, and audience

Section sources

Environment Variables and Deployment Notes

  • Required oracle variables: RPC URL, oracle private key (or ORACLE_PRIVATE_KEY_FILE), identity address, reputation address. A write token (ORACLE_ADMIN_TOKEN or an ORACLE_TOKEN_<NAME>) is required for any bind other than loopback, and the fee registry and external registry settings are optional
  • SDK variables: RPC URL, contract addresses, chain ID, threshold, audience
  • MCP server variables: chain ID, threshold, audience, RPC URL

Section sources

Reputation Model Summary

  • Six-factor deterministic score: fee activity, success rate, tenure, external trust, community, propagation
  • Maturity controls spendable score growth
  • Bonding requirement before scoring
  • Slashing resets all factors and marks agent terminal

Section sources

Overview

Clone this wiki locally