Skip to main content
Glama

生成工作流报告

gitea_workflow_generate_report

Generate workflow reports with issue statistics, health scores, and actionable recommendations for Gitea repositories. Outputs in JSON and Markdown formats.

Instructions

Generate a comprehensive workflow report including issue statistics, health score, and recommendations. Output in JSON and Markdown formats.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
ownerNoRepository owner. Uses context if not provided
repoNoRepository name. Uses context if not provided
time_rangeNoTime range for statistics (default: all time)

Implementation Reference

  • The core handler function that generates comprehensive workflow reports. Fetches open and closed issues, computes statistics by status/priority/type, calculates average age and health score, generates recommendations, and produces a Markdown report.
    export async function workflowGenerateReport(
      ctx: WorkflowToolsContext,
      args: {
        owner?: string;
        repo?: string;
        config?: WorkflowConfig;
        time_range?: 'day' | 'week' | 'month';
      }
    ): Promise<{
      success: boolean;
      report: {
        summary: {
          total_open: number;
          total_closed: number;
          by_status: Record<string, number>;
          by_priority: Record<string, number>;
          by_type: Record<string, number>;
        };
        blocked_count: number;
        avg_age_days: number;
        health_score: number;
        recommendations: string[];
      };
      markdown_report: string;
      error?: string;
    }> {
      logger.debug({ args: { ...args, config: args.config ? '[provided]' : undefined } }, 'Generating report');
    
      const { owner, repo } = ctx.contextManager.resolveOwnerRepo(args.owner, args.repo);
    
      // 获取配置
      let config = args.config;
      if (!config) {
        const loadResult = await workflowLoadConfig(ctx, { owner, repo });
        if (!loadResult.success || !loadResult.config) {
          return {
            success: false,
            report: {
              summary: { total_open: 0, total_closed: 0, by_status: {}, by_priority: {}, by_type: {} },
              blocked_count: 0,
              avg_age_days: 0,
              health_score: 0,
              recommendations: [],
            },
            markdown_report: '',
            error: loadResult.error || '无法加载配置',
          };
        }
        config = loadResult.config;
      }
    
      try {
        // 获取开放和关闭的 Issue
        const openIssues = await ctx.client.get<Issue[]>(`/repos/${owner}/${repo}/issues?state=open&limit=100`);
        const closedIssues = await ctx.client.get<Issue[]>(`/repos/${owner}/${repo}/issues?state=closed&limit=50`);
    
        // 统计
        const byStatus: Record<string, number> = {};
        const byPriority: Record<string, number> = {};
        const byType: Record<string, number> = {};
        let totalAgeDays = 0;
        let blockedCount = 0;
    
        for (const issue of openIssues) {
          // 状态统计
          const status = getIssueStatus(issue) || 'unknown';
          byStatus[status] = (byStatus[status] || 0) + 1;
    
          // 优先级统计
          const priority = getIssuePriority(issue) || 'unknown';
          byPriority[priority] = (byPriority[priority] || 0) + 1;
    
          // 类型统计
          const prefixes = getLabelPrefixes(config);
          const typeLabel = issue.labels.find((l) => matchLabel(prefixes.type, l.name) !== null);
          const type = typeLabel ? (matchLabel(prefixes.type, typeLabel.name) || 'unknown') : 'unknown';
          byType[type] = (byType[type] || 0) + 1;
    
          // 年龄统计
          totalAgeDays += calculateIssueAgeDays(issue);
    
          // 阻塞统计
          const blockedLabel = buildLabel(prefixes.workflow, 'blocked');
          if (hasLabel(issue, blockedLabel)) {
            blockedCount++;
          }
        }
    
        const avgAgeDays = openIssues.length > 0 ? Math.round(totalAgeDays / openIssues.length) : 0;
    
        // 计算健康度评分 (0-100)
        let healthScore = 100;
        if (blockedCount > 0) healthScore -= blockedCount * 5;
        if (avgAgeDays > 30) healthScore -= 20;
        else if (avgAgeDays > 14) healthScore -= 10;
        if (byPriority['P0'] && byPriority['P0'] > 0) healthScore -= byPriority['P0'] * 10;
        healthScore = Math.max(0, Math.min(100, healthScore));
    
        // 生成建议
        const recommendations: string[] = [];
        if (blockedCount > 0) {
          recommendations.push(`有 ${blockedCount} 个 Issue 被阻塞,请及时处理`);
        }
        if (byPriority['P0'] && byPriority['P0'] > 0) {
          recommendations.push(`有 ${byPriority['P0']} 个紧急 Issue (P0),需要立即关注`);
        }
        if (avgAgeDays > 30) {
          recommendations.push(`Issue 平均年龄为 ${avgAgeDays} 天,建议加快处理速度`);
        }
        if (byStatus['unknown'] && byStatus['unknown'] > 0) {
          recommendations.push(`有 ${byStatus['unknown']} 个 Issue 缺少状态标签`);
        }
    
        // 生成 Markdown 报告
        const markdownReport = generateMarkdownReport(
          owner,
          repo,
          {
            total_open: openIssues.length,
            total_closed: closedIssues.length,
            by_status: byStatus,
            by_priority: byPriority,
            by_type: byType,
          },
          blockedCount,
          avgAgeDays,
          healthScore,
          recommendations
        );
    
        logger.info({ owner, repo, open: openIssues.length, health_score: healthScore }, 'Report generated');
    
        return {
          success: true,
          report: {
            summary: {
              total_open: openIssues.length,
              total_closed: closedIssues.length,
              by_status: byStatus,
              by_priority: byPriority,
              by_type: byType,
            },
            blocked_count: blockedCount,
            avg_age_days: avgAgeDays,
            health_score: healthScore,
            recommendations,
          },
          markdown_report: markdownReport,
        };
      } catch (error) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        logger.error({ owner, repo, error: errorMessage }, 'Failed to generate report');
    
        return {
          success: false,
          report: {
            summary: { total_open: 0, total_closed: 0, by_status: {}, by_priority: {}, by_type: {} },
            blocked_count: 0,
            avg_age_days: 0,
            health_score: 0,
            recommendations: [],
          },
          markdown_report: '',
          error: errorMessage,
        };
      }
    }
  • Zod input schema defining parameters: owner, repo (optional), time_range (enum: day/week/month, optional).
    inputSchema: z.object({
      owner: z.string().optional().describe('Repository owner. Uses context if not provided'),
      repo: z.string().optional().describe('Repository name. Uses context if not provided'),
      time_range: z
        .enum(['day', 'week', 'month'])
        .optional()
        .describe('Time range for statistics (default: all time)'),
    }),
  • Tool registration in MCP server, including title, description, input schema, and handler wrapper that calls the workflowGenerateReport function and handles errors.
    mcpServer.registerTool(
      'gitea_workflow_generate_report',
      {
        title: '生成工作流报告',
        description:
          'Generate a comprehensive workflow report including issue statistics, health score, and recommendations. Output in JSON and Markdown formats.',
        inputSchema: z.object({
          owner: z.string().optional().describe('Repository owner. Uses context if not provided'),
          repo: z.string().optional().describe('Repository name. Uses context if not provided'),
          time_range: z
            .enum(['day', 'week', 'month'])
            .optional()
            .describe('Time range for statistics (default: all time)'),
        }),
      },
      async (args) => {
        try {
          const result = await WorkflowTools.workflowGenerateReport(
            { client: ctx.client, contextManager: ctx.contextManager },
            args
          );
          return {
            content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
            isError: !result.success,
          };
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          return {
            content: [{ type: 'text' as const, text: `Error: ${errorMessage}` }],
            isError: true,
          };
        }
      }
    );
  • Helper function to generate the Markdown-formatted report string used in the handler.
    function generateMarkdownReport(
      owner: string,
      repo: string,
      summary: {
        total_open: number;
        total_closed: number;
        by_status: Record<string, number>;
        by_priority: Record<string, number>;
        by_type: Record<string, number>;
      },
      blockedCount: number,
      avgAgeDays: number,
      healthScore: number,
      recommendations: string[]
    ): string {
      const lines: string[] = [
        `# ${owner}/${repo} 工作流报告`,
        '',
        `生成时间: ${new Date().toISOString()}`,
        '',
        '## 概览',
        '',
        `| 指标 | 值 |`,
        `|------|-----|`,
        `| 开放 Issue | ${summary.total_open} |`,
        `| 已关闭 Issue | ${summary.total_closed} |`,
        `| 阻塞 Issue | ${blockedCount} |`,
        `| 平均年龄 | ${avgAgeDays} 天 |`,
        `| 健康度评分 | ${healthScore}/100 |`,
        '',
        '## 状态分布',
        '',
        '| 状态 | 数量 |',
        '|------|------|',
      ];
    
      for (const [status, count] of Object.entries(summary.by_status)) {
        lines.push(`| ${status} | ${count} |`);
      }
    
      lines.push('');
      lines.push('## 优先级分布');
      lines.push('');
      lines.push('| 优先级 | 数量 |');
      lines.push('|--------|------|');
    
      for (const [priority, count] of Object.entries(summary.by_priority)) {
        lines.push(`| ${priority} | ${count} |`);
      }
    
      lines.push('');
      lines.push('## 类型分布');
      lines.push('');
      lines.push('| 类型 | 数量 |');
      lines.push('|------|------|');
    
      for (const [type, count] of Object.entries(summary.by_type)) {
        lines.push(`| ${type} | ${count} |`);
      }
    
      if (recommendations.length > 0) {
        lines.push('');
        lines.push('## 建议');
        lines.push('');
        for (const rec of recommendations) {
          lines.push(`- ${rec}`);
        }
      }
    
      return lines.join('\n');
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the output formats (JSON and Markdown) but doesn't cover critical aspects like whether this is a read-only operation, potential side effects, authentication needs, rate limits, or how the report is generated (e.g., computational cost). For a tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

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

Conciseness5/5

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

The description is a single, efficient sentence that front-loads the key action and details without waste. Every part (verb, content, output formats) earns its place, making it appropriately sized and well-structured for quick understanding.

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 the complexity (3 parameters, no output schema, no annotations), the description is moderately complete. It specifies the report content and output formats, which helps, but lacks details on behavioral traits, usage context, and output structure. Without annotations or output schema, more guidance on what the report includes and how to interpret it would improve completeness for a tool generating comprehensive data.

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?

The description adds no parameter-specific information beyond what the input schema provides. Since schema description coverage is 100%, the baseline score is 3. The schema already documents owner, repo, and time_range with descriptions and enums, so the description doesn't compensate but doesn't need to, given the high coverage.

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 generates a comprehensive workflow report with specific content (issue statistics, health score, recommendations) and output formats (JSON and Markdown). It uses the verb 'generate' with the resource 'workflow report,' making the purpose explicit. However, it doesn't differentiate from sibling tools like gitea_workflow_check_issues or gitea_workflow_check_blocked, which might also involve workflow analysis.

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. It doesn't mention prerequisites, context requirements, or compare it to sibling tools such as gitea_workflow_check_issues for issue-specific checks. Usage is implied by the purpose but lacks explicit when/when-not instructions or named alternatives.

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/SupenBysz/gitea-mcp-tool'

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