Class McpMetricsCollector

java.lang.Object
com.tnsai.mcp.observability.McpMetricsCollector

public class McpMetricsCollector extends Object
Thread-safe collector of metrics for MCP operations.

Collects the following metrics:

  • mcp.tool.invocations - Counter by tool name and success/failure
  • mcp.tool.duration - Histogram (total + count for average) by tool name
  • mcp.errors - Counter by error type
  • mcp.active.sessions - Gauge of currently active sessions

All methods are thread-safe and suitable for concurrent use.

Example usage:


 McpMetricsCollector metrics = new McpMetricsCollector();

 metrics.recordToolInvocation("readFile", true, Duration.ofMillis(120));
 metrics.recordToolInvocation("writeFile", false, Duration.ofMillis(50));
 metrics.recordError("TimeoutException", "readFile");

 Map<String, Object> summary = metrics.getSummary();
 
  • Constructor Details

    • McpMetricsCollector

      public McpMetricsCollector()
  • Method Details

    • recordToolInvocation

      public void recordToolInvocation(String toolName, boolean success, Duration duration)
      Records a tool invocation with its outcome and duration.
      Parameters:
      toolName - the name of the tool that was invoked
      success - true if the invocation succeeded, false otherwise
      duration - the duration of the invocation
    • recordError

      public void recordError(String errorType, String toolName)
      Records an error occurrence.
      Parameters:
      errorType - the type/class of the error
      toolName - the tool name associated with the error (may be null)
    • incrementActiveSessions

      public void incrementActiveSessions()
      Increments the active sessions gauge by one.
    • decrementActiveSessions

      public void decrementActiveSessions()
      Decrements the active sessions gauge by one.
    • getToolInvocationCounts

      public Map<String,Long> getToolInvocationCounts()
      Returns the total invocation count per tool (success + failure).
      Returns:
      map of tool name to total invocation count
    • getToolAverageDurations

      public Map<String,Double> getToolAverageDurations()
      Returns the average duration per tool in milliseconds.
      Returns:
      map of tool name to average duration in milliseconds
    • getErrorCounts

      public Map<String,Long> getErrorCounts()
      Returns error counts by error type (or errorType:toolName).
      Returns:
      map of error key to count
    • getActiveSessions

      public int getActiveSessions()
      Returns the current number of active sessions.
      Returns:
      the active session count
    • getSummary

      public Map<String,Object> getSummary()
      Returns a summary of all collected metrics.
      Returns:
      map containing all metric categories
    • reset

      public void reset()
      Resets all collected metrics to their initial state.