gitea_init
Initialize Gitea project configuration files by auto-detecting Git repository information or accepting manual inputs for repository setup.
Instructions
Initialize project configuration files (.gitea-mcp.json). Auto-detects Git repository info if available.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| owner | No | Repository owner (username or organization). Auto-detected from Git if not provided. | |
| repo | No | Repository name. Auto-detected from Git if not provided. | |
| gitea_url | No | Gitea server URL. Auto-detected from Git remote if not provided. | |
| set_as_default | No | Set this repository as default context (default: true) | |
| force | No | Force overwrite existing configuration (default: false) |
Implementation Reference
- src/index.ts:189-355 (handler)Main handler function for gitea_init tool. Detects Git repository info, elicits user input if necessary, creates .gitea-mcp.json project configuration file, optionally sets as default context, and returns detailed 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, }; } }
- src/index.ts:160-188 (schema)Input schema definition using Zod for the gitea_init tool, including optional parameters for owner, repo, gitea_url, set_as_default, and force.{ 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)'), }), },
- src/index.ts:158-356 (registration)Registration of the gitea_init tool on the MCP server within registerInitTools function.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, }; } } );
- src/utils/git-detector.ts:47-93 (helper)Helper utility to automatically detect Git repository details (server URL, owner, repo) from the local .git directory and origin remote, used for auto-filling gitea_init parameters.export function detectGitInfo(projectPath: string = process.cwd()): GitInfo { const result: GitInfo = { isGitRepo: false, }; try { // Check if .git directory exists const gitDir = path.join(projectPath, '.git'); if (!fs.existsSync(gitDir)) { return result; } result.isGitRepo = true; // Get remote URL (origin) try { const remoteUrl = execSync('git config --get remote.origin.url', { cwd: projectPath, encoding: 'utf-8', }).trim(); if (!remoteUrl) { return result; } result.remoteUrl = remoteUrl; // Parse the remote URL const parsed = parseGitRemoteUrl(remoteUrl); if (parsed) { result.serverUrl = parsed.serverUrl; result.owner = parsed.owner; result.repo = parsed.repo; result.repoPath = `${parsed.owner}/${parsed.repo}`; } else { console.warn(`Failed to parse Git remote URL: ${remoteUrl}`); } } catch (error) { // Git remote not configured console.warn('Git remote not configured:', error); } return result; } catch (error) { console.debug(`Failed to detect Git info: ${error}`); return result; }
- src/config/project.ts:82-105 (helper)ProjectConfigManager.createProjectConfig method that constructs and saves the .gitea-mcp.json configuration file with Gitea server and project details, called by gitea_init handler.createProjectConfig( server: { url: string; serverRef?: string; name?: string }, project: { owner: string; repo: string; org?: string; projectId?: number }, defaults?: { setAsDefaultContext?: boolean } ): ProjectConfig { const config: ProjectConfig = { version: '1.0', gitea: { url: server.url, serverRef: server.serverRef, name: server.name, }, project: { owner: project.owner, repo: project.repo, org: project.org, projectId: project.projectId, }, defaults: defaults || {}, }; this.saveProjectConfig(config); return config; }