Struct Calculator

Source
pub struct Calculator { /* private fields */ }
Expand description

Calculates reputation scores for MCP agents

The Calculator implements a hybrid scoring system that combines prior reputation (based on credentials) with empirical performance (based on reviews and interactions).

§Example

use reputation_core::Calculator;
use reputation_types::AgentDataBuilder;
 
let calculator = Calculator::default();
let agent = AgentDataBuilder::new("did:example:test")
    .with_reviews(50, 4.0)
    .total_interactions(100)  // Must be >= total_reviews
    .build()
    .unwrap();
 
let score = calculator.calculate(&agent).unwrap();
assert!(score.score >= 0.0 && score.score <= 100.0);

Implementations§

Source§

impl Calculator

Source

pub fn interactions_for_confidence( &self, current: u32, target: f64, ) -> Result<u32>

Calculate how many additional interactions are needed to reach a target confidence level

§Arguments
  • current - Current number of interactions
  • target - Target confidence level (0.0 to 1.0)
§Returns

Number of additional interactions needed

§Example
use reputation_core::Calculator;
 
let calc = Calculator::default();
 
// How many more interactions to reach 90% confidence?
let needed = calc.interactions_for_confidence(50, 0.9).unwrap();
println!("Need {} more interactions for 90% confidence", needed);
Source

pub fn confidence_after_interactions( &self, current: u32, additional: u32, ) -> f64

Calculate what the confidence level will be after additional interactions

§Arguments
  • current - Current number of interactions
  • additional - Additional interactions to add
§Returns

The confidence level after the additional interactions

§Example
use reputation_core::Calculator;
 
let calc = Calculator::default();
 
// What will confidence be after 50 more interactions?
let future_confidence = calc.confidence_after_interactions(100, 50);
println!("Confidence will be {:.1}%", future_confidence * 100.0);
Source

pub fn explain_score(&self, agent: &AgentData) -> Result<ScoreExplanation>

Explain how a reputation score was calculated in human-readable format

Provides a detailed breakdown of all components that went into the score.

§Example
use reputation_core::Calculator;
use reputation_types::AgentDataBuilder;
 
let calc = Calculator::default();
let agent = AgentDataBuilder::new("did:example:123")
    .with_reviews(50, 4.2)
    .total_interactions(100)
    .mcp_level(2)
    .identity_verified(true)
    .build()
    .unwrap();
 
let explanation = calc.explain_score(&agent).unwrap();
println!("{}", explanation.explanation);
Source

pub fn predict_score_change( &self, agent: &AgentData, new_reviews: u32, new_rating: f64, ) -> Result<ScorePrediction>

Predict how the score will change with additional reviews

§Arguments
  • agent - Current agent data
  • new_reviews - Number of new reviews to add
  • new_rating - Average rating of new reviews (1.0 to 5.0)
§Example
use reputation_core::Calculator;
use reputation_types::AgentDataBuilder;
 
let calc = Calculator::default();
let agent = AgentDataBuilder::new("did:example:123")
    .with_reviews(50, 4.0)
    .total_interactions(50)
    .build()
    .unwrap();
 
// What if they get 10 more 5-star reviews?
let prediction = calc.predict_score_change(&agent, 10, 5.0).unwrap();
println!("Score would change by {:.1} points", prediction.score_change);
Source

pub fn compare_agents( &self, agent_a: &AgentData, agent_b: &AgentData, ) -> Result<AgentComparison>

Compare two agents’ reputation scores

Provides a detailed comparison including scores, confidence levels, and which agent is more reliable.

§Example
use reputation_core::Calculator;
use reputation_types::AgentDataBuilder;
 
let calc = Calculator::default();
 
let agent_a = AgentDataBuilder::new("did:example:alice")
    .with_reviews(100, 4.5)
    .total_interactions(150)
    .build()
    .unwrap();
 
let agent_b = AgentDataBuilder::new("did:example:bob")
    .with_reviews(20, 4.8)
    .total_interactions(25)
    .build()
    .unwrap();
 
let comparison = calc.compare_agents(&agent_a, &agent_b).unwrap();
println!("Higher score: {}", comparison.higher_score_agent);
println!("More reliable: {}", comparison.more_reliable_agent);
Source§

impl Calculator

Source

pub fn confidence_k(&self) -> f64

Get the confidence growth parameter

Source

pub fn prior_base(&self) -> f64

Get the base prior score

Source

pub fn prior_max(&self) -> f64

Get the maximum prior score

Source

pub fn builder() -> CalculatorBuilder

Creates a builder for constructing a Calculator with custom configuration

§Example
use reputation_core::Calculator;
 
let calculator = Calculator::builder()
    .confidence_k(20.0)
    .prior_base(60.0)
    .build()
    .unwrap();
Source

pub fn from_config(config: CalculatorConfig) -> Result<Self>

Creates a Calculator from a configuration

§Example
use reputation_core::{Calculator, CalculatorConfig};
 
let config = CalculatorConfig {
    confidence_k: 20.0,
    prior_base: 60.0,
    prior_max: 85.0,
};
let calculator = Calculator::from_config(config).unwrap();
Source

pub fn new(confidence_k: f64, prior_base: f64, prior_max: f64) -> Result<Self>

Creates a new Calculator with custom parameters

§Parameters
  • confidence_k: Controls confidence growth rate (must be positive)
  • prior_base: Base prior score (must be 0-100)
  • prior_max: Maximum prior score cap (must be between prior_base and 100)
§Errors

Returns an error if parameters are out of valid ranges

§Example
use reputation_core::Calculator;
 
let calculator = Calculator::new(20.0, 60.0, 90.0).unwrap();
Source

pub fn calculate(&self, agent: &AgentData) -> Result<ReputationScore>

Calculates the reputation score for an agent

§Algorithm Details
  1. Prior Score Calculation (50-80 points by default):

    • Base: 50 points
    • MCP Level bonus: 0-15 points (5 per level)
    • Identity verified: +5 points
    • Security audit: +7 points
    • Open source: +3 points
    • Age > 365 days: +5 points
  2. Empirical Score (0-100 points):

    • Based on average rating (1-5 stars)
    • Converted to 0-100 scale
  3. Confidence Calculation:

    • Based on total interactions
    • Approaches 1.0 asymptotically
§Returns

A ReputationScore containing:

  • score: Final reputation (0-100)
  • confidence: Confidence in the score (0-1)
  • algorithm_version: Version of the algorithm used
  • calculated_at: Timestamp of calculation
§Errors

Returns an error if:

  • Agent data validation fails
  • Calculation produces NaN or out-of-bounds values
§Example
use reputation_core::Calculator;
use reputation_types::AgentDataBuilder;
 
let calculator = Calculator::default();
let agent = AgentDataBuilder::new("did:example:123")
    .with_reviews(100, 4.5)
    .total_interactions(200)  // Must be >= total_reviews
    .identity_verified(true)
    .build()
    .unwrap();
 
let score = calculator.calculate(&agent).unwrap();
match score.confidence {
    c if c < 0.3 => println!("Low confidence - needs more data"),
    c if c < 0.7 => println!("Moderate confidence"),
    _ => println!("High confidence in score"),
}
Source

pub fn calculate_batch( &self, agents: &[AgentData], ) -> Vec<Result<ReputationScore>>

Calculate reputation scores for multiple agents in parallel

This method uses rayon to process agents in parallel, providing significant performance improvements for large batches.

§Returns

A vector of results in the same order as the input agents. Each result contains either a ReputationScore or an error.

§Example
use reputation_core::Calculator;
use reputation_types::AgentDataBuilder;
 
let calculator = Calculator::default();
let agents: Vec<_> = (0..100).map(|i| {
    AgentDataBuilder::new(&format!("did:example:agent{}", i))
        .with_reviews(50, 4.0)
        .total_interactions(100)
        .build()
        .unwrap()
}).collect();
 
let results = calculator.calculate_batch(&agents);
assert_eq!(results.len(), agents.len());
Source

pub fn calculate_batch_with_options( &self, agents: &[AgentData], options: BatchOptions, ) -> BatchResult

Calculate reputation scores with batch processing options

This method provides more control over batch processing with options for chunk size, progress tracking, and detailed timing information.

§Arguments
  • agents - Slice of agents to calculate scores for
  • options - Configuration options for batch processing
§Returns

A BatchResult containing:

  • Individual calculation results with timing
  • Total processing duration
  • Success/failure counts
§Example
use reputation_core::{Calculator, BatchOptions};
use reputation_types::AgentDataBuilder;
 
let calculator = Calculator::default();
let agents: Vec<_> = (0..1000).map(|i| {
    AgentDataBuilder::new(&format!("did:example:agent{}", i))
        .with_reviews(50, 4.0)
        .total_interactions(100)
        .build()
        .unwrap()
}).collect();
 
let options = BatchOptions {
    chunk_size: Some(100),
    fail_fast: false,
    progress_callback: None,
};
 
let result = calculator.calculate_batch_with_options(&agents, options);
println!("Processed {} agents in {:?}", agents.len(), result.total_duration);
println!("Success: {}, Failed: {}", result.successful_count, result.failed_count);

Trait Implementations§

Source§

impl Debug for Calculator

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Calculator

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.