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
impl Calculator
Sourcepub fn interactions_for_confidence(
&self,
current: u32,
target: f64,
) -> Result<u32>
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 interactionstarget- 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);Sourcepub fn confidence_after_interactions(
&self,
current: u32,
additional: u32,
) -> f64
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 interactionsadditional- 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);Sourcepub fn explain_score(&self, agent: &AgentData) -> Result<ScoreExplanation>
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);Sourcepub fn predict_score_change(
&self,
agent: &AgentData,
new_reviews: u32,
new_rating: f64,
) -> Result<ScorePrediction>
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 datanew_reviews- Number of new reviews to addnew_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);Sourcepub fn compare_agents(
&self,
agent_a: &AgentData,
agent_b: &AgentData,
) -> Result<AgentComparison>
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
impl Calculator
Sourcepub fn confidence_k(&self) -> f64
pub fn confidence_k(&self) -> f64
Get the confidence growth parameter
Sourcepub fn prior_base(&self) -> f64
pub fn prior_base(&self) -> f64
Get the base prior score
Sourcepub fn builder() -> CalculatorBuilder
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();Sourcepub fn from_config(config: CalculatorConfig) -> Result<Self>
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();Sourcepub fn new(confidence_k: f64, prior_base: f64, prior_max: f64) -> Result<Self>
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();Sourcepub fn calculate(&self, agent: &AgentData) -> Result<ReputationScore>
pub fn calculate(&self, agent: &AgentData) -> Result<ReputationScore>
Calculates the reputation score for an agent
§Algorithm Details
-
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
-
Empirical Score (0-100 points):
- Based on average rating (1-5 stars)
- Converted to 0-100 scale
-
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 usedcalculated_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"),
}Sourcepub fn calculate_batch(
&self,
agents: &[AgentData],
) -> Vec<Result<ReputationScore>> ⓘ
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());Sourcepub fn calculate_batch_with_options(
&self,
agents: &[AgentData],
options: BatchOptions,
) -> BatchResult
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 foroptions- 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
impl Debug for Calculator
Auto Trait Implementations§
impl Freeze for Calculator
impl RefUnwindSafe for Calculator
impl Send for Calculator
impl Sync for Calculator
impl Unpin for Calculator
impl UnwindSafe for Calculator
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
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 moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
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