### Test Setup Endpoint Example Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Use this cURL command to initialize R2 storage for end-to-end tests. This endpoint is only available in the test environment. ```bash curl -X POST http://localhost:5173/api/setup-r2-for-tests ``` -------------------------------- ### Badge Example URL Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/08-utilities.md Provides an example URL for accessing the badge endpoint, demonstrating how to specify a repository and an optional color. ```bash https://gitmcp.io/badge/microsoft/typescript?color=green ``` -------------------------------- ### R2 Bucket Key Operations Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Examples of checking existence, getting, and putting files in an R2 bucket. ```typescript env.DOCS_BUCKET.head(path) // Check existence env.DOCS_BUCKET.get(path) // Fetch content env.DOCS_BUCKET.put(path, data) // Store file ``` -------------------------------- ### GitHub Integration Example Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/06-github-integration.md Demonstrates common GitHub API interactions including fetching files, getting repository branches, searching for files, and constructing GitHub URLs. Assumes utility functions are imported. ```typescript import { fetchFileFromGitHub, searchGitHubRepo, getRepoBranch, constructGithubUrl, } from "./utils/github"; // Fetch a file const readme = await fetchFileFromGitHub( "microsoft", "typescript", "main", "README.md", env ); // Get default branch const branch = await getRepoBranch("microsoft", "typescript", env); // Search for file const llmsFile = await searchGitHubRepo( "microsoft", "typescript", "llms.txt", branch, env, ctx ); // Construct URL for linking const url = constructGithubUrl( "microsoft", "typescript", branch, llmsFile?.path || "README.md" ); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/idosal/git-mcp/blob/main/README.md Install project dependencies using pnpm. Ensure you have pnpm installed globally. ```bash pnpm install ``` -------------------------------- ### Badge Endpoint URL Examples Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Examples of GET requests to the badge endpoint, showing how to specify owner, repository, and color parameters. These URLs are used to generate SVG badges. ```http GET /badge/microsoft/typescript ``` ```http GET /badge/microsoft/typescript?color=green ``` ```http GET /badge/langchain-ai/langgraph?color=#ff0000 ``` -------------------------------- ### Badge Endpoint Examples Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/08-utilities.md Demonstrates various ways to call the badge endpoint, including specifying different repositories and colors. ```bash GET /badge/microsoft/typescript GET /badge/microsoft/typescript?color=blue GET /badge/langchain-ai/langgraph?color=#00ff00 ``` -------------------------------- ### Start Development Server and MCP Inspector Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md This snippet shows the commands to start the development server and the MCP Inspector in separate terminals. The Inspector requires specific configuration for transport type and URL. ```bash # Terminal 1: Start dev server npm run dev # Terminal 2: Start MCP Inspector npx @modelcontextprotocol/inspector # Inspector: Set Transport Type to SSE # Inspector: Enter URL http://localhost:5173/docs # Inspector: Click Connect ``` -------------------------------- ### GET /* Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Serves the web UI using React Router. This is the main entry point for the client-side application. ```APIDOC ## GET /* ### Description Serves the web UI using React Router. This is the main entry point for the client-side application. ### Method GET ### Endpoint /* ### Purpose Web UI ``` -------------------------------- ### GitHub Pattern Example Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/03-repository-data.md Demonstrates parsing for the `gitmcp.io/{owner}/{repo}` pattern, including localhost variants. ```typescript gitmcp.io/microsoft/playwright → { owner: "microsoft", repo: "playwright", urlType: "github" } ``` -------------------------------- ### Example of robots.txt Parsing Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/07-caching-robots-storage.md Illustrates the expected output format after parsing a sample robots.txt content. ```text User-agent: * Disallow: /admin Disallow: /private Allow: /private/public → [ { userAgent: "*", disallow: ["/admin", "/private"], allow: ["/private/public"] } ] ``` -------------------------------- ### POST /api/setup-r2-for-tests Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Initializes R2 storage for testing purposes. This endpoint is used for test setup and should not be used in production. ```APIDOC ## POST /api/setup-r2-for-tests ### Description Initializes R2 storage for testing purposes. This endpoint is used for test setup and should not be used in production. ### Method POST ### Endpoint /api/setup-r2-for-tests ### Purpose Test initialization ``` -------------------------------- ### GitHub Repository URL Examples Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Examples of GitHub repository URLs in the format `gitmcp.io/{owner}/{repo}`. These URLs are used to access specific repository documentation and code. ```text https://gitmcp.io/microsoft/typescript https://gitmcp.io/facebook/react https://gitmcp.io/langchain-ai/langgraph ``` -------------------------------- ### Test Setup Endpoint Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/README.md An endpoint for setting up R2 storage for testing purposes. This is intended for development environments only. ```APIDOC ## POST /.well-known/oauth-* ### Description This endpoint is used for OAuth metadata and is expected to return a 404 Not Found. ### Method POST ### Endpoint /.well-known/oauth-* ### Response #### Success Response (404) - Not Found ``` -------------------------------- ### KV Namespace Key Operations Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Examples of getting and putting data into a KV namespace. ```typescript env.CACHE_KV.get(key, { type: "json" }) env.CACHE_KV.put(key, value, { expirationTtl }) ``` -------------------------------- ### Subdomain URL Examples Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Examples of URLs using a subdomain pattern `{owner}.gitmcp.io/{repo}`. This pattern maps to GitHub Pages URLs and is used for accessing specific repository content. ```text https://langchain-ai.gitmcp.io/langgraph https://microsoft.gitmcp.io/typescript ``` -------------------------------- ### Test Setup Endpoint Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Initializes R2 storage for end-to-end tests. This endpoint is only available in the test environment. ```APIDOC ## POST /api/setup-r2-for-tests ### Description Initialize R2 storage for E2E tests. This endpoint is intended for development and testing purposes only and will return a 404 in production environments. ### Method POST ### Endpoint /api/setup-r2-for-tests ### Parameters #### Request Body - Empty body ### Response #### Success Response (200) - Test setup completion message ### Request Example ```bash curl -X POST http://localhost:5173/api/setup-r2-for-tests ``` ``` -------------------------------- ### MCP Stream Example Flow Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Illustrates a typical client-server interaction for Model Context Protocol (MCP) communication using Server-Sent Events (SSE). Includes example JSON messages for tool calls and content responses. ```json { "type": "call_tool", "tool": "fetch_microsoft_typescript_documentation", "params": {} } ``` ```json { "type": "content", "content": [ { "type": "text", "text": "# TypeScript Documentation\n..." } ] } ``` -------------------------------- ### Tool Name Length Calculation Example Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/08-utilities.md Illustrates the calculation for tool name length, showing how the server name, tool prefix/suffix, and repository name contribute to the total length and potential shortening. ```text Server: "typescript Docs" (15 chars) Tool prefix: "fetch_" (6 chars) Tool suffix: "_documentation" (14 chars) Remaining for repo: 51 - 15 - 6 - 14 = 16 chars For "my-very-long-repository-name" (28 chars): Too long! Must shorten to fit. Result: "fetch_my_very_long_repository_docs" (34 chars) Total: 15 + 34 = 49 chars ✓ ``` -------------------------------- ### Generate Server Name Examples Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/08-utilities.md Illustrates the usage of the generateServerName function with different repository name inputs, including null and undefined. ```typescript generateServerName("typescript") // → "typescript Docs" generateServerName("react") // → "react Docs" generateServerName(null) // → "MCP Docs" generateServerName(undefined) // → "MCP Docs" ``` -------------------------------- ### Good User-Facing Error Message Example Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/11-error-codes.md This example demonstrates a specific and actionable error message for users, including the URL and the reason for the restriction, adhering to robots.txt policies. ```string "Access to https://example.com/admin/ is disallowed by robots.txt. GitMCP respects robots.txt directives." ``` -------------------------------- ### Run GitMCP Locally for Development Source: https://github.com/idosal/git-mcp/blob/main/README.md Start the GitMCP development server. This command is used for local development and testing. ```bash npm run dev ``` ```bash pnpm dev ``` -------------------------------- ### Badge Markdown Example Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/08-utilities.md Shows how to embed a generated badge into Markdown, linking to the repository's documentation on GitMCP. ```markdown [![GitMCP](https://img.shields.io/endpoint?url=https://gitmcp.io/badge/OWNER/REPO?color=green)](https://gitmcp.io/OWNER/REPO) ``` -------------------------------- ### Subdomain Pattern Example Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/03-repository-data.md Illustrates how a subdomain pattern like `{subdomain}.gitmcp.io/repo` is parsed to extract owner and repo information. ```typescript langchain-ai.gitmcp.io/langgraph → { owner: "langchain-ai", repo: "langgraph", urlType: "subdomain" } ``` -------------------------------- ### Clone and Run Remote MCP Server Locally Source: https://github.com/idosal/git-mcp/blob/main/static/README.md Clone the repository, install dependencies, and run the remote MCP server locally for development. Access it via http://localhost:8787/. ```bash git clone git@github.com:cloudflare/ai.git cd ai npm install npx nx dev remote-mcp-server ``` -------------------------------- ### Cloudflare Worker Configuration (wrangler.toml) Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md An example structure for wrangler.toml, defining build settings, KV namespaces, R2 buckets, queues, and environment-specific routes for development, staging, and production. ```toml name = "git-mcp" type = "service" compatibility_date = "2024-01-01" compatibility_flags = ["nodejs_compat"] # Build [build] command = "npm run build" cwd = "." watch_paths = ["src/**/*.ts"] # KV Namespaces [[kv_namespaces]] binding = "CACHE_KV" id = "cache-namespace-id" preview_id = "cache-preview-id" # R2 Buckets [[r2_buckets]] binding = "DOCS_BUCKET" bucket_name = "git-mcp-docs" # Queues [[queues.producers]] binding = "MY_QUEUE" [[queues.consumers]] queue = "my-queue" max_batch_size = 10 # Environment-specific [env.production] routes = [ { pattern = "gitmcp.io/*" } ] [env.staging] routes = [ { pattern = "staging.gitmcp.io/*" } ] [env.development] routes = [ { pattern = "localhost:*" } ] ``` -------------------------------- ### Queue Documentation Processing Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/11-error-codes.md Logs that background processing for documentation has started by sending a message to a queue if `env.MY_QUEUE` is available. This is expected behavior for initial documentation fetches. ```typescript if (env.MY_QUEUE) { await env.MY_QUEUE.send(JSON.stringify(message)); console.log(`Queued documentation processing for ${owner}/${repo}`, message); } ``` -------------------------------- ### CORS Preflight Request Example Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md This cURL command demonstrates how to make an OPTIONS request to any path to enable cross-origin requests. The response includes CORS headers. ```bash curl -X OPTIONS http://localhost:5173/docs -v ``` -------------------------------- ### Request Context Setup in Fetch Handler Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/02-entry-point.md Sets the request URL on the execution context's props, making it available to the MCP agent during initialization. ```typescript ctx.props.requestUrl = request.url; ``` -------------------------------- ### GET /.well-known/oauth-* Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Serves static 404 responses for OAuth metadata paths. This indicates that OAuth is not supported or configured for these specific paths. ```APIDOC ## GET /.well-known/oauth-* ### Description Serves static 404 responses for OAuth metadata paths. This indicates that OAuth is not supported or configured for these specific paths. ### Method GET ### Endpoint /.well-known/oauth-* ### Purpose OAuth metadata ``` -------------------------------- ### No Results Found Response Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Example of a successful response (200 OK) when no code matches are found for a given query in a specific repository. ```typescript { searchQuery: query, content: [{ type: "text", text: "No code matches found in microsoft/typescript." }] } ``` -------------------------------- ### Missing Environment Binding Error Response Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Example of an error response indicating a missing environment binding. The status is 500 (Internal Server Error) and the message specifies the unavailable binding. ```text Error: DOCS_BUCKET is not available in environment ``` -------------------------------- ### GitHub API Rate Limit Headers Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Example of headers returned by the GitHub API related to rate limiting. These headers provide information about the current rate limit status. ```typescript x-ratelimit-limit: 5000 x-ratelimit-remaining: 4999 x-ratelimit-reset: 1234567890 ``` -------------------------------- ### Analytics WriteDataPoint API Call Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Example of writing a data point to Cloudflare Analytics. ```typescript env.CLOUDFLARE_ANALYTICS.writeDataPoint({ blobs: [url, repoContext]; doubles: [1]; indexes: ["github_api_request"]; }) ``` -------------------------------- ### AI Search API Call Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Example of performing a semantic search using the AutoRAG AI binding. ```typescript env.AI.autorag("docs-rag").search({ query: string; rewrite_query: boolean; max_num_results: number; ranking_options: { score_threshold: number }; filters: object; }) ``` -------------------------------- ### Fetch Documentation Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Fetches documentation for a given repository. It expects an empty schema for parameters and returns file information and content. ```APIDOC ## Fetch Documentation ### Description Fetches documentation for a specified repository. This tool is designed to retrieve file content and metadata. ### Parameters #### Query Parameters - None (empty schema) ### Response #### Success Response (200) - **fileUsed** (string) - The name of the file used for fetching documentation. - **content** (array) - An array of content objects, each with a type and text. - **type** (string) - The type of content, expected to be 'text'. - **text** (string) - The actual documentation content. ### Response Example ```json { "fileUsed": "README.md", "content": [ { "type": "text", "text": "# Example Documentation\nThis is the content of the documentation." } ] } ``` ``` -------------------------------- ### Registering MCP Tools with Server Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/04-mcp-tools.md This TypeScript snippet shows how to import and initialize MCP tools, then register them with a server. Ensure the CloudflareEnvironment is correctly configured. ```typescript import { getMcpTools } from "./api/tools"; const env: CloudflareEnvironment = { /* ... */ }; const tools = getMcpTools(env, "gitmcp.io", "/microsoft/typescript"); // tools array contains: // - fetch_microsoft_typescript_documentation // - search_microsoft_typescript_documentation // - search_microsoft_typescript_code // - fetch_generic_url_content // Register with MCP server for (const tool of tools) { server.tool(tool.name, tool.description, tool.paramsSchema, async (args) => tool.cb(args), tool.annotations); } ``` -------------------------------- ### Fetch Documentation with Caching Strategy Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/00-index.md Fetches documentation, first checking a cache and then fetching fresh data if not found. The fresh data is then stored in the cache. ```typescript const cached = await getCachedFetchDocResult(owner, repo, env); if (cached) return cached; const fresh = await fetchDocumentation({ repoData, env, ctx }); ctx.waitUntil(cacheFetchDocResult(owner, repo, fresh, ttl, env)); return fresh; ``` -------------------------------- ### Development Server and Inspector Commands Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/00-index.md Commands for running the development server, launching the MCP Inspector, and executing end-to-end tests. ```bash # Development server npm run dev # MCP Inspector npx @modelcontextprotocol/inspector # E2E Tests npm run test:e2e ``` -------------------------------- ### Configure Claude Desktop for Local MCP Server Source: https://github.com/idosal/git-mcp/blob/main/static/README.md Integrate your local MCP server with Claude Desktop by updating the configuration file. This allows Claude to communicate with your server via a local proxy. ```json { "mcpServers": { "math": { "command": "npx", "args": ["mcp-remote", "http://localhost:8787/sse"] } } } ``` -------------------------------- ### Web UI Endpoint Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Serves the web interface, typically via GET requests, handling various routes for the application. ```APIDOC ## GET /* ### Description Serves the web interface of the application, typically through GET requests. This endpoint handles various routes, including the home page, repository documentation views, generic documentation interfaces, and embedded chat interfaces. ### Method GET (typically) ### Endpoint /* (all remaining paths) ### Response Format - **Content-Type**: `text/html` - **Body**: HTML with embedded React app ### Purpose Serve the web interface ### Routes Handled - `/` - Home page - `/{owner}/{repo}` - Repository documentation view - `/docs` - Generic documentation interface - `/{owner}/{repo}/chat` - Embedded chat interface ### Integration Receives Cloudflare context via React Router: ```typescript { cloudflare: { env: CloudflareEnvironment; ctx: ExecutionContext; } } ``` ``` -------------------------------- ### Queue Consumer Configuration Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Configure a queue consumer for processing documentation tasks, including batching and retries. ```toml [[queues.consumers]] queue = "my-queue" max_batch_size = 10 max_batch_timeout = 30 max_retries = 3 dead_letter_queue = "my-queue-dlq" ``` -------------------------------- ### GET /badge/{owner}/{repo} Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Generates and returns a badge SVG for a given repository owner and name. This is useful for displaying repository status or metrics. ```APIDOC ## GET /badge/{owner}/{repo} ### Description Generates and returns a badge SVG for a given repository owner and name. This is useful for displaying repository status or metrics. ### Method GET ### Endpoint /badge/{owner}/{repo} ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. ### Purpose Badge SVG ``` -------------------------------- ### R2 Bucket Binding Configuration Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Configure an R2 bucket binding for storing pre-generated documentation in wrangler.toml. ```toml [[r2_buckets]] binding = "DOCS_BUCKET" bucket_name = "..." ``` -------------------------------- ### Literal Types for Method and Type Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/09-types-reference.md Demonstrates the use of literal types for properties like `type` (fixed to 'text') and `method` (restricted to 'GET' or 'POST'). ```typescript type: "text" method: "GET" | "POST" ``` -------------------------------- ### Build Script Configuration Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Defines build and deployment scripts within a package.json file. Includes commands for building the project, deploying to Cloudflare Workers, and running a development server. ```json { "scripts": { "build": "react-router build", "deploy": "npm run build && wrangler deploy", "dev": "react-router dev" } } ``` -------------------------------- ### Fetch Generic Documentation Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Fetches documentation from any repository using the generic dynamic pattern. This allows for dynamic switching between repositories. ```APIDOC ## Fetch Generic Documentation ### Description Fetches documentation from any specified repository using the generic dynamic pattern. This tool enables dynamic switching between different repositories for documentation retrieval. ### Parameters #### Query Parameters - **owner** (string) - Required - The owner of the repository. - **repo** (string) - Required - The name of the repository. - **file** (string) - Optional - The specific file to fetch within the repository. ### Response #### Success Response (200) - **fileUsed** (string) - The name of the file used for fetching documentation. - **content** (array) - An array of content objects, each with a type and text. - **type** (string) - The type of content, expected to be 'text'. - **text** (string) - The actual documentation content. ### Response Example ```json { "fileUsed": "README.md", "content": [ { "type": "text", "text": "# Generic Documentation\nContent from a dynamically specified repository." } ] } ``` ``` -------------------------------- ### Get Cached Robots.txt Rules Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/07-caching-robots-storage.md Retrieves cached robots.txt rules for a given domain from the KV store. Returns an array of RobotsRule objects or null if not found. ```typescript async function getCachedRobotsTxt(domain: string, env: Env): Promise ``` -------------------------------- ### Generate Fetch Tool Description Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/04-mcp-tools.md Generates a dynamic description for documentation fetching tools based on repository details and URL type. ```typescript function generateFetchToolDescription(repoData: Omit): string ``` -------------------------------- ### GitHub API Failure Response Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Example of a response when the GitHub API fails. The tool returns an error message within the 'content' field, detailing the search error. ```typescript { searchQuery: query, content: [{ type: "text", text: "An error occurred while searching code: Error details..." }] } ``` -------------------------------- ### GitMCP Architecture Layers Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/01-overview.md Illustrates the layered architecture of GitMCP, detailing the entry point, API tools, utilities, and shared modules. ```text Entry Point (index.ts) ├── MCP Server (MyMCP class) │ └── Tool Registration ├── Request Router ├── Badge Handler └── CORS/OAuth Handlers API Tools (src/api/tools/) ├── Tool Definitions (commonTools.ts) ├── Repository Handlers (repoHandlers/) │ ├── DefaultRepoHandler │ ├── GenericRepoHandler │ ├── ThreejsRepoHandler │ └── ReactRouterRepoHandler └── Common Operations Utilities (src/api/utils/) ├── GitHub Integration (github.ts, githubClient.ts) ├── Caching (cache.ts) ├── Robots.txt Compliance (robotsTxt.ts) ├── R2 Integration (r2.ts) ├── Vector Store (vectorStore.ts) └── Badge Generation (badge.ts) Shared (src/shared/) ├── Repository Data Parsing (repoData.ts) ├── Name Utilities (nameUtils.ts) └── URL Utilities (urlUtils.ts) ``` -------------------------------- ### List All Subfolders in R2 Bucket Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/07-caching-robots-storage.md Recursively lists all subfolder paths within an R2 bucket starting from a specified prefix. Useful for organizing and accessing hierarchical data. ```typescript async function listAllSubfolders(bucket: R2Bucket, startPrefix: string): Promise ``` ```typescript const prefixes = await listAllSubfolders(bucket, "microsoft/"); // → ["microsoft/typescript/", "microsoft/vscode/", ...] ``` -------------------------------- ### Invalid Repository Error Response Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Example of an error response for an invalid repository. The status is 500 (Internal Server Error) and the body contains details about the invalid repository data. ```text Error: Invalid repository data: { "owner": null, "repo": null, "host": "invalid.com", "urlType": "unknown" } ``` -------------------------------- ### Configure Claude Desktop for GitMCP Source: https://github.com/idosal/git-mcp/blob/main/README.md Replace the existing configuration in Claude Desktop's settings with this JSON to enable gitmcp server integration. ```json { "mcpServers": { "gitmcp": { "command": "npx", "args": [ "mcp-remote", "https://gitmcp.io/{owner}/{repo}" ] } } } ``` -------------------------------- ### MyMCP Class and its Methods Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/02-entry-point.md Details the MyMCP class, which extends McpAgent, and its core methods for server initialization and request handling. It outlines the constructor parameters and the behavior of the init() and fetch() methods. ```APIDOC ## Class: MyMCP ### Description The main MCP server implementation extending `McpAgent`. ### Constructor Initializes the MCP server with a name and version. - **name**: "GitMCP" - **version**: "1.1.0" ### Method: `init()` #### Description Called during MCP initialization to set up tools. It extracts request URL and host, validates them, cleans search parameters, clears the URL hash, parses repository data, and registers MCP tools. #### Behavior 1. Extracts request URL and host from `this.props.requestRequestUrl`. 2. Validates host exists. 3. Cleans search parameters (keeps only `sessionId`). 4. Clears URL hash. 5. Parses repository data via `getRepoData()`. 6. Registers all MCP tools via `getMcpTools()`. #### Error Handling Throws `Error` if request URL or host is missing. #### Side Effects Registers tools on `this.server` using the `tool()` method. ### Method: `fetch(request: Request, env: any, ctx: any): Promise` #### Description The primary request handler for Cloudflare Workers, responsible for routing incoming requests to the appropriate handlers based on path, method, and headers. ``` -------------------------------- ### Get Cached Documentation Fetch Result Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/07-caching-robots-storage.md Retrieves the cached result of a documentation fetch operation for a given repository. Uses a specific cache key format for efficient lookup. ```typescript async function getCachedFetchDocResult( owner: string, repo: string, env: Env, ): Promise ``` -------------------------------- ### Handle No Documentation Found Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/11-error-codes.md Sets content to a default message when no documentation files are found after exhausting all fallback locations. Recovery is not possible; documentation files must be added. ```typescript if (!content) { content = "No documentation found."; return { fileUsed, content: [{ type: "text" as const, text: content, }], }; } ``` -------------------------------- ### Type Mapping: GitHub Integration Input to Output Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/09-types-reference.md Illustrates the input parameters (owner, repo, branch, path) and the output of the `fetchFileFromGitHub` function, which returns a Promise of a string or null. ```typescript // Input owner, repo, branch, path // Processing (fetchFileFromGitHub) ↓ // Output Promise ``` -------------------------------- ### Get Cached Repository File Path Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/07-caching-robots-storage.md Retrieves the cached file path and branch information for a specific file within a repository. Returns null if the file path is not found in the cache. ```typescript async function getCachedFilePath( owner: string, repo: string, filename: string, env: Env, ): Promise<{ path: string; branch: string } | null> ``` -------------------------------- ### Get Default Repository Branch Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/06-github-integration.md Determines the default branch name (e.g., 'main', 'master') for a given GitHub repository. It uses a fallback mechanism if the primary API call fails. ```typescript async function getRepoBranch( owner: string, repo: string, env: CloudflareEnvironment, ): Promise ``` ```typescript const branch = await getRepoBranch("microsoft", "typescript", env); // → "main" ``` -------------------------------- ### Registering a Tool with Server Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/00-index.md Registers a tool with the server, providing its name, description, parameter schema, and a callback function. Optional annotations like title and readOnlyHint can be included. ```typescript server.tool( name, description, paramsSchema, async (args) => callback(args), { annotations: { title, readOnlyHint: true } } ); ``` -------------------------------- ### OPTIONS /* Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Handles CORS preflight requests by setting appropriate CORS headers. This is essential for cross-origin resource sharing. ```APIDOC ## OPTIONS /* ### Description Handles CORS preflight requests by setting appropriate CORS headers. This is essential for cross-origin resource sharing. ### Method OPTIONS ### Endpoint /* ### Purpose CORS headers ``` -------------------------------- ### Get From Cache Gracefully Returns Null Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/11-error-codes.md Retrieves data from cache, returning null on cache miss, expired TTL, or KV errors. The caller should compute fresh values and cache them. ```typescript async function getFromCache(key: string, env: Env): Promise { // Returns null on cache miss } ``` -------------------------------- ### Queue Producer Binding Configuration Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Configure a queue producer binding for asynchronous documentation processing in wrangler.toml. ```toml [[queues.producers]] binding = "MY_QUEUE" ``` -------------------------------- ### Registered Handlers Map Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/05-repo-handlers.md Example of how repository handlers are registered using a map. This allows for custom implementations for specific repositories like Three.js and React Router, as well as a generic handler for documentation endpoints. ```typescript const handlers: RepoHandlerMap = { "all::mrdoob/three.js": getThreejsRepoHandler(), "all::docs/": getGenericRepoHandler(), "all::remix-run/react-router": getReactRouterRepoHandler(), }; ``` -------------------------------- ### Fetch Primary Documentation Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/04-mcp-tools.md Fetches primary documentation from a GitHub repository or GitHub Pages site. Supports caching and respects robots.txt. Queues documentation processing for future generation. ```typescript async function fetchDocumentation({ repoData, env, ctx, }: { repoData: RepoData; env: CloudflareEnvironment; ctx: any; }): Promise ``` -------------------------------- ### fetchDocumentation Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/04-mcp-tools.md Fetches primary documentation from a GitHub repository or GitHub Pages site. It supports caching and respects robots.txt rules. ```APIDOC ## fetchDocumentation() ### Description Fetches primary documentation from a GitHub repository or GitHub Pages site. It supports caching and respects robots.txt rules. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **repoData** (RepoData) - Repository identification - **env** (CloudflareEnvironment) - Environment bindings - **ctx** (any) - Execution context ### Returns `FetchDocumentationResult` with file used and content ### Cache Strategy - **TTL**: 30 minutes - **Key**: `fetch_doc:{owner}:{repo}` - **Behavior**: Returns cached result if available ### Side Effects - Queues documentation processing in `MY_QUEUE` for future generation - Caches result in KV store ### Error Handling Returns generic "No documentation found" message on failure ``` -------------------------------- ### Add Custom SSE URL in Highlight AI for GitMCP Source: https://github.com/idosal/git-mcp/blob/main/README.md Use this SSE URL in Highlight AI's Custom Plugin settings to connect to a gitmcp server. ```text https://gitmcp.io/{owner}/{repo} ``` -------------------------------- ### Configure GitMCP Server in Cursor Source: https://github.com/idosal/git-mcp/blob/main/README.md Add this configuration to your Cursor's mcp.json file to enable GitMCP for a specific repository. Ensure you replace {owner} and {repo} with the actual GitHub owner and repository name. ```json { "mcpServers": { "gitmcp": { "url": "https://gitmcp.io/{owner}/{repo}" } } } ``` -------------------------------- ### Configure Claude Desktop for Deployed MCP Server Source: https://github.com/idosal/git-mcp/blob/main/static/README.md Connect Claude Desktop to your deployed MCP server by updating the configuration file with your Worker's `workers.dev` URL. Restart Claude after updating the configuration. ```json { "mcpServers": { "math": { "command": "npx", "args": ["mcp-remote", "https://worker-name.account-name.workers.dev/sse"] } } } ``` -------------------------------- ### Assets Binding Configuration Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Configure an assets binding for serving static files, such as README.md, in wrangler.toml. ```toml [env.production.routes] pattern = "example.com/assets/*" zone_name = "example.com" [[assets]] file = "path/to/assets" ``` -------------------------------- ### URL String Parsing with getRepoDataFromUrl Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/03-repository-data.md Demonstrates parsing URL strings using getRepoDataFromUrl, showing extraction for both simple owner/repo formats and full URLs. ```typescript import { getRepoDataFromUrl } from "./repoData"; getRepoDataFromUrl("microsoft/typescript") // → { owner: "microsoft", repo: "typescript" } getRepoDataFromUrl("https://github.com/langchain-ai/langgraph") // → { owner: "langchain-ai", repo: "langgraph" } ``` -------------------------------- ### Configure VSCode for GitMCP Source: https://github.com/idosal/git-mcp/blob/main/README.md Add this configuration to your VSCode's .vscode/mcp.json file to integrate gitmcp. ```json { "servers": { "gitmcp": { "type": "sse", "url": "https://gitmcp.io/{owner}/{repo}" } } } ``` -------------------------------- ### Registering Handler Tools with MCP Server Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/05-repo-handlers.md Shows how tools generated by repository handlers are registered with the MCP server. This makes the tools available to AI assistants. ```typescript getMcpTools(env, host, canonicalUrl, ctx).forEach((tool) => { this.server.tool( tool.name, tool.description, tool.paramsSchema, async (args: any) => tool.cb(args), tool.annotations ? { annotations: tool.annotations } : undefined, ); }); ``` -------------------------------- ### Fetch Documentation Parameters Schema Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Defines the parameter schema for fetching documentation, which accepts an empty object or null, indicating no specific parameters are required. ```typescript paramsSchema: z.union([z.object({}), z.null()]) ``` -------------------------------- ### Match Library to Repository Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Matches a given library name to its corresponding owner and repository on GitHub. Returns structured information about the match. ```APIDOC ## Match Library to Repository ### Description Attempts to match a library name to its GitHub owner and repository. This is useful for discovering where a library is hosted. ### Parameters #### Query Parameters - **library** (string) - Required - The name of the library to try and match to an owner/repo. ### Response #### Success Response (200) - **content** (array) - An array containing a single JSON string with match details. - **type** (string) - The type of content, expected to be 'text'. - **text** (string) - A JSON string representing the matched library details. - **library** (string) - The name of the library. - **libraryTitle** (string) - The title or full name of the library. - **owner** (string) - The GitHub owner of the repository. - **repo** (string) - The name of the GitHub repository. ### Response Example ```json { "content": [ { "type": "text", "text": "{\"library\": \"react\", \"libraryTitle\": \"React\", \"owner\": \"facebook\", \"repo\": \"react\"}" } ] } ``` ``` -------------------------------- ### Development URLs Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md These are the base URLs used for local development. The specific paths can be used to access different parts of the application or documentation. ```text http://localhost:5173/ http://localhost:5173/microsoft/typescript http://localhost:5173/docs ``` -------------------------------- ### Fetch File with Robots.txt Check Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/07-caching-robots-storage.md Safely fetches a file after verifying robots.txt directives for the given URL and environment. Returns the content or null if blocked by robots.txt. ```typescript async function fetchFileWithRobotsTxtCheck( url: string, env: Env, ): Promise<{ content: string | null; blockedByRobots: boolean }> ``` ```typescript const result = await fetchFileWithRobotsTxtCheck( "https://example.com/docs/README.md", env ); if (result.blockedByRobots) { console.log("Access denied by robots.txt"); } else { console.log(result.content); } ``` -------------------------------- ### MyMCP init() Method Signature Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/02-entry-point.md Signature for the init method called during MCP initialization to set up tools. It handles request URL extraction, validation, parameter cleaning, and parsing repository data. ```typescript async init(): Promise ``` -------------------------------- ### Configure MCP Inspector for Local Server Source: https://github.com/idosal/git-mcp/blob/main/static/README.md Connect the MCP Inspector to your local MCP server by setting the Transport Type to SSE and providing the server URL. Any email and password can be used for login. ```bash npx @modelcontextprotocol/inspector ``` -------------------------------- ### Generate Fetch Documentation Cache Key Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/07-caching-robots-storage.md Generates a cache key for storing the results of fetching documentation for a repository. This key is associated with a shorter TTL of 30 minutes. ```typescript function getFetchDocCacheKey(owner: string, repo: string): string ``` -------------------------------- ### Web UI Endpoint Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/README.md Serves the Web User Interface for GitMCP. ```APIDOC ## GET /* ### Description Serves the main Web User Interface (UI) for GitMCP. ### Method GET ### Endpoint /* ### Response #### Success Response (200) - (text/html) - The HTML content of the Web UI. ``` -------------------------------- ### Generate Fetch Tool Name Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/04-mcp-tools.md Generates a tool name for documentation fetching, ensuring it adheres to length limits when combined with a server name. ```typescript function generateFetchToolName(repoData: Omit): string ``` -------------------------------- ### Generic Dynamic Pattern URL Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md The generic dynamic URL `https://gitmcp.io/docs` is used for dynamic repository switching and accessing common libraries. ```text https://gitmcp.io/docs ``` -------------------------------- ### fetchUrlContent Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/04-mcp-tools.md Fetches content from any absolute URL while respecting robots.txt rules. It can process HTML content into Markdown. ```APIDOC ## fetchUrlContent() ### Description Fetches content from any absolute URL while respecting robots.txt rules. It can process HTML content into Markdown. ### Parameters #### Path Parameters - **url** (string) - Required - Absolute URL to fetch - **env** (Env) - Required - Environment bindings ### Returns Object with URL, status, and content. ### Status Values - `"success"`: Content fetched successfully - `"blocked"`: robots.txt disallows access - `"not_found"`: Resource doesn't exist or requires auth - `"error"`: Exception during fetch ### Processing Steps 1. Checks robots.txt rules via `fetchFileWithRobotsTxtCheck()`. 2. Returns blocked status if disallowed. 3. Converts HTML to Markdown if applicable. 4. Returns plain content if not HTML. ### Error Handling Returns error status with message on exception. ``` -------------------------------- ### Match Library to Repository Parameters Schema Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Defines the parameter schema for matching a library to its owner and repository, requiring a 'library' string. ```typescript paramsSchema: { library: z.string().describe("The name of the library to try and match to an owner/repo") } ``` -------------------------------- ### App Load Context Interface Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/09-types-reference.md Provides the application load context, including Cloudflare environment and execution context. ```typescript interface AppLoadContext { cloudflare: { env: CloudflareEnvironment; ctx: ExecutionContext; }; } ``` -------------------------------- ### Complete Repository Data Structure Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/09-types-reference.md Extends MinimalRepoData to include the host and the determined URL type. ```typescript type RepoData = MinimalRepoData & { host: string; urlType: UrlType; } ``` -------------------------------- ### Accessing Cloudflare Bindings in Code Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/10-configuration-environment.md Demonstrates how to import and use various Cloudflare bindings (KV, R2, Queue, AI, Analytics) within a TypeScript function. ```typescript import { env } from 'cloudflare:workers' async function myFunction(env: CloudflareEnvironment) { // KV Cache const cached = await env.CACHE_KV.get('key') // R2 Storage const file = await env.DOCS_BUCKET.get('path') // Queue await env.MY_QUEUE.send(JSON.stringify(message)) // AI const result = await env.AI.autorag('docs-rag').search({...}) // Analytics env.CLOUDFLARE_ANALYTICS?.writeDataPoint({...}) } ``` -------------------------------- ### Register Tool with MCP Server Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/12-api-endpoints.md Registers a tool with the MCP server, providing its name, description, parameter schema, callback function, and optional annotations. Ensure the tool's schema and callback are correctly defined. ```typescript this.server.tool( tool.name, tool.description, tool.paramsSchema, async (args: any) => tool.cb(args), tool.annotations ? { annotations: tool.annotations } : undefined ); ``` -------------------------------- ### Common TypeScript Imports for Repository and MCP Tools Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/00-index.md Imports for repository data, MCP tools, handlers, GitHub utilities, caching, robots.txt checks, and naming utilities. ```typescript // Repository Data import { getRepoData, type RepoData, type UrlType } from './shared/repoData' // MCP Tools import { getMcpTools, fetchDocumentation, searchRepositoryDocumentation } from './api/tools' import type { Tool } from './api/tools/repoHandlers/RepoHandler' // Handlers import { getHandlerByRepoData } from './api/tools/repoHandlers/handlers' // GitHub import { fetchFileFromGitHub, getRepoBranch, constructGithubUrl } from './api/utils/github' // Cache import { getFromCache, setInCache, getCachedFetchDocResult } from './api/utils/cache' // Robots.txt import { checkRobotsTxt, fetchFileWithRobotsTxtCheck } from './api/utils/robotsTxt' // Utilities import { generateServerName } from './shared/nameUtils' import { generateBadgeResponse } from './api/utils/badge' ``` -------------------------------- ### Search Repository Documentation Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/04-mcp-tools.md Searches repository documentation using vector search or a naive fallback. It first checks for R2 documentation and then attempts AutoRAG vector search before falling back to a simpler search method. ```typescript async function searchRepositoryDocumentation({ repoData, query, env, ctx, fallbackSearch, }: { repoData: RepoData; query: string; env: CloudflareEnvironment; ctx: any; fallbackSearch?: typeof searchRepositoryDocumentationNaive; }): Promise ``` -------------------------------- ### Basic Repository Extraction with getRepoData Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/03-repository-data.md Extracts repository data including owner, repo, host, and URL type using the getRepoData function. Requires requestHost and requestUrl parameters. ```typescript import { getRepoData, UrlType } from "./repoData"; const repoData = getRepoData({ requestHost: "gitmcp.io", requestUrl: "/microsoft/typescript" }); console.log(repoData); // { // owner: "microsoft", // repo: "typescript", // host: "gitmcp.io", // urlType: "github" // } ``` -------------------------------- ### GenericRepoHandler Initialization Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/05-repo-handlers.md Defines the GenericRepoHandler class and its initialization function. This handler is used for dynamic repository switching, particularly for the gitmcp.io/docs endpoint. ```typescript class GenericRepoHandler implements RepoHandler { name = "generic" } function getGenericRepoHandler(): GenericRepoHandler ``` -------------------------------- ### Fallback Chain for File Retrieval Source: https://github.com/idosal/git-mcp/blob/main/_autodocs/11-error-codes.md This strategy attempts to fetch a file from multiple predefined locations, then falls back to GitHub search, R2 storage, and finally the README file. If all else fails, it returns a 'not found' message. ```typescript // Try llms.txt in multiple locations const possibleLocations = [ "docs/docs/llms.txt", "llms.txt", "docs/llms.txt", ]; for (const location of possibleLocations) { const content = await fetchFileFromGitHub(..., location, ...); if (content) return { content, fileUsed: "llms.txt" }; } // Fallback to GitHub Search const result = await searchGitHubRepo(..., "llms.txt", ...); if (result) return { content: result.content, fileUsed: "llms.txt" }; // Fallback to R2 pre-generated const content = await fetchFileFromR2(..., "llms.txt", ...); if (content) return { content, fileUsed: "llms.txt (generated)" }; // Fallback to README const readme = await searchGitHubRepo(..., "README+path:/", ...); if (readme) return { content: readme.content, fileUsed: "README.md" }; // Final fallback return "No documentation found."; ```