Skip to main content

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.
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},
        }),
    )
}
agentName
string
required
Agent name used to derive the DID: did:agentmesh:<agentName>.
opts
...Option
Zero or more functional options applied at construction time.

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
}
Action
string
required
Glob pattern for action matching. * matches everything; data.* matches any action starting with data..
Effect
Decision
required
agentmesh.Allow, agentmesh.Deny, agentmesh.Review, agentmesh.RateLimit, or agentmesh.RequiresApproval.
Conditions
map[string]interface{}
Key-value pairs that must match the context for the rule to apply. Supports $and, $or, $not, $gt, $gte, $lt, $lte, $ne, $in.
MaxCalls / Window
int / string
Rate limiting: MaxCalls: 100, Window: "1m" limits to 100 calls per minute.
MinApprovals / Approvers
int / []string
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.
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)
Decision constants:
ConstantValueDescription
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)
InitialScore
float64
Starting score for new agents. Default: 0.5.
DecayRate
float64
Per-hour decay rate applied to idle agents. Default: 0.01.
RewardFactor
float64
Multiplier on success reward. Default: 1.0.
PenaltyFactor
float64
Multiplier on failure penalty (asymmetric). Default: 1.5.
TierThresholds.High
float64
Score threshold for "high" tier. Default: 0.8.
TierThresholds.Medium
float64
Score threshold for "medium" tier. Default: 0.5.
PersistPath
string
JSON file for score persistence across restarts.

AuditLogger

Append-only SHA-256 hash-chain audit trail with configurable retention and JSON export.
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)

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

ComponentLocation
Client + optionsagent-governance-golang/packages/agentmesh/client.go
Type definitionsagent-governance-golang/packages/agentmesh/types.go
PolicyEngineagent-governance-golang/packages/agentmesh/policy.go
TrustManageragent-governance-golang/packages/agentmesh/trust.go
AuditLoggeragent-governance-golang/packages/agentmesh/audit.go
AgentIdentityagent-governance-golang/packages/agentmesh/identity.go
Conflict resolutionagent-governance-golang/packages/agentmesh/conflict.go
Metricsagent-governance-golang/packages/agentmesh/metrics.go
Testsagent-governance-golang/packages/agentmesh/*_test.go

Build docs developers (and LLMs) love