Skip to main content
Glama

analyze_contract_performance

Analyze Clarity smart contracts to identify performance bottlenecks and SIP-012 optimization opportunities. Provides cost breakdowns and actionable recommendations to improve contract efficiency.

Instructions

Analyze a Clarity contract for performance bottlenecks and SIP-012 optimization opportunities. Provides detailed cost breakdown and optimization recommendations.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
contractCodeYesThe Clarity contract code to analyze
functionNameNoSpecific function to analyze (optional)
optimizationLevelYesLevel of optimization analysis

Implementation Reference

  • The core handler for the 'analyze_contract_performance' tool. Defines the tool object with name, description, parameters schema, and the execute function that analyzes Clarity contract code for SIP-012 performance metrics, identifies issues, and generates optimization recommendations.
    export const analyzeContractPerformanceTool: Tool<undefined, typeof ContractAnalysisScheme> = {
      name: "analyze_contract_performance",
      description: "Analyze a Clarity contract for performance bottlenecks and SIP-012 optimization opportunities. Provides detailed cost breakdown and optimization recommendations.",
      parameters: ContractAnalysisScheme,
      execute: async (args, context) => {
        try {
          await recordTelemetry({ action: "analyze_contract_performance" }, context);
          
          // Parse contract for performance analysis
          const analysis = analyzeContractCode(args.contractCode, args.functionName);
          const optimizations = generateOptimizations(analysis, args.optimizationLevel);
          
          return `# SIP-012 Performance Analysis
    
    ## Contract Overview
    - **Functions Analyzed**: ${analysis.functionCount}
    - **Map Operations**: ${analysis.mapOperations}
    - **List Operations**: ${analysis.listOperations}
    - **Contract Calls**: ${analysis.contractCalls}
    
    ## Performance Metrics
    
    ### Estimated Resource Usage
    \`\`\`
    Runtime Cost: ${analysis.estimatedCosts.runtime.toLocaleString()} units
    Read Operations: ${analysis.estimatedCosts.readCount}
    Write Operations: ${analysis.estimatedCosts.writeCount}
    Storage Read: ${analysis.estimatedCosts.readLength} bytes
    Storage Write: ${analysis.estimatedCosts.writeLength} bytes
    \`\`\`
    
    ### Block Capacity Usage
    - **Runtime**: ${((analysis.estimatedCosts.runtime / SIP012_COSTS.limits.runtime) * 100).toFixed(2)}% of block limit
    - **Read Count**: ${((analysis.estimatedCosts.readCount / SIP012_COSTS.limits.readCount) * 100).toFixed(2)}% of block limit
    - **Write Count**: ${((analysis.estimatedCosts.writeCount / SIP012_COSTS.limits.writeCount) * 100).toFixed(2)}% of block limit
    
    ## Performance Issues Detected
    
    ${analysis.issues.map(issue => `### ${issue.type}
    - **Severity**: ${issue.severity}
    - **Description**: ${issue.description}
    - **Impact**: ${issue.impact}
    - **Location**: ${issue.location || 'Multiple locations'}
    `).join('\n')}
    
    ## SIP-012 Optimization Opportunities
    
    ${optimizations.map(opt => `### ${opt.title}
    - **Type**: ${opt.type}
    - **Potential Savings**: ${opt.savings}
    - **Implementation**: ${opt.implementation}
    
    **Before:**
    \`\`\`clarity
    ${opt.before}
    \`\`\`
    
    **After:**
    \`\`\`clarity
    ${opt.after}
    \`\`\`
    `).join('\n')}
    
    ## Performance Recommendations
    
    ### Immediate Actions
    ${optimizations.filter(o => o.priority === 'high').map(o => `- ${o.title}: ${o.savings}`).join('\n')}
    
    ### Medium-term Improvements  
    ${optimizations.filter(o => o.priority === 'medium').map(o => `- ${o.title}: ${o.savings}`).join('\n')}
    
    ### Advanced Optimizations
    ${optimizations.filter(o => o.priority === 'low').map(o => `- ${o.title}: ${o.savings}`).join('\n')}
    
    ## Next Steps
    1. Implement high-priority optimizations first
    2. Profile contract with Clarinet performance tests
    3. Monitor gas usage in production
    4. Consider batch operations for high-frequency functions
    5. Leverage SIP-012 dynamic list sizing for collections
    
    ## SIP-012 Specific Benefits
    ✅ **2x Database Operations**: Take advantage of increased read/write limits
    ✅ **Dynamic List Storage**: Reduce storage costs with actual-size assessment
    ✅ **Optimized Cost Functions**: More accurate performance modeling
    ✅ **Enhanced Throughput**: Better block space utilization`;
          
        } catch (error) {
          return `❌ Failed to analyze contract performance: ${error}`;
        }
      },
    };
  • Zod schema defining the input parameters for the analyze_contract_performance tool: contract code, optional function name, and optimization level.
    const ContractAnalysisScheme = z.object({
      contractCode: z.string().describe("The Clarity contract code to analyze"),
      functionName: z.string().optional().describe("Specific function to analyze (optional)"),
      optimizationLevel: z.enum(["basic", "intermediate", "advanced"]).describe("Level of optimization analysis"),
    });
  • Registration of the analyzeContractPerformanceTool in the FastMCP server via registerTools function.
    server.addTool(analyzeContractPerformanceTool);
  • Import statement that brings the analyzeContractPerformanceTool into the index.ts for registration.
    import {
      analyzeContractPerformanceTool,
      estimateOperationCostTool,
      generateOptimizationRecommendationsTool
    } from "./stacks_blockchain/performance/sip012_cost_analysis.js";
  • Key helper function called by the handler to parse and analyze the contract code, count operations, estimate SIP-012 costs, and detect performance issues.
    function analyzeContractCode(code: string, targetFunction?: string) {
      // Simplified contract analysis
      const mapOperations = (code.match(/map-(get|set|delete)\?/g) || []).length;
      const listOperations = (code.match(/\b(append|filter|map|fold)\b/g) || []).length;
      const contractCalls = (code.match(/contract-call\?/g) || []).length;
      const functionCount = (code.match(/define-(public|private|read-only)/g) || []).length;
      
      // Estimate costs based on operations
      const estimatedCosts = {
        runtime: mapOperations * SIP012_COSTS.runtime.mapGet + 
                listOperations * SIP012_COSTS.runtime.listAppend + 
                contractCalls * SIP012_COSTS.runtime.contractCall,
        readCount: mapOperations + listOperations,
        writeCount: (code.match(/map-set|map-delete/g) || []).length,
        readLength: mapOperations * 40 + listOperations * 100,
        writeLength: (code.match(/map-set|map-delete/g) || []).length * 40,
      };
      
      // Identify performance issues
      const issues = [];
      
      if (mapOperations > 10) {
        issues.push({
          type: "High Database Usage",
          severity: "Medium",
          description: "Contract performs many map operations",
          impact: "May hit read/write count limits",
          location: "Multiple functions"
        });
      }
      
      if (listOperations > 5) {
        issues.push({
          type: "Inefficient List Processing",
          severity: "Medium", 
          description: "Multiple list operations detected",
          impact: "High runtime costs",
          location: "List processing functions"
        });
      }
      
      if (contractCalls > 3) {
        issues.push({
          type: "Cross-Contract Dependencies",
          severity: "Low",
          description: "Multiple external contract calls",
          impact: "Increased transaction complexity",
          location: "External interactions"
        });
      }
      
      return {
        functionCount,
        mapOperations,
        listOperations,
        contractCalls,
        estimatedCosts,
        issues
      };
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions the tool 'analyzes' and 'provides' outputs, which implies a read-only operation, but doesn't specify whether it requires specific permissions, has rate limits, whether the analysis is cached, what format the output takes, or any side effects. For a tool with 3 parameters and no annotation coverage, this is insufficient behavioral context.

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

Conciseness4/5

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

The description is efficiently structured in two sentences that cover purpose and outputs. It's appropriately sized for the tool's complexity, though it could be slightly more front-loaded by mentioning the key parameters. Every sentence contributes meaningful information without redundancy.

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

Completeness3/5

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

Given moderate complexity (3 parameters, no output schema, no annotations), the description provides basic purpose and outputs but lacks important context. It doesn't explain the relationship to sibling tools, doesn't describe output format or structure, and provides minimal behavioral guidance. For a tool that performs analysis and provides recommendations, more completeness about what 'detailed cost breakdown' entails would be helpful.

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

Parameters3/5

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

Schema description coverage is 100%, so the schema already documents all three parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema - it doesn't explain what 'SIP-012 optimization opportunities' means in practice, how 'optimizationLevel' affects the analysis, or provide examples of contractCode format. Baseline 3 is appropriate when schema does the heavy lifting.

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

Purpose4/5

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

The description clearly states the tool analyzes Clarity contracts for performance bottlenecks and SIP-012 optimization opportunities, providing cost breakdowns and recommendations. It specifies the resource (Clarity contract) and outcomes (bottlenecks, optimization, cost breakdown). However, it doesn't explicitly differentiate from sibling tools like 'generate_optimization_recommendations' or 'estimate_operation_cost' that might overlap in functionality.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. With siblings like 'generate_optimization_recommendations' and 'estimate_operation_cost' that might serve similar purposes, there's no indication of when this specific analysis tool is preferred, what prerequisites exist, or when other tools might be more appropriate.

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/exponentlabshq/stacks-clarity-mcp'

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