Skip to main content
Glama

检查 PR 格式规范

gitea_compliance_check_pr

Validate pull request descriptions against format requirements including sections and issue links to ensure compliance with project standards.

Instructions

Check if PR description complies with format requirements (sections, issue links, etc.).

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
ownerNoRepository owner. Uses context if not provided
repoNoRepository name. Uses context if not provided
pr_numberYesPull request number to check
config_pathNoPath to compliance config file
tokenNoOptional API token to override default authentication

Implementation Reference

  • Core handler function that implements the gitea_compliance_check_pr tool logic. It fetches the PR details from Gitea API, checks for required sections in the PR body using regex patterns, validates if an issue link is present using multiple regex patterns, optionally checks title format, collects issues and suggestions, and returns a structured PRCheckResult.
    export async function checkPR(
      ctx: ComplianceToolsContext,
      params: CheckPRParams
    ): Promise<PRCheckResult> {
      const config = loadComplianceConfig(params.config_path);
      const owner = ctx.contextManager.resolveOwner(params.owner);
      const repo = ctx.contextManager.resolveRepo(params.repo);
    
      logger.info({ owner, repo, pr: params.pr_number }, 'Checking PR format');
    
      // 获取 PR 信息
      let pr: any;
      try {
        const response = await ctx.client.request({
          method: 'GET',
          path: `/repos/${owner}/${repo}/pulls/${params.pr_number}`,
          token: params.token,
        });
        pr = response.data;
      } catch (err) {
        logger.warn({ pr: params.pr_number, error: err }, 'Failed to fetch PR');
        return {
          pr_number: params.pr_number,
          title: '',
          compliant: false,
          issues: [`无法获取 PR #${params.pr_number} 的信息`],
          suggestions: [],
          missing_sections: [],
          has_issue_link: false,
        };
      }
    
      const issues: string[] = [];
      const suggestions: string[] = [];
      const body = pr.body || '';
      const title = pr.title || '';
    
      // 检查必需章节
      const missingSections: string[] = [];
      for (const section of config.pr.required_sections) {
        // 检查 ## Section 或 # Section 格式
        const sectionRegex = new RegExp(`^#+\\s*${section}`, 'mi');
        if (!sectionRegex.test(body)) {
          missingSections.push(section);
        }
      }
    
      if (missingSections.length > 0) {
        issues.push(`缺少必需的章节: ${missingSections.join(', ')}`);
        suggestions.push('PR 描述应包含以下章节:');
        for (const section of missingSections) {
          suggestions.push(`  ## ${section}`);
        }
      }
    
      // 检查 Issue 链接
      const issuePatterns = [
        /(?:closes?|fixes?|resolves?)\s+#\d+/i,
        /(?:closes?|fixes?|resolves?)\s+https?:\/\/[^\s]+\/issues\/\d+/i,
        /#\d+/,
        /issue[- ]?\d+/i,
      ];
    
      const hasIssueLink = issuePatterns.some((pattern) => pattern.test(body) || pattern.test(title));
    
      if (config.pr.require_issue_link && !hasIssueLink) {
        issues.push('PR 未关联任何 Issue');
        suggestions.push('请在 PR 描述中添加关联的 Issue,如:');
        suggestions.push('  Closes #123');
        suggestions.push('  Fixes #456');
      }
    
      // 检查标题格式(可选,使用 Conventional Commit 格式)
      const titleParsed = parseConventionalCommit(title);
      if (!titleParsed.valid) {
        suggestions.push('建议 PR 标题使用 Conventional Commit 格式:');
        suggestions.push('  feat(scope): add new feature');
        suggestions.push('  fix(scope): fix bug');
      }
    
      return {
        pr_number: params.pr_number,
        title,
        compliant: issues.length === 0,
        issues,
        suggestions,
        missing_sections: missingSections,
        has_issue_link: hasIssueLink,
      };
    }
  • Registration of the 'gitea_compliance_check_pr' MCP tool, including title, description, Zod input schema, and a thin async handler wrapper that calls the core checkPR function and formats the response as MCP content.
    mcpServer.registerTool(
      'gitea_compliance_check_pr',
      {
        title: '检查 PR 格式规范',
        description: 'Check if PR description complies with format requirements (sections, issue links, etc.).',
        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'),
          pr_number: z.number().int().positive().describe('Pull request number to check'),
          config_path: z.string().optional().describe('Path to compliance config file'),
          token: tokenSchema,
        }),
      },
      async (args) => {
        try {
          const result = await ComplianceTools.checkPR(toolsContext, args as any);
          return { content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }] };
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          return { content: [{ type: 'text' as const, text: `Error: ${errorMessage}` }], isError: true };
        }
      }
    );
  • Zod input schema for the tool defining parameters: owner, repo, pr_number (required), config_path, and optional token.
    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'),
      pr_number: z.number().int().positive().describe('Pull request number to check'),
      config_path: z.string().optional().describe('Path to compliance config file'),
      token: tokenSchema,
    }),
  • TypeScript interface defining the input parameters for the checkPR handler.
    export interface CheckPRParams extends ComplianceParams {
      pr_number: number;
      config_path?: string;
    }
  • TypeScript interface defining the output structure of the PR compliance check.
    export interface PRCheckResult extends CheckResult {
      pr_number: number;
      title: string;
      missing_sections: string[];
      has_issue_link: boolean;
    }
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 states the tool checks compliance but doesn't describe what happens during the check (e.g., whether it modifies the PR, returns a report, or requires specific permissions). For a tool with zero annotation coverage, this leaves significant gaps in understanding its behavior and effects.

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: 'Check if PR description complies with format requirements (sections, issue links, etc.)'. It's front-loaded with the core purpose and uses parentheses to clarify scope without unnecessary elaboration. Every word earns its place, making it highly concise and well-structured.

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

Completeness2/5

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

Given the complexity of a compliance check tool with 5 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what the tool returns (e.g., a pass/fail result, detailed errors), how it interacts with the PR, or any behavioral traits like rate limits. For a tool with rich input schema but lacking other structured data, the description should provide more context to be fully 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 5 parameters (owner, repo, pr_number, config_path, token). The description adds no additional meaning beyond what's in the schema, such as explaining the format of 'config_path' or how 'token' overrides authentication. With high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate but doesn't detract either.

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's purpose: 'Check if PR description complies with format requirements (sections, issue links, etc.)'. It specifies the verb ('Check'), resource ('PR description'), and scope ('format requirements'), making it easy to understand what the tool does. However, it doesn't explicitly differentiate from sibling tools like 'gitea_compliance_check_all' or 'gitea_compliance_check_branch', which likely check other aspects of compliance.

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 sibling tools like 'gitea_compliance_check_all' (which might check multiple PRs) or 'gitea_compliance_check_branch' (which might check branch names), nor does it specify prerequisites or exclusions. Usage is implied by the purpose but lacks explicit context for selection.

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