# Directory Structure ``` ├── .gitignore ├── LICENSE.txt ├── package.json ├── README.md ├── src │ └── index.ts └── tsconfig.json ``` # Files -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- ``` 1 | # Dependencies 2 | node_modules/ 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | package-lock.json 7 | yarn.lock 8 | 9 | # TypeScript 10 | *.tsbuildinfo 11 | build/ 12 | dist/ 13 | 14 | # IDE - VSCode 15 | .vscode/* 16 | !.vscode/settings.json 17 | !.vscode/tasks.json 18 | !.vscode/launch.json 19 | !.vscode/extensions.json 20 | 21 | # IDE - JetBrains 22 | .idea/ 23 | *.iml 24 | *.iws 25 | .idea_modules/ 26 | 27 | # macOS 28 | .DS_Store 29 | .AppleDouble 30 | .LSOverride 31 | ._* 32 | .DocumentRevisions-V100 33 | .fseventsd 34 | .Spotlight-V100 35 | .TemporaryItems 36 | .Trashes 37 | .VolumeIcon.icns 38 | .com.apple.timemachine.donotpresent 39 | 40 | # Environment files 41 | .env 42 | .env.local 43 | .env.*.local 44 | .env.development 45 | .env.test 46 | .env.production 47 | 48 | # Logs 49 | logs/ 50 | *.log 51 | 52 | # Testing 53 | coverage/ 54 | 55 | # Optional npm cache directory 56 | .npm 57 | 58 | # Optional eslint cache 59 | .eslintcache 60 | 61 | # Optional REPL history 62 | .node_repl_history 63 | 64 | # Output of 'npm pack' 65 | *.tgz 66 | 67 | # Temporary files 68 | *.swp 69 | *.swo 70 | *~ ``` -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- ```markdown 1 | # Git Forensics MCP 2 | 3 | A specialized Model Context Protocol (MCP) server for deep git repository investigation and analysis. This forensics tool provides detailed insights into repository history, branch relationships, and development patterns, focusing solely on git repository analysis rather than general GitHub or git operations. 4 | 5 | ## Features 6 | 7 | The server provides four main analysis tools: 8 | 9 | 1. **Branch Overview** (`get_branch_overview`) 10 | - Provides high-level overview of branch states and relationships 11 | - Analyzes last commits, commit counts, and merge bases 12 | - Generates statistical summaries of branch activities 13 | 14 | 2. **Time Period Analysis** (`analyze_time_period`) 15 | - Analyzes detailed development activity in specific time periods 16 | - Categorizes commits (feature, fix, refactor, docs, other) 17 | - Provides activity summaries with commit patterns 18 | 19 | 3. **File Changes Analysis** (`analyze_file_changes`) 20 | - Tracks changes to specific files across branches 21 | - Identifies potential conflict areas 22 | - Provides risk assessment for file modifications 23 | - Generates recommended review order based on risk levels 24 | 25 | 4. **Merge Recommendations** (`get_merge_recommendations`) 26 | - Determines optimal merge strategies 27 | - Assesses conflict risks 28 | - Identifies code hotspots 29 | - Provides step-by-step merge guidance 30 | 31 | ## Input Parameters 32 | 33 | Each tool requires specific parameters: 34 | 35 | - `repoPath`: Path to the git repository 36 | - `branches`: Array of branch names to analyze 37 | - `outputPath`: Path where analysis results will be written 38 | - Additional tool-specific parameters: 39 | - `timeRange`: Start and end dates for period analysis 40 | - `files`: Array of file paths for file change analysis 41 | 42 | ## Output Format 43 | 44 | All tools output JSON files containing: 45 | - Detailed analysis results 46 | - Summary statistics 47 | - Risk assessments (where applicable) 48 | - Recommendations based on analysis 49 | 50 | ## Technical Details 51 | 52 | - Built with TypeScript 53 | - Uses MCP SDK for server implementation 54 | - Executes git commands through child processes 55 | - Provides error handling and validation 56 | - Runs on stdio transport 57 | 58 | ## Dependencies 59 | 60 | - @modelcontextprotocol/sdk 61 | - Node.js 62 | - Git (must be installed and accessible) 63 | 64 | ## Usage 65 | 66 | The server runs as an MCP service and can be integrated with any MCP-compatible client. All analysis results are written to specified output files in JSON format. 67 | 68 | ## Contributing and License 69 | 70 | This project is licensed under the Apache License, Version 2.0 - see the [LICENSE.txt](LICENSE.txt) file for details. 71 | 72 | ### Collaboration Welcome 73 | Forks and contributions welcome. 74 | 75 | All contributions will be under the Apache License 2.0. This permissive license allows you to: 76 | - Use the code commercially 77 | - Modify and distribute the code 78 | - Create derivative works 79 | - Include in other projects 80 | 81 | Copyright 2025. Licensed under the Apache License, Version 2.0; you may not use this project except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ``` -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "name": "git-forensics-mcp", 3 | "version": "0.1.0", 4 | "description": "MCP server for deep git repository analysis and investigation, providing insights into branch relationships, merge strategies, and development patterns", 5 | "type": "module", 6 | "main": "build/index.js", 7 | "scripts": { 8 | "build": "tsc && chmod +x build/index.js", 9 | "start": "node build/index.js" 10 | }, 11 | "dependencies": { 12 | "@modelcontextprotocol/sdk": "latest" 13 | }, 14 | "devDependencies": { 15 | "@types/node": "^20.0.0", 16 | "typescript": "^5.0.0" 17 | } 18 | } ``` -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- ```json 1 | { 2 | "compilerOptions": { 3 | "target": "ES2020", 4 | "module": "ES2020", 5 | "moduleResolution": "node", 6 | "esModuleInterop": true, 7 | "strict": true, 8 | "outDir": "build", 9 | "rootDir": "src", 10 | "declaration": true, 11 | "sourceMap": true, 12 | "skipLibCheck": true, 13 | "noImplicitAny": true, 14 | "strictNullChecks": true, 15 | "strictFunctionTypes": true, 16 | "strictPropertyInitialization": true, 17 | "noImplicitThis": true, 18 | "alwaysStrict": true 19 | }, 20 | "include": ["src/**/*"], 21 | "exclude": ["node_modules", "build"] 22 | } ``` -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- ``` 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright davidorex.ai 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. ``` -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- ```typescript 1 | #!/usr/bin/env node 2 | import { Server } from '@modelcontextprotocol/sdk/server/index.js'; 3 | import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; 4 | import { 5 | CallToolRequestSchema, 6 | ErrorCode, 7 | ListToolsRequestSchema, 8 | McpError, 9 | } from '@modelcontextprotocol/sdk/types.js'; 10 | import { execSync } from 'child_process'; 11 | import { writeFileSync } from 'fs'; 12 | import { join } from 'path'; 13 | 14 | interface BranchOverviewArgs { 15 | repoPath: string; 16 | branches: string[]; 17 | outputPath: string; 18 | } 19 | 20 | interface TimePeriodArgs { 21 | repoPath: string; 22 | branches: string[]; 23 | timeRange: { 24 | start: string; 25 | end: string; 26 | }; 27 | outputPath: string; 28 | } 29 | 30 | interface FileChangesArgs { 31 | repoPath: string; 32 | branches: string[]; 33 | files: string[]; 34 | outputPath: string; 35 | } 36 | 37 | interface MergeRecommendationsArgs { 38 | repoPath: string; 39 | branches: string[]; 40 | outputPath: string; 41 | } 42 | 43 | class GitAnalysisServer { 44 | private server: Server; 45 | 46 | constructor() { 47 | this.server = new Server( 48 | { 49 | name: 'git-analysis-server', 50 | version: '0.1.0', 51 | }, 52 | { 53 | capabilities: { 54 | tools: {}, 55 | }, 56 | } 57 | ); 58 | 59 | this.setupToolHandlers(); 60 | 61 | this.server.onerror = (error) => console.error('[MCP Error]', error); 62 | process.on('SIGINT', async () => { 63 | await this.server.close(); 64 | process.exit(0); 65 | }); 66 | } 67 | 68 | private setupToolHandlers() { 69 | this.server.setRequestHandler(ListToolsRequestSchema, async () => ({ 70 | tools: [ 71 | { 72 | name: 'get_branch_overview', 73 | description: 'Get high-level overview of branch states and relationships', 74 | inputSchema: { 75 | type: 'object', 76 | properties: { 77 | repoPath: { 78 | type: 'string', 79 | description: 'Path to git repository', 80 | }, 81 | branches: { 82 | type: 'array', 83 | items: { type: 'string' }, 84 | description: 'Branches to analyze', 85 | }, 86 | outputPath: { 87 | type: 'string', 88 | description: 'Path to write analysis output', 89 | }, 90 | }, 91 | required: ['repoPath', 'branches', 'outputPath'], 92 | }, 93 | }, 94 | { 95 | name: 'analyze_time_period', 96 | description: 'Analyze detailed development activity in a specific time period', 97 | inputSchema: { 98 | type: 'object', 99 | properties: { 100 | repoPath: { 101 | type: 'string', 102 | description: 'Path to git repository', 103 | }, 104 | branches: { 105 | type: 'array', 106 | items: { type: 'string' }, 107 | description: 'Branches to analyze', 108 | }, 109 | timeRange: { 110 | type: 'object', 111 | properties: { 112 | start: { type: 'string' }, 113 | end: { type: 'string' }, 114 | }, 115 | required: ['start', 'end'], 116 | }, 117 | outputPath: { 118 | type: 'string', 119 | description: 'Path to write analysis output', 120 | }, 121 | }, 122 | required: ['repoPath', 'branches', 'timeRange', 'outputPath'], 123 | }, 124 | }, 125 | { 126 | name: 'analyze_file_changes', 127 | description: 'Analyze changes to specific files across branches', 128 | inputSchema: { 129 | type: 'object', 130 | properties: { 131 | repoPath: { 132 | type: 'string', 133 | description: 'Path to git repository', 134 | }, 135 | branches: { 136 | type: 'array', 137 | items: { type: 'string' }, 138 | description: 'Branches to analyze', 139 | }, 140 | files: { 141 | type: 'array', 142 | items: { type: 'string' }, 143 | description: 'Files to analyze', 144 | }, 145 | outputPath: { 146 | type: 'string', 147 | description: 'Path to write analysis output', 148 | }, 149 | }, 150 | required: ['repoPath', 'branches', 'files', 'outputPath'], 151 | }, 152 | }, 153 | { 154 | name: 'get_merge_recommendations', 155 | description: 'Get detailed merge strategy recommendations', 156 | inputSchema: { 157 | type: 'object', 158 | properties: { 159 | repoPath: { 160 | type: 'string', 161 | description: 'Path to git repository', 162 | }, 163 | branches: { 164 | type: 'array', 165 | items: { type: 'string' }, 166 | description: 'Branches to analyze', 167 | }, 168 | outputPath: { 169 | type: 'string', 170 | description: 'Path to write analysis output', 171 | }, 172 | }, 173 | required: ['repoPath', 'branches', 'outputPath'], 174 | }, 175 | }, 176 | ], 177 | })); 178 | 179 | this.server.setRequestHandler(CallToolRequestSchema, async (request) => { 180 | try { 181 | switch (request.params.name) { 182 | case 'get_branch_overview': { 183 | const args = request.params.arguments as BranchOverviewArgs; 184 | if (!args?.repoPath || !args?.branches || !args?.outputPath) { 185 | throw new McpError(ErrorCode.InvalidParams, 'Missing required parameters'); 186 | } 187 | return await this.handleBranchOverview(args); 188 | } 189 | case 'analyze_time_period': { 190 | const args = request.params.arguments as TimePeriodArgs; 191 | if (!args?.repoPath || !args?.branches || !args?.timeRange || !args?.outputPath) { 192 | throw new McpError(ErrorCode.InvalidParams, 'Missing required parameters'); 193 | } 194 | return await this.handleTimePeriodAnalysis(args); 195 | } 196 | case 'analyze_file_changes': { 197 | const args = request.params.arguments as FileChangesArgs; 198 | if (!args?.repoPath || !args?.branches || !args?.files || !args?.outputPath) { 199 | throw new McpError(ErrorCode.InvalidParams, 'Missing required parameters'); 200 | } 201 | return await this.handleFileChangesAnalysis(args); 202 | } 203 | case 'get_merge_recommendations': { 204 | const args = request.params.arguments as MergeRecommendationsArgs; 205 | if (!args?.repoPath || !args?.branches || !args?.outputPath) { 206 | throw new McpError(ErrorCode.InvalidParams, 'Missing required parameters'); 207 | } 208 | return await this.handleMergeRecommendations(args); 209 | } 210 | default: 211 | throw new McpError( 212 | ErrorCode.MethodNotFound, 213 | `Unknown tool: ${request.params.name}` 214 | ); 215 | } 216 | } catch (error) { 217 | return { 218 | content: [ 219 | { 220 | type: 'text', 221 | text: `Git analysis error: ${error instanceof Error ? error.message : String(error)}`, 222 | }, 223 | ], 224 | isError: true, 225 | }; 226 | } 227 | }); 228 | } 229 | 230 | private async handleBranchOverview(args: BranchOverviewArgs) { 231 | const overview = args.branches.map(branch => { 232 | const lastCommit = this.getLastCommit(args.repoPath, branch); 233 | const commitCount = this.getCommitCount(args.repoPath, branch); 234 | const mergeBase = args.branches.map(otherBranch => { 235 | if (otherBranch === branch) return null; 236 | return { 237 | branch: otherBranch, 238 | base: this.getMergeBase(args.repoPath, branch, otherBranch), 239 | }; 240 | }).filter((base): base is NonNullable<typeof base> => base !== null); 241 | 242 | return { 243 | branch, 244 | lastCommit, 245 | commitCount, 246 | mergeBase, 247 | }; 248 | }); 249 | 250 | const analysis = { 251 | overview, 252 | summary: this.generateOverviewSummary(overview), 253 | }; 254 | 255 | writeFileSync(args.outputPath, JSON.stringify(analysis, null, 2)); 256 | 257 | return { 258 | content: [ 259 | { 260 | type: 'text', 261 | text: `Branch analysis written to ${args.outputPath}`, 262 | }, 263 | ], 264 | }; 265 | } 266 | 267 | private async handleTimePeriodAnalysis(args: TimePeriodArgs) { 268 | const analysis = args.branches.map(branch => { 269 | const commits = this.getCommitsInRange(args.repoPath, branch, args.timeRange); 270 | return { 271 | branch, 272 | commits, 273 | activitySummary: this.summarizeActivity(commits), 274 | }; 275 | }); 276 | 277 | const result = { 278 | analysis, 279 | summary: this.generateTimePeriodSummary(analysis), 280 | }; 281 | 282 | writeFileSync(args.outputPath, JSON.stringify(result, null, 2)); 283 | 284 | return { 285 | content: [ 286 | { 287 | type: 'text', 288 | text: `Time period analysis written to ${args.outputPath}`, 289 | }, 290 | ], 291 | }; 292 | } 293 | 294 | private async handleFileChangesAnalysis(args: FileChangesArgs) { 295 | const analysis = args.files.map(file => { 296 | const changes = args.branches.map(branch => ({ 297 | branch, 298 | history: this.getFileHistory(args.repoPath, branch, file), 299 | })); 300 | 301 | return { 302 | file, 303 | changes, 304 | conflicts: this.analyzeConflicts(changes), 305 | }; 306 | }); 307 | 308 | const result = { 309 | analysis, 310 | summary: this.generateFileChangesSummary(analysis), 311 | }; 312 | 313 | writeFileSync(args.outputPath, JSON.stringify(result, null, 2)); 314 | 315 | return { 316 | content: [ 317 | { 318 | type: 'text', 319 | text: `File changes analysis written to ${args.outputPath}`, 320 | }, 321 | ], 322 | }; 323 | } 324 | 325 | private async handleMergeRecommendations(args: MergeRecommendationsArgs) { 326 | const recommendations = { 327 | strategy: this.determineMergeStrategy(args.repoPath, args.branches), 328 | conflictRisks: this.assessConflictRisks(args.repoPath, args.branches), 329 | steps: this.generateMergeSteps(args.repoPath, args.branches), 330 | }; 331 | 332 | writeFileSync(args.outputPath, JSON.stringify(recommendations, null, 2)); 333 | 334 | return { 335 | content: [ 336 | { 337 | type: 'text', 338 | text: `Merge recommendations written to ${args.outputPath}`, 339 | }, 340 | ], 341 | }; 342 | } 343 | 344 | private getLastCommit(repoPath: string, branch: string) { 345 | const output = execSync( 346 | `cd "${repoPath}" && git log -1 --format="%H|%aI|%s" ${branch}`, 347 | { encoding: 'utf8' } 348 | ).trim(); 349 | const [hash, date, message] = output.split('|'); 350 | return { hash, date, message, branch }; 351 | } 352 | 353 | private getCommitCount(repoPath: string, branch: string): number { 354 | return parseInt( 355 | execSync( 356 | `cd "${repoPath}" && git rev-list --count ${branch}`, 357 | { encoding: 'utf8' } 358 | ).trim(), 359 | 10 360 | ); 361 | } 362 | 363 | private getMergeBase(repoPath: string, branch1: string, branch2: string): string { 364 | return execSync( 365 | `cd "${repoPath}" && git merge-base ${branch1} ${branch2}`, 366 | { encoding: 'utf8' } 367 | ).trim(); 368 | } 369 | 370 | private getCommitsInRange( 371 | repoPath: string, 372 | branch: string, 373 | timeRange: { start: string; end: string } 374 | ) { 375 | const output = execSync( 376 | `cd "${repoPath}" && git log --format="%H|%aI|%s" ` + 377 | `--after="${timeRange.start}" --before="${timeRange.end}" ${branch}`, 378 | { encoding: 'utf8' } 379 | ); 380 | 381 | return output.trim().split('\n').filter(Boolean).map(line => { 382 | const [hash, date, message] = line.split('|'); 383 | return { hash, date, message, branch }; 384 | }); 385 | } 386 | 387 | private getFileHistory(repoPath: string, branch: string, file: string) { 388 | const output = execSync( 389 | `cd "${repoPath}" && git log --format="%H|%aI|%s" ${branch} -- ${file}`, 390 | { encoding: 'utf8' } 391 | ); 392 | 393 | return output.trim().split('\n').filter(Boolean).map(line => { 394 | const [hash, date, message] = line.split('|'); 395 | return { hash, date, message, branch }; 396 | }); 397 | } 398 | 399 | private summarizeActivity(commits: Array<{ hash: string; date: string; message: string; branch: string }>) { 400 | return { 401 | totalCommits: commits.length, 402 | firstCommit: commits[commits.length - 1], 403 | lastCommit: commits[0], 404 | commitTypes: this.categorizeCommits(commits), 405 | }; 406 | } 407 | 408 | private categorizeCommits(commits: Array<{ message: string }>) { 409 | const categories = { 410 | feature: 0, 411 | fix: 0, 412 | refactor: 0, 413 | docs: 0, 414 | other: 0, 415 | }; 416 | 417 | commits.forEach(({ message }) => { 418 | if (message.match(/^feat|^add/i)) categories.feature++; 419 | else if (message.match(/^fix|^bug/i)) categories.fix++; 420 | else if (message.match(/^refactor|^style|^chore/i)) categories.refactor++; 421 | else if (message.match(/^docs/i)) categories.docs++; 422 | else categories.other++; 423 | }); 424 | 425 | return categories; 426 | } 427 | 428 | private analyzeConflicts(branchChanges: Array<{ branch: string; history: Array<{ hash: string; date: string; message: string }> }>) { 429 | const overlaps = this.findOverlappingChanges(branchChanges); 430 | return { 431 | riskLevel: this.assessRiskLevel(overlaps), 432 | reasons: this.generateConflictReasons(overlaps), 433 | }; 434 | } 435 | 436 | private findOverlappingChanges(branchChanges: Array<{ branch: string; history: Array<{ date: string }> }>) { 437 | const timeRanges = branchChanges.map(({ branch, history }) => ({ 438 | branch, 439 | start: history[history.length - 1]?.date, 440 | end: history[0]?.date, 441 | })); 442 | 443 | return timeRanges.flatMap((range1, i) => 444 | timeRanges.slice(i + 1).map(range2 => ({ 445 | branches: [range1.branch, range2.branch], 446 | overlaps: this.datesOverlap( 447 | new Date(range1.start), 448 | new Date(range1.end), 449 | new Date(range2.start), 450 | new Date(range2.end) 451 | ), 452 | })) 453 | ).filter(({ overlaps }) => overlaps); 454 | } 455 | 456 | private datesOverlap(start1: Date, end1: Date, start2: Date, end2: Date): boolean { 457 | return start1 <= end2 && start2 <= end1; 458 | } 459 | 460 | private assessRiskLevel(overlaps: Array<{ branches: string[] }>) { 461 | if (overlaps.length === 0) return 'low'; 462 | if (overlaps.length <= 2) return 'medium'; 463 | return 'high'; 464 | } 465 | 466 | private generateConflictReasons(overlaps: Array<{ branches: string[] }>) { 467 | return overlaps.map(({ branches }) => 468 | `Parallel development detected between ${branches.join(' and ')}` 469 | ); 470 | } 471 | 472 | private determineMergeStrategy(repoPath: string, branches: string[]) { 473 | const commitCounts = branches.map(branch => ({ 474 | branch, 475 | count: this.getCommitCount(repoPath, branch), 476 | })); 477 | 478 | const baseChoice = commitCounts.reduce((a, b) => 479 | a.count > b.count ? a : b 480 | ); 481 | 482 | return { 483 | recommendedBase: baseChoice.branch, 484 | approach: 'cherry-pick', 485 | reasoning: [ 486 | `${baseChoice.branch} has the most changes (${baseChoice.count} commits)`, 487 | 'Cherry-pick approach allows for selective integration', 488 | ], 489 | }; 490 | } 491 | 492 | private assessConflictRisks(repoPath: string, branches: string[]) { 493 | const changedFiles = new Map<string, string[]>(); 494 | 495 | branches.forEach(branch => { 496 | const files = execSync( 497 | `cd "${repoPath}" && git diff --name-only $(git merge-base ${branches[0]} ${branch})..${branch}`, 498 | { encoding: 'utf8' } 499 | ) 500 | .trim() 501 | .split('\n') 502 | .filter(Boolean); 503 | 504 | files.forEach(file => { 505 | const current = changedFiles.get(file) || []; 506 | changedFiles.set(file, [...current, branch]); 507 | }); 508 | }); 509 | 510 | const hotspots = Array.from(changedFiles.entries()) 511 | .filter(([_, branches]) => branches.length > 1) 512 | .map(([file]) => file); 513 | 514 | return { 515 | overallRisk: hotspots.length > 5 ? 'high' : hotspots.length > 0 ? 'medium' : 'low', 516 | hotspots, 517 | recommendations: [ 518 | 'Review changes in hotspots first', 519 | 'Consider creating integration tests for modified components', 520 | ], 521 | }; 522 | } 523 | 524 | private generateMergeSteps(repoPath: string, branches: string[]) { 525 | return [ 526 | 'Create backup branches', 527 | 'Create integration branch from recommended base', 528 | 'Cherry-pick non-conflicting changes', 529 | 'Resolve conflicts in hotspots', 530 | 'Run test suite after each significant change', 531 | 'Verify functionality of modified components', 532 | 'Update documentation to reflect changes', 533 | ]; 534 | } 535 | 536 | private generateOverviewSummary(overview: Array<{ branch: string; commitCount: number }>) { 537 | const totalCommits = overview.reduce((sum, { commitCount }) => sum + commitCount, 0); 538 | const avgCommits = totalCommits / overview.length; 539 | 540 | return { 541 | totalBranches: overview.length, 542 | totalCommits, 543 | averageCommitsPerBranch: Math.round(avgCommits), 544 | mostActiveBranch: overview.reduce((a, b) => 545 | a.commitCount > b.commitCount ? a : b 546 | ).branch, 547 | }; 548 | } 549 | 550 | private generateTimePeriodSummary( 551 | analysis: Array<{ 552 | branch: string; 553 | commits: Array<{ message: string }>; 554 | activitySummary: { totalCommits: number }; 555 | }> 556 | ) { 557 | const totalCommits = analysis.reduce( 558 | (sum, { activitySummary }) => sum + activitySummary.totalCommits, 559 | 0 560 | ); 561 | 562 | return { 563 | totalCommits, 564 | branchesWithActivity: analysis.filter( 565 | ({ activitySummary }) => activitySummary.totalCommits > 0 566 | ).length, 567 | mostActiveBy: { 568 | commits: analysis.reduce((a, b) => 569 | a.activitySummary.totalCommits > b.activitySummary.totalCommits ? a : b 570 | ).branch, 571 | }, 572 | }; 573 | } 574 | 575 | private generateFileChangesSummary( 576 | analysis: Array<{ 577 | file: string; 578 | changes: Array<{ branch: string; history: Array<unknown> }>; 579 | conflicts: { riskLevel: string }; 580 | }> 581 | ) { 582 | const riskLevels = analysis.map(({ conflicts }) => conflicts.riskLevel); 583 | 584 | return { 585 | totalFiles: analysis.length, 586 | filesWithConflicts: riskLevels.filter(level => level !== 'low').length, 587 | highRiskFiles: riskLevels.filter(level => level === 'high').length, 588 | recommendedReviewOrder: analysis 589 | .sort((a, b) => this.riskToNumber(b.conflicts.riskLevel) - this.riskToNumber(a.conflicts.riskLevel)) 590 | .map(({ file }) => file), 591 | }; 592 | } 593 | 594 | private riskToNumber(risk: string): number { 595 | switch (risk) { 596 | case 'high': return 3; 597 | case 'medium': return 2; 598 | case 'low': return 1; 599 | default: return 0; 600 | } 601 | } 602 | 603 | async run() { 604 | const transport = new StdioServerTransport(); 605 | await this.server.connect(transport); 606 | console.error('Git Analysis MCP server running on stdio'); 607 | } 608 | } 609 | 610 | const server = new GitAnalysisServer(); 611 | server.run().catch(console.error); ```