Skip to main content
Glama

初始化项目配置

gitea_init

Initialize project configuration files for Gitea MCP integration. Auto-detects Git repository information and Gitea server settings to set up connection.

Instructions

Initialize project configuration files (.gitea-mcp.json). Auto-detects Git repository info if available.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
ownerNoRepository owner (username or organization). Auto-detected from Git if not provided.
repoNoRepository name. Auto-detected from Git if not provided.
gitea_urlNoGitea server URL. Auto-detected from Git remote if not provided.
set_as_defaultNoSet this repository as default context (default: true)
forceNoForce overwrite existing configuration (default: false)

Implementation Reference

  • The handler function for the gitea_init tool. It detects Git repository information from the current working directory, elicits additional input via MCP elicitation if necessary, determines configuration parameters, validates them, checks for existing config, creates the project configuration using getProjectConfig, updates context if set as default, and returns success/error response.
    async (args) => {
      logger.debug({ args }, 'gitea_init called');
    
      try {
        // 获取工作目录
        const workingDir = process.cwd();
    
        // 自动检测 Git 信息
        const gitInfo = detectGitInfo(workingDir);
    
        // 如果自动检测失败且没有提供参数,使用 elicitation
        if (
          (!args.owner || !args.repo) &&
          (!gitInfo.owner || !gitInfo.repo)
        ) {
          // 使用 elicitation 请求用户输入
          const result = await ctx.server.server.elicitInput({
            message: '无法自动检测仓库信息,请手动输入:',
            requestedSchema: {
              type: 'object',
              properties: {
                owner: {
                  type: 'string',
                  title: '仓库所有者',
                  description: '用户名或组织名',
                },
                repo: {
                  type: 'string',
                  title: '仓库名称',
                  description: '仓库的名称',
                },
                gitea_url: {
                  type: 'string',
                  title: 'Gitea 服务器 URL',
                  description: 'Gitea 服务器地址',
                  default: ctx.client['config'].baseUrl,
                },
                set_as_default: {
                  type: 'boolean',
                  title: '设为默认上下文',
                  description: '是否将此仓库设为默认上下文',
                  default: true,
                },
              },
              required: ['owner', 'repo'],
            },
          });
    
          if (result.action !== 'accept') {
            return {
              content: [
                {
                  type: 'text',
                  text: 'Configuration initialization cancelled by user',
                },
              ],
            };
          }
    
          // 使用用户输入的数据
          args = {
            ...args,
            owner: (result.content?.owner as string) || args.owner,
            repo: (result.content?.repo as string) || args.repo,
            gitea_url: (result.content?.gitea_url as string) || args.gitea_url,
            set_as_default:
              (result.content?.set_as_default as boolean) ?? args.set_as_default,
          };
        }
    
        // 确定配置参数(优先使用参数,其次使用 Git 检测)
        const owner = args.owner || gitInfo.owner;
        const repo = args.repo || gitInfo.repo;
        const giteaUrl = args.gitea_url || gitInfo.serverUrl || ctx.client['config'].baseUrl;
        const setAsDefault = args.set_as_default !== false; // 默认为 true
        const force = args.force || false;
    
        // 验证必需参数
        if (!owner || !repo) {
          return {
            content: [
              {
                type: 'text',
                text: `Missing required parameters: owner and repo. Auto-detection result: owner=${gitInfo.owner || 'N/A'}, repo=${gitInfo.repo || 'N/A'}`,
              },
            ],
            isError: true,
          };
        }
    
        // 获取项目配置管理器
        const projectConfig = getProjectConfig(workingDir);
    
        // 检查是否已存在配置
        if (!force && projectConfig.hasProjectConfig()) {
          return {
            content: [
              {
                type: 'text',
                text: `Project configuration already exists at ${projectConfig.getProjectConfigPath()}. Use force=true to overwrite.`,
              },
            ],
            isError: true,
          };
        }
    
        // 创建项目配置
        const createdConfig = projectConfig.createProjectConfig(
          {
            url: giteaUrl,
            name: giteaUrl.replace(/https?:\/\//, ''),
          },
          {
            owner,
            repo,
          },
          {
            setAsDefaultContext: setAsDefault,
          }
        );
    
        // 如果设置为默认上下文,更新上下文管理器
        if (setAsDefault) {
          ctx.contextManager.setContext({
            owner,
            repo,
          });
        }
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  success: true,
                  message: 'Project configuration initialized successfully',
                  filesCreated: [projectConfig.getProjectConfigPath()],
                  config: createdConfig,
                  detectedInfo: {
                    isGitRepo: gitInfo.isGitRepo,
                    detectedOwner: gitInfo.owner,
                    detectedRepo: gitInfo.repo,
                    detectedUrl: gitInfo.serverUrl,
                  },
                  defaultContext: setAsDefault ? { owner, repo } : null,
                },
                null,
                2
              ),
            },
          ],
        };
      } catch (error: unknown) {
        const errorMessage = error instanceof Error ? error.message : String(error);
        logger.error({ error: errorMessage }, 'Failed to initialize configuration');
        return {
          content: [
            {
              type: 'text',
              text: `Error: ${errorMessage}`,
            },
          ],
          isError: true,
        };
      }
    }
  • Zod schema defining the input parameters for the gitea_init tool. All parameters are optional as they can be auto-detected.
    inputSchema: z.object({
      owner: z
        .string()
        .optional()
        .describe(
          'Repository owner (username or organization). Auto-detected from Git if not provided.'
        ),
      repo: z
        .string()
        .optional()
        .describe('Repository name. Auto-detected from Git if not provided.'),
      gitea_url: z
        .string()
        .optional()
        .describe('Gitea server URL. Auto-detected from Git remote if not provided.'),
      set_as_default: z
        .boolean()
        .optional()
        .describe('Set this repository as default context (default: true)'),
      force: z
        .boolean()
        .optional()
        .describe('Force overwrite existing configuration (default: false)'),
    }),
  • src/index.ts:158-356 (registration)
    Registration of the gitea_init tool on the McpServer instance within the registerInitTools function. Includes title, description, input schema, and inline handler.
    mcpServer.registerTool(
      'gitea_init',
      {
        title: '初始化项目配置',
        description:
          'Initialize project configuration files (.gitea-mcp.json). Auto-detects Git repository info if available.',
        inputSchema: z.object({
          owner: z
            .string()
            .optional()
            .describe(
              'Repository owner (username or organization). Auto-detected from Git if not provided.'
            ),
          repo: z
            .string()
            .optional()
            .describe('Repository name. Auto-detected from Git if not provided.'),
          gitea_url: z
            .string()
            .optional()
            .describe('Gitea server URL. Auto-detected from Git remote if not provided.'),
          set_as_default: z
            .boolean()
            .optional()
            .describe('Set this repository as default context (default: true)'),
          force: z
            .boolean()
            .optional()
            .describe('Force overwrite existing configuration (default: false)'),
        }),
      },
      async (args) => {
        logger.debug({ args }, 'gitea_init called');
    
        try {
          // 获取工作目录
          const workingDir = process.cwd();
    
          // 自动检测 Git 信息
          const gitInfo = detectGitInfo(workingDir);
    
          // 如果自动检测失败且没有提供参数,使用 elicitation
          if (
            (!args.owner || !args.repo) &&
            (!gitInfo.owner || !gitInfo.repo)
          ) {
            // 使用 elicitation 请求用户输入
            const result = await ctx.server.server.elicitInput({
              message: '无法自动检测仓库信息,请手动输入:',
              requestedSchema: {
                type: 'object',
                properties: {
                  owner: {
                    type: 'string',
                    title: '仓库所有者',
                    description: '用户名或组织名',
                  },
                  repo: {
                    type: 'string',
                    title: '仓库名称',
                    description: '仓库的名称',
                  },
                  gitea_url: {
                    type: 'string',
                    title: 'Gitea 服务器 URL',
                    description: 'Gitea 服务器地址',
                    default: ctx.client['config'].baseUrl,
                  },
                  set_as_default: {
                    type: 'boolean',
                    title: '设为默认上下文',
                    description: '是否将此仓库设为默认上下文',
                    default: true,
                  },
                },
                required: ['owner', 'repo'],
              },
            });
    
            if (result.action !== 'accept') {
              return {
                content: [
                  {
                    type: 'text',
                    text: 'Configuration initialization cancelled by user',
                  },
                ],
              };
            }
    
            // 使用用户输入的数据
            args = {
              ...args,
              owner: (result.content?.owner as string) || args.owner,
              repo: (result.content?.repo as string) || args.repo,
              gitea_url: (result.content?.gitea_url as string) || args.gitea_url,
              set_as_default:
                (result.content?.set_as_default as boolean) ?? args.set_as_default,
            };
          }
    
          // 确定配置参数(优先使用参数,其次使用 Git 检测)
          const owner = args.owner || gitInfo.owner;
          const repo = args.repo || gitInfo.repo;
          const giteaUrl = args.gitea_url || gitInfo.serverUrl || ctx.client['config'].baseUrl;
          const setAsDefault = args.set_as_default !== false; // 默认为 true
          const force = args.force || false;
    
          // 验证必需参数
          if (!owner || !repo) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Missing required parameters: owner and repo. Auto-detection result: owner=${gitInfo.owner || 'N/A'}, repo=${gitInfo.repo || 'N/A'}`,
                },
              ],
              isError: true,
            };
          }
    
          // 获取项目配置管理器
          const projectConfig = getProjectConfig(workingDir);
    
          // 检查是否已存在配置
          if (!force && projectConfig.hasProjectConfig()) {
            return {
              content: [
                {
                  type: 'text',
                  text: `Project configuration already exists at ${projectConfig.getProjectConfigPath()}. Use force=true to overwrite.`,
                },
              ],
              isError: true,
            };
          }
    
          // 创建项目配置
          const createdConfig = projectConfig.createProjectConfig(
            {
              url: giteaUrl,
              name: giteaUrl.replace(/https?:\/\//, ''),
            },
            {
              owner,
              repo,
            },
            {
              setAsDefaultContext: setAsDefault,
            }
          );
    
          // 如果设置为默认上下文,更新上下文管理器
          if (setAsDefault) {
            ctx.contextManager.setContext({
              owner,
              repo,
            });
          }
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(
                  {
                    success: true,
                    message: 'Project configuration initialized successfully',
                    filesCreated: [projectConfig.getProjectConfigPath()],
                    config: createdConfig,
                    detectedInfo: {
                      isGitRepo: gitInfo.isGitRepo,
                      detectedOwner: gitInfo.owner,
                      detectedRepo: gitInfo.repo,
                      detectedUrl: gitInfo.serverUrl,
                    },
                    defaultContext: setAsDefault ? { owner, repo } : null,
                  },
                  null,
                  2
                ),
              },
            ],
          };
        } catch (error: unknown) {
          const errorMessage = error instanceof Error ? error.message : String(error);
          logger.error({ error: errorMessage }, 'Failed to initialize configuration');
          return {
            content: [
              {
                type: 'text',
                text: `Error: ${errorMessage}`,
              },
            ],
            isError: true,
          };
        }
      }
    );
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 auto-detection capabilities which is useful context, but doesn't address important behavioral aspects: whether this is a read-only or write operation (implied write from 'Initialize'), what permissions are required, whether it creates files locally or remotely, error handling, or what happens when auto-detection fails. For a configuration initialization tool with zero annotation coverage, this leaves significant gaps.

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 appropriately sized with two concise sentences that get straight to the point. The first sentence states the core purpose, and the second adds important context about auto-detection. There's no wasted verbiage, though it could be slightly more structured with clearer separation of concerns.

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?

For a configuration initialization tool with 5 parameters, no annotations, and no output schema, the description is incomplete. It doesn't explain what the tool actually produces (beyond mentioning the file name), what format the configuration takes, whether it validates inputs, or what happens on success/failure. The auto-detection mention is helpful but insufficient for a tool that presumably creates or modifies system configuration.

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 fully documents all 5 parameters. The description adds minimal value beyond the schema - it mentions auto-detection generally but doesn't provide additional context about parameter interactions or edge cases. The baseline of 3 is appropriate when the schema does the heavy lifting, though the description could have added more about how parameters work together.

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 action ('Initialize project configuration files') and the specific resource ('.gitea-mcp.json'), providing a specific verb+resource combination. It distinguishes from siblings like 'gitea_compliance_init' or 'gitea_workflow_init' by focusing on configuration file creation rather than compliance or workflow setup. However, it doesn't explicitly contrast with these similar-named tools.

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 mentions auto-detection capabilities but doesn't explain when manual parameter input might be preferable, nor does it reference any sibling tools for comparison. There are no explicit when/when-not instructions or named alternatives provided.

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