Skip to main content
Glama

检查提交信息规范

gitea_compliance_check_commit

Validate commit messages against Conventional Commit format by checking SHA or message directly to ensure compliance with project standards.

Instructions

Check if commit message complies with Conventional Commit format. Can check by SHA or message directly.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
ownerNoRepository owner. Uses context if not provided
repoNoRepository name. Uses context if not provided
shaNoCommit SHA to check (will fetch message from API)
messageNoCommit message to check directly
config_pathNoPath to compliance config file
tokenNoOptional API token to override default authentication

Implementation Reference

  • Main handler function for checking commit message compliance. Fetches commit message via Gitea API if SHA provided, parses using Conventional Commit regex, validates type, scope, length, capitalization against loaded config, returns detailed result with issues and suggestions.
    export async function checkCommit(
      ctx: ComplianceToolsContext,
      params: CheckCommitParams
    ): Promise<CommitCheckResult> {
      const config = loadComplianceConfig(params.config_path);
      const owner = ctx.contextManager.resolveOwner(params.owner);
      const repo = ctx.contextManager.resolveRepo(params.repo);
    
      let message = params.message;
      let sha = params.sha || '';
    
      // 如果提供了 SHA,从 API 获取提交信息
      if (params.sha && !params.message) {
        try {
          const response = await ctx.client.request({
            method: 'GET',
            path: `/repos/${owner}/${repo}/git/commits/${params.sha}`,
            token: params.token,
          });
          message = (response.data as any)?.commit?.message || (response.data as any)?.message || '';
          sha = params.sha;
        } catch (err) {
          logger.warn({ sha: params.sha, error: err }, 'Failed to fetch commit');
          return {
            sha: params.sha,
            message: '',
            compliant: false,
            issues: [`无法获取提交 ${params.sha} 的信息`],
            suggestions: [],
          };
        }
      }
    
      if (!message) {
        return {
          sha,
          message: '',
          compliant: false,
          issues: ['未提供提交信息'],
          suggestions: [],
        };
      }
    
      logger.info({ sha, message: message.substring(0, 50) }, 'Checking commit message');
    
      const issues: string[] = [];
      const suggestions: string[] = [];
      const parsed = parseConventionalCommit(message);
    
      if (!parsed.valid) {
        issues.push('提交信息不符合 Conventional Commit 格式');
        suggestions.push('正确格式: <type>(<scope>): <subject>');
        suggestions.push('示例: feat(cli): add new command');
      } else {
        // 检查 type 是否有效
        if (parsed.type && !config.commit.types.includes(parsed.type)) {
          issues.push(`无效的提交类型: ${parsed.type}`);
          suggestions.push(`允许的类型: ${config.commit.types.join(', ')}`);
        }
    
        // 检查是否需要 scope
        if (config.commit.scope_required && !parsed.scope) {
          issues.push('缺少作用域 (scope)');
          suggestions.push('请在类型后添加作用域,如: feat(cli): ...');
        }
    
        // 检查 subject 长度
        if (parsed.subject && parsed.subject.length > config.commit.max_subject_length) {
          issues.push(`主题行过长: ${parsed.subject.length} 字符 (最大 ${config.commit.max_subject_length})`);
          suggestions.push('请缩短主题行,详细信息放在正文中');
        }
    
        // 检查主题行是否以大写开头
        if (parsed.subject && /^[A-Z]/.test(parsed.subject)) {
          issues.push('主题行不应以大写字母开头');
          suggestions.push('主题行应以小写字母开头');
        }
    
        // 检查主题行是否以句号结尾
        if (parsed.subject && parsed.subject.endsWith('.')) {
          issues.push('主题行不应以句号结尾');
        }
      }
    
      return {
        sha,
        message,
        compliant: issues.length === 0,
        issues,
        suggestions,
        type: parsed.type,
        scope: parsed.scope,
        subject: parsed.subject,
      };
    }
  • Tool registration in MCP server, including title, description, input schema using Zod, and wrapper handler that calls the main checkCommit function with context.
    mcpServer.registerTool(
      'gitea_compliance_check_commit',
      {
        title: '检查提交信息规范',
        description: 'Check if commit message complies with Conventional Commit format. Can check by SHA or message directly.',
        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'),
          sha: z.string().optional().describe('Commit SHA to check (will fetch message from API)'),
          message: z.string().optional().describe('Commit message to check directly'),
          config_path: z.string().optional().describe('Path to compliance config file'),
          token: tokenSchema,
        }),
      },
      async (args) => {
        try {
          const result = await ComplianceTools.checkCommit(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 defining parameters: owner, repo, sha, message, config_path, 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'),
      sha: z.string().optional().describe('Commit SHA to check (will fetch message from API)'),
      message: z.string().optional().describe('Commit message to check directly'),
      config_path: z.string().optional().describe('Path to compliance config file'),
      token: tokenSchema,
    }),
  • Helper function to parse commit message using regex for Conventional Commit format: type(scope): subject.
    function parseConventionalCommit(message: string): {
      type?: string;
      scope?: string;
      subject?: string;
      valid: boolean;
    } {
      // 格式: type(scope): subject 或 type: subject
      const regex = /^(\w+)(?:\(([^)]+)\))?:\s*(.+)$/;
      const firstLine = message.split('\n')[0].trim();
      const match = firstLine.match(regex);
    
      if (match) {
        return {
          type: match[1],
          scope: match[2],
          subject: match[3],
          valid: true,
        };
      }
    
      return { valid: false };
    }
  • Loads compliance config from .gitea/compliance.yaml or falls back to defaults, merges with overrides.
    export function loadComplianceConfig(configPath?: string): ComplianceConfig {
      const searchPaths = [
        configPath,
        path.join(process.cwd(), '.gitea', 'compliance.yaml'),
        path.join(process.cwd(), '.gitea', 'compliance.yml'),
      ].filter(Boolean) as string[];
    
      for (const p of searchPaths) {
        if (fs.existsSync(p)) {
          try {
            const content = fs.readFileSync(p, 'utf-8');
            const parsed = yaml.parse(content);
            logger.info({ path: p }, 'Loaded compliance config');
            return mergeConfig(DEFAULT_CONFIG, parsed);
          } catch (err) {
            logger.warn({ path: p, error: err }, 'Failed to parse compliance config');
          }
        }
      }
    
      logger.info('Using default compliance config');
      return DEFAULT_CONFIG;
    }
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. It mentions the tool can check via SHA (fetching from API) or direct message input, which adds some behavioral context. However, it lacks critical details: it doesn't disclose authentication requirements (implied by the 'token' parameter but not stated), rate limits, error handling, or what the output looks like (e.g., pass/fail result, detailed errors). For a tool with no annotations, this is a significant gap.

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 appropriately sized and front-loaded: a single sentence states the core purpose, followed by a second sentence clarifying the two checking methods. Every sentence earns its place with no wasted words, making it easy to scan and understand quickly.

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 (6 parameters, no annotations, no output schema), the description is incomplete. It lacks information on authentication needs, output format (critical for a compliance check tool), error conditions, and how it differs from sibling tools. Without annotations or an output schema, the description should provide more behavioral and result 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 6 parameters thoroughly. The description adds minimal value beyond the schema: it mentions 'SHA or message directly,' which implies the 'sha' and 'message' parameters are alternatives, but this is somewhat redundant with the schema's descriptions. Baseline 3 is appropriate as the schema does the heavy lifting, though the description doesn't compensate with additional insights like parameter interactions or defaults.

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 commit message complies with Conventional Commit format.' It specifies the action (check compliance) and the resource (commit message). However, it doesn't explicitly differentiate from sibling tools like 'gitea_compliance_check_all' or 'gitea_compliance_check_branch', which likely check different scopes 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 Guidelines3/5

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

The description provides implied usage by mentioning two methods: 'Can check by SHA or message directly.' This gives some guidance on when to use each approach, but it doesn't explicitly state when to choose this tool over alternatives like 'gitea_compliance_check_all' or clarify prerequisites (e.g., authentication needs). No exclusions or explicit alternatives are mentioned.

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