Skip to main content
Glama
0xjcf
by 0xjcf

calculate-metrics

Analyze code to calculate metrics like complexity, maintainability, and lines of code for quality assessment and improvement.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
repositoryUrlNoURL of the repository to analyze (e.g., 'https://github.com/username/repo')
filePathNoPath to the file within the repository (e.g., 'src/main.ts')
fileContentNoSource code content to analyze directly instead of from a repository
languageNoProgramming language of the code (e.g., 'javascript', 'python', 'typescript', 'rust')
metricsNoSpecific metrics to calculate, such as 'complexity', 'linesOfCode', 'maintainability', 'functions', 'classes'

Implementation Reference

  • Registration of the 'calculate-metrics' MCP tool, including input schema (Zod) and inline handler function that delegates to getMetrics and formats the MCP response.
    server.tool(
      "calculate-metrics",
      {
        repositoryUrl: z.string().optional().describe("URL of the repository to analyze (e.g., 'https://github.com/username/repo')"),
        filePath: z.string().optional().describe("Path to the file within the repository (e.g., 'src/main.ts')"),
        fileContent: z.string().optional().describe("Source code content to analyze directly instead of from a repository"),
        language: z.string().optional().describe("Programming language of the code (e.g., 'javascript', 'python', 'typescript', 'rust')"),
        metrics: z.array(z.string()).optional().describe("Specific metrics to calculate, such as 'complexity', 'linesOfCode', 'maintainability', 'functions', 'classes'")
      },
      async ({ repositoryUrl, filePath, fileContent, language, metrics }) => {
        try {
          const results = await getMetrics({
            repositoryUrl,
            filePath,
            fileContent,
            language,
            metrics: metrics || ["complexity", "linesOfCode", "maintainability"]
          });
          
          return {
            content: [{
              type: "text",
              text: JSON.stringify(results, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: "text",
              text: `Error calculating metrics: ${(error as Error).message}`
            }],
            isError: true
          };
        }
      }
    );
  • getMetrics helper function called by the tool handler. Handles caching, repository/file analysis orchestration, reads code, and delegates to calculateMetrics.
    export async function getMetrics(options: {
      repositoryUrl?: string;
      filePath?: string;
      fileContent?: string;
      language?: string;
      metrics?: string[];
      analysisId?: string;
      type?: string;
    }): Promise<any> {
      const { repositoryUrl, filePath, fileContent, language, metrics, analysisId, type } = options;
      
      // If analysisId is provided, retrieve from cache
      if (analysisId) {
        const cachedAnalysis = analysisCache.get(analysisId);
        if (!cachedAnalysis) {
          throw new Error(`Analysis not found: ${analysisId}`);
        }
        
        if (type) {
          return cachedAnalysis[type] || {};
        }
        
        return cachedAnalysis;
      }
      
      // Otherwise perform new analysis
      if (repositoryUrl) {
        const repoPath = await getRepository(repositoryUrl);
        
        if (filePath) {
          // Analyze specific file
          const fullPath = path.join(repoPath, filePath);
          const code = fs.readFileSync(fullPath, 'utf8');
          return calculateMetrics(code, language, metrics);
        } else {
          // Analyze entire repository
          const files = listFiles(repoPath);
          const allMetrics: Record<string, any> = {};
          
          for (const file of files) {
            const fullPath = path.join(repoPath, file);
            const code = fs.readFileSync(fullPath, 'utf8');
            allMetrics[file] = calculateMetrics(code, path.extname(file).slice(1), metrics);
          }
          
          return allMetrics;
        }
      } else if (fileContent) {
        // Analyze provided code content
        return calculateMetrics(fileContent, language, metrics);
      } else {
        throw new Error("Either repositoryUrl, filePath, or fileContent must be provided");
      }
    }
  • Core calculateMetrics function implementing the metric computations: linesOfCode, complexity (cyclomatic-like), maintainability score.
    function calculateMetrics(code: string, language?: string, metricTypes?: string[]): Record<string, any> {
      const result: Record<string, any> = {};
      
      if (!metricTypes || metricTypes.includes('linesOfCode')) {
        result.linesOfCode = code.split('\n').length;
      }
      
      if (!metricTypes || metricTypes.includes('complexity')) {
        // Simple complexity heuristic (would be replaced with actual analysis)
        const decisions = (code.match(/if|else|for|while|switch|case|try|catch/g) || []).length;
        result.complexity = decisions;
      }
      
      if (!metricTypes || metricTypes.includes('maintainability')) {
        // Simple maintainability heuristic
        const commentLines = (code.match(/\/\/.*$|\/*[\s\S]*?\*\//gm) || []).length;
        const codeLines = code.split('\n').length;
        
        // Calculate a simple maintainability index (higher is better)
        const commentRatio = commentLines / codeLines;
        const complexity = result.complexity || 0;
        
        result.maintainability = Math.max(0, 100 - (complexity * 0.25) + (commentRatio * 20));
      }
      
      return result;
    }
Behavior1/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Tool has no description.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness1/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Tool has no description.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness1/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Tool has no description.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters1/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Tool has no description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose1/5

Does the description clearly state what the tool does and how it differs from similar tools?

Tool has no description.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines1/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Tool has no description.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/0xjcf/MCP_CodeAnalysis'

If you have feedback or need assistance with the MCP directory API, please join our Discord server