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 Rust crate provides zero-overhead governance abstractions for AI agents. It implements policy evaluation, trust scoring, hash-chain audit logging, Ed25519 agent identity, execution control, and lifecycle management — all with Rust’s ownership guarantees ensuring that governance state cannot be accidentally aliased or mutated across threads. The companion agentmesh-mcp crate keeps MCP-focused security functionality available as a smaller standalone dependency.
Target runtime: Rust 1.75+ (2021 edition) · Workspace: agent-governance-rust/ · Crates: agentmesh and agentmesh-mcp · Dependencies: serde, serde_yaml, sha2, ed25519-dalek, thiserror

Installation

[dependencies]
agentmesh = "3"
cargo add agentmesh
For MCP security scanning only:
agentmesh-mcp = "3"

AgentMeshClient

AgentMeshClient is the recommended entry point. It owns the AgentIdentity, TrustManager, PolicyEngine, and AuditLogger as public fields, wiring them into a single execute_with_governance call.
use agentmesh::{AgentMeshClient, ClientOptions, TrustConfig};

// Default client — Ed25519 identity, empty policy (allow-all), default trust
let client = AgentMeshClient::new("my-agent").expect("failed to create client");

// Client with options
let opts = ClientOptions {
    capabilities: vec!["data.read".into(), "data.write".into()],
    trust_config: Some(TrustConfig {
        initial_score: 500,
        reward: 15,
        penalty: 75,
        ..Default::default()
    }),
    policy_yaml: None,  // load later via client.policy.load_from_file(...)
};
let client = AgentMeshClient::with_options("analyst-001", opts)?;
agent_name
&str
required
Agent name used to derive the DID: did:agentmesh:<agent_name>.
opts.capabilities
Vec<String>
Capability strings granted to the identity.
opts.trust_config
Option<TrustConfig>
Trust manager configuration. None uses defaults: initial_score: 500, reward: 10, penalty: 50.
opts.policy_yaml
Option<String>
YAML policy to load at creation. None starts with an empty (allow-all) engine.

PolicyEngine

Evaluates actions against YAML-defined rules. Supports four decision types: Allow, Deny, RequiresApproval, and RateLimited.
use agentmesh::PolicyEngine;

let engine = PolicyEngine::new();          // empty — allows everything
assert!(!engine.is_loaded());

// Load from YAML string
let yaml = r#"
version: "1.0"
agent: my-agent
policies:
  - name: capability-gate
    type: capability
    allowed_actions:
      - "data.read"
      - "data.write"
    denied_actions:
      - "shell:*"
"#;
engine.load_from_yaml(yaml)?;

// Load from file
engine.load_from_file("policies/security.yaml")?;

assert!(engine.is_loaded());

TrustManager

Per-agent trust scoring on a 0–1000 integer scale with five tiers, time-based decay, and optional JSON persistence.
use agentmesh::{TrustManager, TrustConfig, TrustTier};

// Defaults: initial_score=500, reward=10, penalty=50, decay_rate=0.95
let tm = TrustManager::with_defaults();

// Custom configuration
let config = TrustConfig {
    initial_score: 800,
    threshold:     700,
    reward:        20,
    penalty:       100,
    decay_rate:    0.95,
    persist_path:  Some("trust-scores.json".into()),
};
let tm = TrustManager::new(config);
initial_score
u32
Starting score for new agents. Default: 500.
reward
u32
Points added per successful interaction. Default: 10.
penalty
u32
Points deducted per failed interaction. Default: 50.
decay_rate
f64
Hourly multiplier for idle decay. 0.95 = 5%/hr. Default: 0.95.
persist_path
Option<String>
JSON file path for persistence. Scores loaded on construction.

AuditLogger

Append-only SHA-256 hash-chain audit trail. Each entry links to the previous entry’s hash, creating a tamper-evident sequence.
use agentmesh::{AuditLogger, types::AuditFilter};

let logger = AuditLogger::new();

// Log events
let entry = logger.log("agent-001", "data.read", "allow");
println!("Hash: {}", entry.hash);
println!("Prev: {}", entry.previous_hash);  // empty for genesis entry
println!("Seq:  {}", entry.seq);             // 0

// Multiple entries — chain links
logger.log("agent-1", "data.read",   "allow");
logger.log("agent-1", "data.write",  "deny");
logger.log("agent-2", "report.send", "allow");

assert!(logger.verify());  // true — chain intact

let entries = logger.entries();
assert_eq!(entries[1].previous_hash, entries[0].hash);

// Filter
let filter = AuditFilter { agent_id: Some("agent-1".into()), action: None, decision: None };
let filtered = logger.get_entries(&filter);
println!("Agent-1 entries: {}", filtered.len());
Rust’s ownership model ensures the AuditLogger’s internal Vec<AuditEntry> cannot be aliased — there is no risk of a second mutable reference silently corrupting the hash chain between calls.

AgentIdentity

Ed25519-based cryptographic identity with DID identifiers, signing, verification, and JSON serialization.
use agentmesh::{AgentIdentity, PublicIdentity};

// Generate a new identity
let identity = AgentIdentity::generate(
    "researcher-agent",
    vec!["data.read".into(), "search".into()],
)?;

println!("DID: {}", identity.did);               // did:agentmesh:researcher-agent
println!("Capabilities: {:?}", identity.capabilities);
println!("Public key: {} bytes", identity.public_key.len());

// Sign and verify
let data = b"important message";
let signature = identity.sign(data)?;
println!("Signature: {} bytes", signature.len());  // 64 bytes

assert!(identity.verify(data, &signature));
assert!(!identity.verify(b"wrong message", &signature));

// JSON serialization (public key only)
let json = identity.to_json()?;
let imported = AgentIdentity::from_json(&json)?;
assert_eq!(imported.did, identity.did);

// Verification-only public identity
let pub_id = PublicIdentity {
    did:          identity.did.clone(),
    public_key:   identity.public_key.to_bytes().to_vec(),
    capabilities: identity.capabilities.clone(),
};
assert!(pub_id.verify(data, &signature));

Extended Crate Surface

The agentmesh workspace exposes a rich set of governance helpers beyond the core client:
use agentmesh::{
    ExecutionRequest, ExecutionResponse, GovernanceHook,
    FrameworkGovernanceAdapter, FrameworkKind, GovernancePolicy,
};

struct ReadOnlyHook;

impl GovernanceHook for ReadOnlyHook {
    fn before_execute(&self, request: &ExecutionRequest) -> ExecutionResponse {
        match request.action.as_str() {
            "data.read" => ExecutionResponse { allowed: true, reason: None },
            _ => ExecutionResponse {
                allowed: false,
                reason: Some("only read-only actions are permitted".into()),
            },
        }
    }
}

let adapter = FrameworkGovernanceAdapter::for_tower(
    ReadOnlyHook,
    GovernancePolicy {
        allowed_tools: vec!["read_file".into()],
        ..GovernancePolicy::default()
    },
);

let result = adapter.evaluate_request(
    ExecutionRequest { actor: "did:mesh:worker-1".into(), action: "data.read".into(), payload: None },
    Some("read_file"),
    Some(0.95),
);
assert!(result.decision.allowed);

Full Governance Pipeline

use agentmesh::{AgentMeshClient, ClientOptions, TrustConfig};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let policy_yaml = r#"
version: "1.0"
agent: research-agent
policies:
  - name: data-gate
    type: capability
    allowed_actions:
      - "data.read"
      - "search.*"
    denied_actions:
      - "data.delete"
      - "shell:*"
  - name: api-throttle
    type: rate_limit
    actions:
      - "search.*"
    max_calls: 5
    window: "60s"
"#;

    let client = AgentMeshClient::with_options("research-agent", ClientOptions {
        capabilities: vec!["data.read".into(), "search.web".into()],
        trust_config: Some(TrustConfig {
            initial_score: 500,
            reward: 15,
            penalty: 75,
            ..Default::default()
        }),
        policy_yaml: Some(policy_yaml.into()),
    })?;

    println!("Agent DID: {}", client.identity.did);

    for action in &["data.read", "search.web", "data.delete", "shell:ls"] {
        let result = client.execute_with_governance(action, None);
        println!(
            "  {} → {} (trust: {}, tier: {:?})",
            action,
            if result.allowed { "✅ allowed" } else { "❌ denied" },
            result.trust_score.score,
            result.trust_score.tier,
        );
    }

    println!("\nAudit trail: {} entries", client.audit.entries().len());
    println!("Chain valid: {}", client.audit.verify());

    Ok(())
}

Build docs developers (and LLMs) love