Documentation Index
Fetch the complete documentation index at: https://mintlify.com/microsoft/agent-governance-toolkit/llms.txt
Use this file to discover all available pages before exploring further.
The agentmesh Go package provides idiomatic governance primitives for AI agents. It delivers Ed25519 cryptographic identity, configurable trust scoring, declarative policy evaluation, and hash-chain audit logging through a clean functional-options API. A single external dependency — gopkg.in/yaml.v3 — handles YAML policy parsing.
Target runtime: Go 1.25+ · Module: github.com/microsoft/agent-governance-toolkit/agent-governance-golang · Package: agentmesh
Installation
go get github.com/microsoft/agent-governance-toolkit/agent-governance-golang
# Verify the install
go list -m github.com/microsoft/agent-governance-toolkit/agent-governance-golang
AgentMeshClient
AgentMeshClient is the recommended entry point. It ties together AgentIdentity, TrustManager, PolicyEngine, and AuditLogger via a functional-options constructor.
NewClient()
Functional Options
ExecuteWithGovernance()
Public Fields
package main
import (
"fmt"
agentmesh "github.com/microsoft/agent-governance-toolkit/agent-governance-golang/packages/agentmesh"
)
func main() {
// Default client — deny-all policy by default
client, err := agentmesh.NewClient("my-agent")
if err != nil {
panic(err)
}
// Client with functional options
client, err = agentmesh.NewClient("analyst-001",
agentmesh.WithCapabilities([]string{"data.read", "data.write"}),
agentmesh.WithTrustConfig(agentmesh.TrustConfig{
InitialScore: 0.8,
DecayRate: 0.01,
RewardFactor: 1.0,
PenaltyFactor: 1.5,
TierThresholds: agentmesh.TierThresholds{High: 0.8, Medium: 0.5},
}),
agentmesh.WithPolicyRules([]agentmesh.PolicyRule{
{Action: "data.read", Effect: agentmesh.Allow},
{Action: "data.write", Effect: agentmesh.Review},
{Action: "*", Effect: agentmesh.Deny},
}),
)
}
Agent name used to derive the DID: did:agentmesh:<agentName>.
Zero or more functional options applied at construction time.
| Option | Description |
|---|
WithCapabilities([]string) | Set capability strings on the generated identity. |
WithTrustConfig(TrustConfig) | Override default trust configuration. |
WithPolicyRules([]PolicyRule) | Set initial policy rules for the engine. |
// WithCapabilities
agentmesh.WithCapabilities([]string{"data.read", "search"})
// WithTrustConfig
agentmesh.WithTrustConfig(agentmesh.TrustConfig{
InitialScore: 0.5,
DecayRate: 0.01,
RewardFactor: 1.0,
PenaltyFactor: 1.5,
MinInteractions: 5,
TierThresholds: agentmesh.TierThresholds{High: 0.8, Medium: 0.5},
PersistPath: "trust-state.json", // optional persistence
})
// WithPolicyRules
agentmesh.WithPolicyRules([]agentmesh.PolicyRule{
{Action: "data.read", Effect: agentmesh.Allow},
{Action: "deploy.*", Effect: agentmesh.Review},
{Action: "shell.*", Effect: agentmesh.Deny},
{Action: "*", Effect: agentmesh.Deny},
})
result, err := client.ExecuteWithGovernance("data.read", nil)
if err != nil {
log.Fatal(err)
}
fmt.Println("Allowed:", result.Allowed)
fmt.Println("Decision:", result.Decision) // allow | deny | review | rate_limit | requires_approval
fmt.Printf("Trust: %.2f (%s)\n", result.TrustScore.Overall, result.TrustScore.Tier)
fmt.Println("Audit hash:", result.AuditEntry.Hash)
Action string evaluated against policy rules.
Optional context for conditional rule matching. Pass nil for no context.
Whether the action is permitted.
"allow" | "deny" | "review" | "rate_limit" | "requires_approval"
Score and tier after this action.
SHA-256 hash-chain record appended to the logger.
// Identity
fmt.Println("DID:", client.Identity.DID)
fmt.Println("Capabilities:", client.Identity.Capabilities)
// Trust
score := client.Trust.GetTrustScore(client.Identity.DID)
fmt.Printf("Trust: %.2f Tier: %s\n", score.Overall, score.Tier)
// Policy engine
err := client.Policy.LoadFromYAML("policies/governance.yaml")
// Audit chain
fmt.Println("Chain valid:", client.Audit.Verify())
PolicyRule
PolicyRule is the struct used to configure individual policy rules inline or via WithPolicyRules.
type PolicyRule struct {
Action string // glob pattern: "data.*", "*", "deploy.production"
Effect Decision // Allow | Deny | Review | RateLimit | RequiresApproval
Conditions map[string]interface{} // optional key=value conditions
MaxCalls int // rate limit: max calls per Window (0 = unlimited)
Window string // rate limit window: "1m", "1h", "1d"
MinApprovals int // approval threshold (0 = not required)
Approvers []string // required approver identifiers
}
Glob pattern for action matching. * matches everything; data.* matches any action starting with data..
agentmesh.Allow, agentmesh.Deny, agentmesh.Review, agentmesh.RateLimit, or agentmesh.RequiresApproval.
Key-value pairs that must match the context for the rule to apply. Supports $and, $or, $not, $gt, $gte, $lt, $lte, $ne, $in.
Rate limiting: MaxCalls: 100, Window: "1m" limits to 100 calls per minute.
Approval requirements: MinApprovals: 2, Approvers: []string{"lead", "sre"}.
PolicyEngine
The PolicyEngine evaluates actions against a set of rules. Rules are evaluated in order; first match wins. The default decision when no rule matches is Deny.
NewPolicyEngine()
Conditional Rules
Rate Limiting & Approval
YAML Loading
rules := []agentmesh.PolicyRule{
{Action: "data.read", Effect: agentmesh.Allow},
{Action: "data.write", Effect: agentmesh.Allow},
{Action: "deploy.*", Effect: agentmesh.Review},
{Action: "shell.*", Effect: agentmesh.Deny},
{Action: "*", Effect: agentmesh.Deny}, // catch-all
}
engine := agentmesh.NewPolicyEngine(rules)
fmt.Println(engine.Evaluate("data.read", nil)) // allow
fmt.Println(engine.Evaluate("shell.exec", nil)) // deny
fmt.Println(engine.Evaluate("deploy.prod", nil)) // review
fmt.Println(engine.Evaluate("unknown", nil)) // deny (catch-all)
rules := []agentmesh.PolicyRule{
{
Action: "deploy.*",
Effect: agentmesh.Deny,
Conditions: map[string]interface{}{"environment": "production"},
},
{
Action: "deploy.*",
Effect: agentmesh.Allow,
},
}
engine := agentmesh.NewPolicyEngine(rules)
prodCtx := map[string]interface{}{"environment": "production"}
fmt.Println(engine.Evaluate("deploy.app", prodCtx)) // deny
stagingCtx := map[string]interface{}{"environment": "staging"}
fmt.Println(engine.Evaluate("deploy.app", stagingCtx)) // allow (first rule skipped)
Advanced condition operators: $gt, $gte, $lt, $lte, $ne, $in, $and, $or, $not.// Rate limiting
rules := []agentmesh.PolicyRule{
{
Action: "api.call",
Effect: agentmesh.Allow,
MaxCalls: 5,
Window: "1m", // 5 calls per minute
},
}
engine := agentmesh.NewPolicyEngine(rules)
for i := 0; i < 5; i++ {
fmt.Println(engine.Evaluate("api.call", nil)) // allow
}
fmt.Println(engine.Evaluate("api.call", nil)) // rate_limit
// Approval requirement
rules = []agentmesh.PolicyRule{
{
Action: "deploy.production",
Effect: agentmesh.Allow,
MinApprovals: 2,
Approvers: []string{"lead", "sre"},
},
}
engine = agentmesh.NewPolicyEngine(rules)
fmt.Println(engine.Evaluate("deploy.production", nil)) // requires_approval
# policies/governance.yaml
rules:
- action: "data.read"
effect: allow
- action: "data.write"
effect: allow
conditions:
role: admin
- action: "shell.*"
effect: deny
- action: "deploy.*"
effect: review
- action: "*"
effect: deny
engine := agentmesh.NewPolicyEngine(nil)
err := engine.LoadFromYAML("policies/governance.yaml")
if err != nil {
log.Fatalf("failed to load policy: %v", err)
}
// LoadFromYAML replaces the existing rule set
// MergeFromYAML appends to the existing rule set
err = engine.MergeFromYAML("policies/additional.yaml")
Decision constants:
| Constant | Value | Description |
|---|
agentmesh.Allow | "allow" | Action is permitted |
agentmesh.Deny | "deny" | Action is blocked |
agentmesh.Review | "review" | Action requires human review |
agentmesh.RateLimit | "rate_limit" | Action is rate-limited |
agentmesh.RequiresApproval | "requires_approval" | Explicit approval needed |
TrustManager
Per-agent trust scoring on a 0.0–1.0 scale with three tiers, configurable decay, and optional file persistence.
// Default configuration
tm := agentmesh.NewTrustManager(agentmesh.DefaultTrustConfig())
// Custom configuration
cfg := agentmesh.TrustConfig{
InitialScore: 0.8,
DecayRate: 0.02,
RewardFactor: 1.0,
PenaltyFactor: 2.0,
MinInteractions: 5,
TierThresholds: agentmesh.TierThresholds{
High: 0.8,
Medium: 0.5,
},
PersistPath: "trust-state.json",
}
tm = agentmesh.NewTrustManager(cfg)
Starting score for new agents. Default: 0.5.
Per-hour decay rate applied to idle agents. Default: 0.01.
Multiplier on success reward. Default: 1.0.
Multiplier on failure penalty (asymmetric). Default: 1.5.
Score threshold for "high" tier. Default: 0.8.
Score threshold for "medium" tier. Default: 0.5.
JSON file for score persistence across restarts.
// New agent starts at 0.5 (medium tier)
score := tm.GetTrustScore("agent-x")
fmt.Println(score.Overall) // 0.5
fmt.Println(score.Tier) // medium
// Record success — trust increases
tm.RecordSuccess("agent-x", 0.05)
tm.RecordSuccess("agent-x", 0.05)
// Record failure — trust decreases (asymmetric: penalty × PenaltyFactor)
tm.RecordFailure("agent-x", 0.1)
score = tm.GetTrustScore("agent-x")
fmt.Println(score.Overall, score.Tier)
Trust tiers (0.0–1.0 scale):| Tier | Score Range | Description |
|---|
low | 0.0–0.49 | Untrusted or new agent |
medium | 0.5–0.79 | Provisional trust |
high | 0.8–1.0 | Fully trusted |
// Peer verification
peer, _ := agentmesh.GenerateIdentity("peer-agent", nil)
result, err := tm.VerifyPeer("peer-agent", peer)
fmt.Println("Verified:", result.Verified)
fmt.Println("Score:", result.Score.Overall)
// File persistence — scores auto-saved after each update
cfg := agentmesh.TrustConfig{PersistPath: "trust-state.json"}
tm1 := agentmesh.NewTrustManager(cfg)
tm1.RecordSuccess("agent-x", 0.05)
// On next startup, scores are restored
tm2 := agentmesh.NewTrustManager(cfg)
score := tm2.GetTrustScore("agent-x")
fmt.Println(score.Overall) // restored score
AuditLogger
Append-only SHA-256 hash-chain audit trail with configurable retention and JSON export.
Log & Verify
Retention & Filtering
logger := agentmesh.NewAuditLogger()
// Log an event
entry := logger.Log("agent-001", "data.read", agentmesh.Allow)
fmt.Println("Hash:", entry.Hash)
fmt.Println("Prev:", entry.PreviousHash) // empty for genesis entry
// Multiple entries — chain verifies
logger.Log("agent-1", "data.write", agentmesh.Deny)
logger.Log("agent-2", "report.send", agentmesh.Allow)
fmt.Println(logger.Verify()) // true
Entry 0 Entry 1 Entry 2
┌──────────┐ ┌──────────┐ ┌──────────┐
│ hash: A │──────▶│ prev: A │──────▶│ prev: B │
│ prev: "" │ │ hash: B │ │ hash: C │
└──────────┘ └──────────┘ └──────────┘
hash = SHA-256(timestamp | agentID | action | decision | previousHash)
// Retention limit
logger := agentmesh.NewAuditLogger()
logger.MaxEntries = 1000
// Chain-aware eviction — Verify() still passes after eviction
for i := 0; i < 1500; i++ {
logger.Log("agent", fmt.Sprintf("action-%d", i), agentmesh.Allow)
}
fmt.Println(logger.Verify()) // true
// Filter by agent
filter := agentmesh.AuditFilter{AgentID: "agent-1"}
entries := logger.GetEntries(filter)
fmt.Println("Agent-1 entries:", len(entries))
// Filter by decision
deny := agentmesh.Deny
filter = agentmesh.AuditFilter{Decision: &deny}
denied := logger.GetEntries(filter)
// Export
jsonStr, _ := logger.ExportJSON()
AgentIdentity
Ed25519-based cryptographic identity with DID identifiers and data signing.
// Generate identity
identity, err := agentmesh.GenerateIdentity(
"researcher-agent",
[]string{"data.read", "search"},
)
if err != nil {
log.Fatal(err)
}
fmt.Println("DID:", identity.DID) // did:agentmesh:researcher-agent
fmt.Println("Capabilities:", identity.Capabilities)
fmt.Println("Public key:", len(identity.PublicKey), "bytes") // 32 bytes
// Sign and verify
data := []byte("important message")
signature, err := identity.Sign(data)
fmt.Println("Signature:", len(signature), "bytes") // 64 bytes
fmt.Println("Valid:", identity.Verify(data, signature)) // true
fmt.Println("Tampered:", identity.Verify([]byte("wrong"), signature)) // false
// JSON serialization (public key only — share safely)
jsonBytes, err := identity.ToJSON()
imported, err := agentmesh.FromJSON(jsonBytes)
fmt.Println("Imported DID:", imported.DID)
fmt.Println("Can verify:", imported.Verify(data, signature)) // true
Full Governance Pipeline
package main
import (
"fmt"
"log"
agentmesh "github.com/microsoft/agent-governance-toolkit/agent-governance-golang/packages/agentmesh"
)
func main() {
client, err := agentmesh.NewClient("research-agent",
agentmesh.WithCapabilities([]string{"data.read", "search.web"}),
agentmesh.WithTrustConfig(agentmesh.TrustConfig{
InitialScore: 0.5,
DecayRate: 0.01,
RewardFactor: 1.0,
PenaltyFactor: 1.5,
TierThresholds: agentmesh.TierThresholds{High: 0.8, Medium: 0.5},
}),
agentmesh.WithPolicyRules([]agentmesh.PolicyRule{
{Action: "data.read", Effect: agentmesh.Allow},
{Action: "search.*", Effect: agentmesh.Allow},
{Action: "data.write", Effect: agentmesh.Review},
{Action: "*", Effect: agentmesh.Deny},
}),
)
if err != nil {
log.Fatal(err)
}
fmt.Println("Agent DID:", client.Identity.DID)
actions := []string{"data.read", "search.web", "data.write", "shell.exec"}
for _, action := range actions {
result, _ := client.ExecuteWithGovernance(action, nil)
status := "✅ allowed"
if !result.Allowed {
status = "❌ denied"
}
fmt.Printf(" %s → %s (trust: %.2f, tier: %s)\n",
action, status, result.TrustScore.Overall, result.TrustScore.Tier)
}
fmt.Println("\nAudit chain valid:", client.Audit.Verify())
jsonStr, _ := client.Audit.ExportJSON()
fmt.Println("Audit JSON:", jsonStr[:80], "...")
}
Expected output:
Agent DID: did:agentmesh:research-agent
data.read → ✅ allowed (trust: 0.54, tier: medium)
search.web → ✅ allowed (trust: 0.59, tier: medium)
data.write → ❌ denied (trust: 0.44, tier: low)
shell.exec → ❌ denied (trust: 0.28, tier: low)
Audit chain valid: true
Source File Reference
| Component | Location |
|---|
| Client + options | agent-governance-golang/packages/agentmesh/client.go |
| Type definitions | agent-governance-golang/packages/agentmesh/types.go |
PolicyEngine | agent-governance-golang/packages/agentmesh/policy.go |
TrustManager | agent-governance-golang/packages/agentmesh/trust.go |
AuditLogger | agent-governance-golang/packages/agentmesh/audit.go |
AgentIdentity | agent-governance-golang/packages/agentmesh/identity.go |
| Conflict resolution | agent-governance-golang/packages/agentmesh/conflict.go |
| Metrics | agent-governance-golang/packages/agentmesh/metrics.go |
| Tests | agent-governance-golang/packages/agentmesh/*_test.go |