|
| 1 | +"""Main module for the MCP server application.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import logging |
| 7 | +import os |
| 8 | +from typing import Any |
| 9 | + |
| 10 | +from mcp.server.fastmcp import FastMCP |
| 11 | + |
| 12 | +from gitingest.entrypoint import ingest_async |
| 13 | +from gitingest.utils.logging_config import get_logger |
| 14 | + |
| 15 | +# Initialize logger for this module |
| 16 | +logger = get_logger(__name__) |
| 17 | + |
| 18 | +# Create the FastMCP server instance |
| 19 | +mcp = FastMCP("gitingest") |
| 20 | + |
| 21 | +@mcp.tool() |
| 22 | +async def ingest_repository( |
| 23 | + source: str, |
| 24 | + max_file_size: int = 10485760, |
| 25 | + include_patterns: list[str] | None = None, |
| 26 | + exclude_patterns: list[str] | None = None, |
| 27 | + branch: str | None = None, |
| 28 | + include_gitignored: bool = False, |
| 29 | + include_submodules: bool = False, |
| 30 | + token: str | None = None, |
| 31 | +) -> str: |
| 32 | + """Ingest a Git repository or local directory and return a structured digest for LLMs. |
| 33 | + |
| 34 | + Args: |
| 35 | + source: Git repository URL or local directory path |
| 36 | + max_file_size: Maximum file size to process in bytes (default: 10MB) |
| 37 | + include_patterns: Shell-style patterns to include files |
| 38 | + exclude_patterns: Shell-style patterns to exclude files |
| 39 | + branch: Git branch to clone and ingest |
| 40 | + include_gitignored: Include files matched by .gitignore |
| 41 | + include_submodules: Include repository's submodules |
| 42 | + token: GitHub personal access token for private repositories |
| 43 | + """ |
| 44 | + try: |
| 45 | + logger.info("Starting MCP ingestion", extra={"source": source}) |
| 46 | + |
| 47 | + # Convert patterns to sets if provided |
| 48 | + include_patterns_set = set(include_patterns) if include_patterns else None |
| 49 | + exclude_patterns_set = set(exclude_patterns) if exclude_patterns else None |
| 50 | + |
| 51 | + # Call the ingestion function |
| 52 | + summary, tree, content = await ingest_async( |
| 53 | + source=source, |
| 54 | + max_file_size=max_file_size, |
| 55 | + include_patterns=include_patterns_set, |
| 56 | + exclude_patterns=exclude_patterns_set, |
| 57 | + branch=branch, |
| 58 | + include_gitignored=include_gitignored, |
| 59 | + include_submodules=include_submodules, |
| 60 | + token=token, |
| 61 | + output=None # Don't write to file, return content instead |
| 62 | + ) |
| 63 | + |
| 64 | + # Create a structured response |
| 65 | + response_content = f"""# Repository Analysis: {source} |
| 66 | +
|
| 67 | +## Summary |
| 68 | +{summary} |
| 69 | +
|
| 70 | +## File Structure |
| 71 | +``` |
| 72 | +{tree} |
| 73 | +``` |
| 74 | +
|
| 75 | +## Content |
| 76 | +{content} |
| 77 | +
|
| 78 | +--- |
| 79 | +*Generated by Gitingest MCP Server* |
| 80 | +""" |
| 81 | + |
| 82 | + return response_content |
| 83 | + |
| 84 | + except Exception as e: |
| 85 | + logger.error(f"Error during ingestion: {e}", exc_info=True) |
| 86 | + return f"Error ingesting repository: {str(e)}" |
| 87 | + |
| 88 | + |
| 89 | + |
| 90 | +async def start_mcp_server_tcp(host: str = "0.0.0.0", port: int = 8001): |
| 91 | + """Start the MCP server with HTTP transport using SSE.""" |
| 92 | + logger.info(f"Starting Gitingest MCP server with HTTP/SSE transport on {host}:{port}") |
| 93 | + |
| 94 | + import uvicorn |
| 95 | + from fastapi import FastAPI, Request, HTTPException |
| 96 | + from fastapi.responses import StreamingResponse, JSONResponse |
| 97 | + from fastapi.middleware.cors import CORSMiddleware |
| 98 | + import json |
| 99 | + import asyncio |
| 100 | + from typing import AsyncGenerator |
| 101 | + |
| 102 | + tcp_app = FastAPI(title="Gitingest MCP Server", description="MCP server over HTTP/SSE") |
| 103 | + |
| 104 | + # Add CORS middleware for remote access |
| 105 | + tcp_app.add_middleware( |
| 106 | + CORSMiddleware, |
| 107 | + allow_origins=["*"], # In production, specify allowed origins |
| 108 | + allow_credentials=True, |
| 109 | + allow_methods=["*"], |
| 110 | + allow_headers=["*"], |
| 111 | + ) |
| 112 | + |
| 113 | + @tcp_app.get("/health") |
| 114 | + async def health_check(): |
| 115 | + """Health check endpoint.""" |
| 116 | + return {"status": "healthy", "transport": "http", "version": "1.0"} |
| 117 | + |
| 118 | + @tcp_app.post("/message") |
| 119 | + async def handle_message(message: dict): |
| 120 | + """Handle MCP messages via HTTP POST.""" |
| 121 | + try: |
| 122 | + logger.info(f"Received MCP message: {message}") |
| 123 | + |
| 124 | + # Handle different MCP message types |
| 125 | + if message.get("method") == "initialize": |
| 126 | + return JSONResponse({ |
| 127 | + "jsonrpc": "2.0", |
| 128 | + "id": message.get("id"), |
| 129 | + "result": { |
| 130 | + "protocolVersion": "2024-11-05", |
| 131 | + "capabilities": { |
| 132 | + "tools": {} |
| 133 | + }, |
| 134 | + "serverInfo": { |
| 135 | + "name": "gitingest", |
| 136 | + "version": "1.0.0" |
| 137 | + } |
| 138 | + } |
| 139 | + }) |
| 140 | + |
| 141 | + elif message.get("method") == "tools/list": |
| 142 | + return JSONResponse({ |
| 143 | + "jsonrpc": "2.0", |
| 144 | + "id": message.get("id"), |
| 145 | + "result": { |
| 146 | + "tools": [{ |
| 147 | + "name": "ingest_repository", |
| 148 | + "description": "Ingest a Git repository or local directory and return a structured digest for LLMs", |
| 149 | + "inputSchema": { |
| 150 | + "type": "object", |
| 151 | + "properties": { |
| 152 | + "source": { |
| 153 | + "type": "string", |
| 154 | + "description": "Git repository URL or local directory path" |
| 155 | + }, |
| 156 | + "max_file_size": { |
| 157 | + "type": "integer", |
| 158 | + "description": "Maximum file size to process in bytes", |
| 159 | + "default": 10485760 |
| 160 | + } |
| 161 | + }, |
| 162 | + "required": ["source"] |
| 163 | + } |
| 164 | + }] |
| 165 | + } |
| 166 | + }) |
| 167 | + |
| 168 | + elif message.get("method") == "tools/call": |
| 169 | + tool_name = message.get("params", {}).get("name") |
| 170 | + arguments = message.get("params", {}).get("arguments", {}) |
| 171 | + |
| 172 | + if tool_name == "ingest_repository": |
| 173 | + try: |
| 174 | + result = await ingest_repository(**arguments) |
| 175 | + return JSONResponse({ |
| 176 | + "jsonrpc": "2.0", |
| 177 | + "id": message.get("id"), |
| 178 | + "result": { |
| 179 | + "content": [{"type": "text", "text": result}] |
| 180 | + } |
| 181 | + }) |
| 182 | + except Exception as e: |
| 183 | + return JSONResponse({ |
| 184 | + "jsonrpc": "2.0", |
| 185 | + "id": message.get("id"), |
| 186 | + "error": { |
| 187 | + "code": -32603, |
| 188 | + "message": f"Tool execution failed: {str(e)}" |
| 189 | + } |
| 190 | + }) |
| 191 | + |
| 192 | + else: |
| 193 | + return JSONResponse({ |
| 194 | + "jsonrpc": "2.0", |
| 195 | + "id": message.get("id"), |
| 196 | + "error": { |
| 197 | + "code": -32601, |
| 198 | + "message": f"Unknown tool: {tool_name}" |
| 199 | + } |
| 200 | + }) |
| 201 | + |
| 202 | + else: |
| 203 | + return JSONResponse({ |
| 204 | + "jsonrpc": "2.0", |
| 205 | + "id": message.get("id"), |
| 206 | + "error": { |
| 207 | + "code": -32601, |
| 208 | + "message": f"Unknown method: {message.get('method')}" |
| 209 | + } |
| 210 | + }) |
| 211 | + |
| 212 | + except Exception as e: |
| 213 | + logger.error(f"Error handling MCP message: {e}", exc_info=True) |
| 214 | + return JSONResponse({ |
| 215 | + "jsonrpc": "2.0", |
| 216 | + "id": message.get("id") if "message" in locals() else None, |
| 217 | + "error": { |
| 218 | + "code": -32603, |
| 219 | + "message": f"Internal error: {str(e)}" |
| 220 | + } |
| 221 | + }) |
| 222 | + |
| 223 | + # Start the HTTP server |
| 224 | + config = uvicorn.Config( |
| 225 | + tcp_app, |
| 226 | + host=host, |
| 227 | + port=port, |
| 228 | + log_config=None, # Use our logging config |
| 229 | + access_log=False |
| 230 | + ) |
| 231 | + server = uvicorn.Server(config) |
| 232 | + await server.serve() |
0 commit comments