### Example ApplicationConfiguration Instance Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md An example of how to instantiate the ApplicationConfiguration. ```typescript { githubToken: "ghp_...", logLevel: "info", serverName: "github-mcp-server", serverVersion: "0.2.0", apiTimeoutMs: 10000, rateLimiting: { enabled: true, minRemaining: 50, resetBufferMs: 5000 }, maxRetries: 3 } ``` -------------------------------- ### Configuration Quick Start - .env file Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Example .env file for configuring the GitHub MCP Server. ```dotenv GITHUB_TOKEN=ghp_your_personal_access_token LOG_LEVEL=info SERVER_NAME=github-mcp-server ``` -------------------------------- ### Example Responses Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Examples illustrating the structure of responses for different operations like getting a repository, creating a branch, or creating an issue. ```typescript // Get repository response { repository: GitHubRepositoryEntity, requestTimestamp: string } // Create branch response { branch: GitHubBranchEntity, repository: { owner: string; name: string }, creationTimestamp: string } // Create issue response { issue: GitHubIssueEntity, repository: { owner: string; name: string }, creationTimestamp: string } ``` -------------------------------- ### Start the server Source: https://github.com/cyanheads/github-mcp-server/blob/main/README.md Command to start the built server. ```bash node build/index.js ``` -------------------------------- ### Example RateLimitingConfiguration Instance Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md An example of how to instantiate the RateLimitingConfiguration. ```typescript { enabled: true, minRemaining: 50, resetBufferMs: 5000 } ``` -------------------------------- ### Example ApplicationEnvironmentConfiguration Instance Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md An example of how to instantiate the ApplicationEnvironmentConfiguration. ```typescript { githubToken: "ghp_...", logLevel: "info", serverName: "github-mcp-server", serverVersion: "0.2.0", apiTimeoutMs: 10000, rateLimiting: { enabled: true, minRemaining: 50, resetBufferMs: 5000 } } ``` -------------------------------- ### Factory Pattern Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Shows how to use a factory function to get instances of GitHubService and RateLimiter. ```typescript export function getGitHubService(): GitHubService { return GitHubService.getInstance(); } export function getGitHubRateLimiter(): RateLimiter { // Returns rate limiter instance } ``` -------------------------------- ### Getting a Repository Workflow Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Example of how to retrieve repository information using the `getRepositoryByOwnerAndName` function. ```typescript const result = await getRepositoryByOwnerAndName({ owner: "anthropics", repo: "anthropic-sdk-python" }); if (result.resultSuccessful) { console.log(result.resultData.repository.repositoryUrl); } else { console.error(result.resultError.errorMessage); } ``` -------------------------------- ### Timeout Configuration Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Example of how to set the API timeout using an environment variable. ```bash export API_TIMEOUT_MS=30000 # 30 seconds ``` -------------------------------- ### recordInfoEntry() Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Example of logging an informational message with context. ```typescript StructuredLoggingUtility.recordInfoEntry('Successfully created branch', { branch: 'feature/x' }); ``` -------------------------------- ### GitHub Service Usage Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Example of how to get and use the singleton GitHub service for API interactions. ```typescript const service = getGitHubService(); const repo = await service.getRepository({ owner, repo }); const branches = await service.listRepositoryBranches({ owner, repo }); ``` -------------------------------- ### Example .env File Format Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Shows the required format for the .env file, including mandatory and optional variables. ```bash # Required GITHUB_TOKEN=ghp_your_personal_access_token_here # Optional - Logging LOG_LEVEL=info ``` -------------------------------- ### Example Usage of get_repository Tool Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md An example demonstrating how to execute the get_repository tool with owner and repo parameters. ```typescript const result = await tool.execute({ owner: "anthropics", repo: "anthropic-sdk-python" }); ``` -------------------------------- ### Example Usage of list_repositories Tool Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md An example demonstrating how to execute the list_repositories tool with type and sort parameters. ```typescript const result = await tool.execute({ type: "owner", sort: "updated" }); ``` -------------------------------- ### Data Flow Example: Creating a Repository Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Illustrates the step-by-step process of creating a repository, from user tool call to logging success. ```text User Tool Call (create_repository) ↓ Tool.execute() in ToolRegistry ↓ validateOperationInput(createRepositorySchema) // Validation utility ↓ createNewRepository() operation // Feature module ↓ getGitHubService() // Get singleton GitHub service ↓ GitHubService.createRepository() ↓ getGitHubRateLimiter().waitIfNeeded() // Rate limiter ↓ this.octokit.repos.createForAuthenticatedUser() // Octokit API call ↓ getGitHubResponseMapper().mapRepository() // Response mapper ↓ ApplicationErrorHandlingUtility.createSuccessResult() // Wrap in result ↓ StructuredLoggingUtility.recordInfoEntry() // Log success ↓ Return OperationResult ``` -------------------------------- ### Install dependencies Source: https://github.com/cyanheads/github-mcp-server/blob/main/README.md Command to install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Claude Desktop Configuration Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Example JSON configuration for the MCP client (Claude Desktop) to connect to the GitHub MCP Server. ```json { "mcpServers": { "github": { "command": "node", "args": ["/path/to/github-mcp-server/build/index.js"], "env": { "GITHUB_TOKEN": "ghp_your_personal_access_token_here", "LOG_LEVEL": "info", "SERVER_NAME": "github-mcp-server", "SERVER_VERSION": "0.2.0", "API_TIMEOUT_MS": "10000", "RATE_LIMIT_ENABLED": "true", "MIN_RATE_LIMIT_REMAINING": "50", "RATE_LIMIT_RESET_BUFFER_MS": "5000" } } } } ``` -------------------------------- ### Unit Test Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md An example of a unit test for the `getRepository` function. ```typescript describe('getRepository', () => { it('should return repository data', async () => { const result = await getRepositoryByOwnerAndName({ owner: 'test', repo: 'repo' }); expect(result.resultSuccessful).toBe(true); }); }); ``` -------------------------------- ### recordWarnEntry() Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Example of logging a warning message with context. ```typescript StructuredLoggingUtility.recordWarnEntry('Using fallback value', { value: 50 }); ``` -------------------------------- ### Example Usage for update_file (Text File) Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Example of creating or updating a text file. ```typescript const result = await tool.execute({ owner: "anthropics", repo: "anthropic-sdk-python", path: "README.md", message: "docs: Update installation instructions", content: "# My Project\n\nInstallation: `pip install ...`" }); ``` -------------------------------- ### Example Usage of getApplicationConfiguration Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Demonstrates how to use the getApplicationConfiguration function to access configuration values. ```typescript const config = getApplicationConfiguration(); console.log(config.githubToken); // GitHub token console.log(config.logLevel); // Current log level console.log(config.maxRetries); // Retry attempts ``` -------------------------------- ### Example Usage of resetApplicationConfiguration Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Demonstrates resetting the configuration, which forces a reload on the next call. ```typescript resetApplicationConfiguration(); const config = getApplicationConfiguration(); // Reloads from env ``` -------------------------------- ### Example Usage of loadEnvironmentConfiguration Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Demonstrates calling the loadEnvironmentConfiguration function. ```typescript const envConfig = loadEnvironmentConfiguration(); ``` -------------------------------- ### recordErrorEntry() Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Example of logging an error message with context. ```typescript StructuredLoggingUtility.recordErrorEntry('Failed to retrieve repository', { error: 'Not found' }); ``` -------------------------------- ### Example Usage for update_pull_request Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Example of how to use the update_pull_request tool. ```typescript const result = await tool.execute({ owner: "anthropics", repo: "anthropic-sdk-python", pull_number: 42, title: "feat: Updated title", state: "closed" }); ``` -------------------------------- ### recordDebugEntry() Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Example of logging a debug message with context. ```typescript StructuredLoggingUtility.recordDebugEntry('Validating input', { owner: 'anthropics' }); ``` -------------------------------- ### Safe Concurrent Operations Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Demonstrates how to safely run multiple tools concurrently using Promise.all. ```typescript // Multiple tools can run concurrently const [result1, result2] = await Promise.all([ tool1.execute(params1), tool2.execute(params2) ]); ``` -------------------------------- ### Example Usage for update_file (Update Existing File) Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Example of updating an existing file using its SHA. ```typescript const result = await tool.execute({ owner: "anthropics", repo: "anthropic-sdk-python", path: "src/config.py", message: "fix: Update configuration", content: "CONFIG_VALUE = 42", sha: "abc123def456" // Current SHA from previous read }); ``` -------------------------------- ### Repository Pattern Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Demonstrates the use of GitHubService as a repository for abstracting GitHub API calls. ```typescript const repo = await githubService.getRepository({ owner, repo }); const branches = await githubService.listRepositoryBranches({ owner, repo }); ``` -------------------------------- ### Integration Test Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md An example of an integration test demonstrating tool execution. ```typescript describe('Tool execution', () => { it('should execute get_repository tool', async () => { const registry = new ToolRegistry(); const tool = registry.findTool('get_repository'); const result = await tool.execute({ owner: 'anthropics', repo: 'sdk-python' }); expect(result.content).toBeDefined(); }); }); ``` -------------------------------- ### Concurrency Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Demonstrates how the server handles concurrent tool executions using `Promise.all`. ```typescript const [r1, r2, r3] = await Promise.all([ tool1.execute(params1), tool2.execute(params2), tool3.execute(params3) ]); ``` -------------------------------- ### Example Log Output Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/errors.md An example of structured log output for an error encountered during repository retrieval. ```log [ERROR] 2024-01-01T12:00:00.000Z - Failed to retrieve repository owner: "anthropics" repo: "nonexistent" error: "GitHub API returned 404: Not Found" ``` -------------------------------- ### Environment variables configuration Source: https://github.com/cyanheads/github-mcp-server/blob/main/README.md Example of a .env file for configuring the server with GitHub token and logging level. ```dotenv GITHUB_TOKEN=your_github_personal_access_token LOG_LEVEL=info SERVER_NAME=github-mcp-server ``` -------------------------------- ### Example - createStandardizedError() Usage Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/errors.md An example demonstrating how to use the createStandardizedError method. ```typescript const error = ApplicationErrorHandlingUtility.createStandardizedError( 'Invalid repository name', 'VALIDATION_ERROR', ErrorCategoryType.CATEGORY_VALIDATION, ErrorSeverityLevel.SEVERITY_WARN, { field: 'name', value: '' } ); ``` -------------------------------- ### Concurrent Requests Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Demonstrates how Node.js async/await and Promise.all can be used to handle multiple tool executions concurrently. ```typescript // Multiple tools can execute concurrently const [result1, result2, result3] = await Promise.all([ toolA.execute(params1), toolB.execute(params2), toolC.execute(params3) ]); ``` -------------------------------- ### MCP Client Configuration Source: https://github.com/cyanheads/github-mcp-server/blob/main/README.md Example JSON configuration for an MCP client to connect to the GitHub MCP Server. ```json { "mcpServers": { "github": { "command": "node", "args": ["/path/to/github-mcp-server/build/index.js"], "env": { "GITHUB_TOKEN": "your_github_personal_access_token", "LOG_LEVEL": "info", "SERVER_NAME": "github-mcp-server" } } } } ``` -------------------------------- ### Example - wrapExceptionAsStandardizedError() Usage Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/errors.md An example showing how to catch an exception and convert it into a standardized error. ```typescript try { await someAsyncOperation(); } catch (error) { const standardized = ApplicationErrorHandlingUtility.wrapExceptionAsStandardizedError( error, 'Failed to complete operation' ); return ApplicationErrorHandlingUtility.createFailureResult(standardized); } ``` -------------------------------- ### Strategy Pattern Example for Tool Instantiation Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Illustrates the Strategy pattern applied to input validation, showing how a Tool can use different validation schemas. ```typescript // Tool can use any validation schema new Tool(name, description, inputSchema, operation, zodSchema) ``` -------------------------------- ### Example - Unexpected Error Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/errors.md An example of a standardized unexpected error object structure. ```typescript { errorCode: 'UNEXPECTED_ERROR', errorCategory: ErrorCategoryType.CATEGORY_SYSTEM, errorSeverity: ErrorSeverityLevel.SEVERITY_ERROR, errorMessage: 'Unexpected internal error', errorStack: '...', errorContext: { originalError: { /* exception object */ } } } ``` -------------------------------- ### Singleton Pattern Implementation for GitHubService Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Example implementation of the Singleton pattern for the GitHubService, ensuring a single instance is shared across the application. ```typescript class GitHubService { private static instance: GitHubService; static getInstance(): GitHubService { if (!GitHubService.instance) { GitHubService.instance = new GitHubService(); } return GitHubService.instance; } } ``` -------------------------------- ### Zod Schema Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md An example of a Zod schema used for runtime validation of input data, specifically for creating a repository. ```typescript createRepositorySchema = z.object({ name: z.string().min(1, "Repository name is required"), description: z.string().optional(), private: z.boolean().optional() }); ``` -------------------------------- ### Error Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md An example of a standardized error object returned by operations. ```json { errorMessage: "Repository not found", errorCode: "GITHUB_API_ERROR", errorCategory: "GITHUB_API", errorSeverity: "ERROR", errorTimestamp: "2024-01-01T12:00:00.000Z", errorContext: { owner: "anthropics", repo: "nonexistent", status: 404 } } ``` -------------------------------- ### Custom Error Handler Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Provides an example of creating a domain-specific error using the `ApplicationErrorHandlingUtility`. ```typescript // Create domain-specific error in feature const error = ApplicationErrorHandlingUtility.createStandardizedError( 'Custom message', 'CUSTOM_CODE', ErrorCategoryType.CATEGORY_GITHUB_API, ErrorSeverityLevel.SEVERITY_ERROR, { customContext: true } ); ``` -------------------------------- ### Strategy Pattern Example for Response Mapping Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Illustrates the Strategy pattern applied to response mapping, showing how to adapt different API versions. ```typescript // Response mapper can adapt different API versions getGitHubResponseMapper().mapRepository(apiResponse) ``` -------------------------------- ### Example Invalid Token Error Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/errors.md An example of a standardized error object for an invalid authentication token. ```typescript { errorCode: 'AUTH_TOKEN_INVALID', errorCategory: ErrorCategoryType.CATEGORY_AUTHENTICATION, errorSeverity: ErrorSeverityLevel.SEVERITY_FATAL, errorMessage: 'GITHUB_TOKEN appears to be invalid, check format and permissions', errorContext: { tokenLength: 32, tokenPrefix: 'xxxx', hint: 'GitHub tokens should follow specific format patterns' } } ``` -------------------------------- ### Integration Test Pattern Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Shows an example of an integration test for the `create_pull_request` tool. ```typescript describe('create_pull_request tool', () => { it('should create a pull request', async () => { const tool = registry.findTool('create_pull_request'); const result = await tool.execute({ owner: 'anthropics', repo: 'sdk-python', title: 'Test PR', head: 'feature/test', base: 'main' }); expect(result.isError).toBeFalsy(); expect(result.content[0].text).toContain('pullRequest'); }); }); ``` -------------------------------- ### Decorator Pattern Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Illustrates how decorators can be applied to wrap operations for logging, validation, and serialization. ```typescript // Decorators applied: validateInput(schema) → executeOperation() → serializeOutput() → logResult() ``` -------------------------------- ### Validation Schema Example Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Defines Zod schemas for validating input parameters for creating a repository and a branch. ```typescript createRepositorySchema ├── name: string (min 1 char) ├── description: string (optional) └── private: boolean (optional, default: false) createBranchSchema ├── owner: string (required) ├── repo: string (required) ├── branch: string (required) └── sha: string (required, 40-char commit hash) ``` -------------------------------- ### Operation Result Example Pattern Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/types.md Demonstrates how to handle the OperationResult type, checking for success or failure to access the appropriate data. ```typescript const result = await operation(params); if (result.resultSuccessful) { // Access result.resultData console.log(result.resultData); } else { // Access result.resultError console.log(result.resultError.errorMessage); } ``` -------------------------------- ### Example Validation Error Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/errors.md An example of a standardized error object for a validation failure. ```typescript { errorCode: 'VALIDATION_ERROR', errorCategory: ErrorCategoryType.CATEGORY_VALIDATION, errorSeverity: ErrorSeverityLevel.SEVERITY_WARN, errorMessage: 'Input validation failed', errorContext: { validationErrors: [ { path: 'owner', message: 'Owner is required' } ] } } ``` -------------------------------- ### Build the project Source: https://github.com/cyanheads/github-mcp-server/blob/main/README.md Command to build the project using npm. ```bash npm run build ``` -------------------------------- ### createOctokitClient() Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Creates Octokit instance with GitHub token and request timeout from configuration. ```typescript private createOctokitClient(): Octokit { return new Octokit({ auth: this._config.githubToken, request: { timeout: this._config.apiTimeoutMs } }); } ``` -------------------------------- ### Creating a Branch Workflow Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Demonstrates the process of creating a new branch for a repository. ```typescript const result = await createRepositoryBranch({ owner: "anthropics", repo: "anthropic-sdk-python", branch: "feature/new-feature", sha: "abc123def456" }); if (result.resultSuccessful) { console.log(`Created branch: ${result.resultData.branch.name}`); } ``` -------------------------------- ### Validation Error Format Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Example of the standardized format for validation errors. ```typescript { errorCode: 'VALIDATION_ERROR', errorCategory: 'VALIDATION', errorMessage: 'Input validation failed', errorContext: { validationErrors: [ { path: 'owner', message: 'Owner is required' }, { path: 'repo', message: 'Repository name is required' } ] } } ``` -------------------------------- ### Create Repository Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Creates a new GitHub repository under the authenticated user's account. ```typescript createNewRepository( params: CreateRepositoryParams ): Promise> ``` ```json { "type": "object", "properties": { "name": { "type": "string", "description": "Repository name" }, "description": { "type": "string", "description": "Repository description" }, "private": { "type": "boolean", "default": false } }, "required": ["name"] } ``` ```typescript const result = await tool.execute({ name: "my-new-project", description: "A new project", private: false }); ``` -------------------------------- ### Architecture Overview Diagram Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Diagram illustrating the architecture of the GitHub MCP Server. ```text MCP Clients ↓ Application Entry (src/application.entry.ts) ↓ Tool Registry (src/dependencyInjection/tool.registry.ts) ↓ Feature Modules (src/features/) — 6 domains ↓ GitHub Service (src/services/githubAccess/) ├→ Octokit Client ├→ Rate Limiter ├→ Response Mapper └→ Configuration Manager ↓ GitHub REST API ``` -------------------------------- ### Clone the repository Source: https://github.com/cyanheads/github-mcp-server/blob/main/README.md Command to clone the github-mcp-server repository. ```bash git clone https://github.com/cyanheads/github-mcp-server.git cd github-mcp-server ``` -------------------------------- ### getEnvVariable() function Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md TypeScript function to get a configuration environment variable with defaults. Throws if required but missing. ```typescript function getEnvVariable( key: ConfigKey, required: boolean, defaultValue?: string ): string ``` -------------------------------- ### create_release Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Creates a new GitHub release. ```typescript createRepositoryRelease( params: CreateReleaseParams ): Promise> ``` ```json { "type": "object", "properties": { "owner": { "type": "string" }, "repo": { "type": "string" }, "tag_name": { "type": "string" }, "name": { "type": "string" }, "body": { "type": "string" }, "draft": { "type": "boolean" }, "prerelease": { "type": "boolean" } }, "required": ["owner", "repo", "tag_name"] } ``` ```typescript const result = await tool.execute({ owner: "anthropics", repo: "anthropic-sdk-python", tag_name: "v1.0.0", name: "Version 1.0.0", body: "Initial release with full API support", draft: false, prerelease: false }); ``` -------------------------------- ### createGithubApiError() Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Creates a GitHub API error with `CATEGORY_GITHUB_API`. ```typescript static createGithubApiError( message: string, context?: Record ): StandardizedApplicationErrorObject ``` -------------------------------- ### GitHubServer Class Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Illustrates the key components and methods of the GitHubServer class in the Application Entry Layer. ```typescript class GitHubServer { private server: Server; // MCP Server instance private toolRegistry: ToolRegistry; // Tool registration setupRequestHandlers() // Sets up ListTools and CallTool handlers determineErrorCategory() // Categorizes errors for logging run() // Starts stdio transport } ``` -------------------------------- ### Project Overview Table Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Key properties and values for the github-mcp-server project. ```markdown | Property | Value | |----------|-------| | **Name** | github-mcp-server | | **Version** | 1.0.2 | | **License** | Apache 2.0 | | **Status** | Deprecated (use official GitHub MCP server) | | **Language** | TypeScript 5.8 | | **Runtime** | Node.js 16+ | | **Protocol** | Model Context Protocol 1.7.0 | ``` -------------------------------- ### getNonConfigEnvVariable() function Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md TypeScript function to get any environment variable with special validation for sensitive variables like GITHUB_TOKEN. ```typescript function getNonConfigEnvVariable( key: string, required: boolean, defaultValue?: string ): string ``` -------------------------------- ### Development Scripts Source: https://github.com/cyanheads/github-mcp-server/blob/main/README.md Common npm scripts for building, watching, inspecting, cleaning, and rebuilding the project. ```bash npm run build npm run watch npm run inspector npm run clean npm run rebuild npm run tree ``` -------------------------------- ### refreshConfiguration() Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Allows manual configuration refresh if needed (e.g., token renewal). ```typescript public refreshConfiguration(): void { this._config = getApplicationConfiguration(); this._octokit = this.createOctokitClient(); this.lastConfigRefresh = Date.now(); } ``` -------------------------------- ### Contributing Workflow Source: https://github.com/cyanheads/github-mcp-server/blob/main/README.md Steps for contributing to the project, including forking, branching, committing, and opening a Pull Request. ```bash git checkout -b feature/amazing-feature git commit -m 'Add some amazing feature' git push origin feature/amazing-feature ``` -------------------------------- ### getToolDefinitions Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Returns definitions of all registered tools suitable for MCP tool listing. ```typescript getToolDefinitions(): Array<{ name: string; description: string; inputSchema: any }> ``` ```typescript const registry = new ToolRegistry(); const allTools = registry.getToolDefinitions(); const tool = registry.findTool('get_repository'); ``` -------------------------------- ### getApplicationConfiguration Function Signature Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Signature for the function that retrieves the application configuration. ```typescript function getApplicationConfiguration(): ApplicationConfiguration ``` -------------------------------- ### GitHub Token Validation Logic Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md This TypeScript function validates the format of GitHub tokens, including Personal Access Tokens, OAuth Tokens, App Installation Tokens, and Classic Tokens. ```typescript function validateGitHubToken(token: string): boolean { const validPrefixes = ['ghp_', 'gho_', 'ghs_', 'ghu_']; const hasValidPrefix = validPrefixes.some(prefix => token.startsWith(prefix)); const isValidLength = token.length >= 36; const couldBeClassicToken = /^[a-f0-9]{40}$/i.test(token); return (hasValidPrefix && isValidLength) || couldBeClassicToken; } ``` -------------------------------- ### Configuration Refresh Interval Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md The service automatically refreshes configuration every 15 minutes. ```typescript private static readonly CONFIG_REFRESH_INTERVAL_MS = 15 * 60 * 1000; ``` -------------------------------- ### resetApplicationConfiguration Function Signature Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Signature for the function that resets the application configuration singleton. ```typescript function resetApplicationConfiguration(): void ``` -------------------------------- ### Project Directory Structure Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Provides a comprehensive overview of the project's directory structure, including source code, build artifacts, and configuration files. ```tree github-mcp-server/ ├── src/ │ ├── application.entry.ts │ ├── configuration/ │ ├── dependencyInjection/ │ ├── features/ │ │ ├── branchManagement/ │ │ ├── fileManagement/ │ │ ├── issueManagement/ │ │ ├── pullRequestManagement/ │ │ ├── releaseManagement/ │ │ └── repositoryManagement/ │ ├── services/githubAccess/ │ ├── types/ │ └── utilities/ ├── build/ # Compiled JavaScript ├── package.json ├── tsconfig.json ├── .env # Environment variables └── README.md ``` -------------------------------- ### Key Export Points - Services Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Exports for GitHub related services. ```javascript export { GitHubService, getGitHubService } export { getGitHubRateLimiter } export { getGitHubResponseMapper } ``` -------------------------------- ### Key Export Points - Configuration Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Exports related to application configuration. ```typescript export { getApplicationConfiguration, resetApplicationConfiguration } export type { ApplicationConfiguration, ApplicationEnvironmentConfiguration } export { loadEnvironmentConfiguration } ``` -------------------------------- ### GitHubService Class Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Singleton service that encapsulates all GitHub API interactions. ```typescript class GitHubService implements GitHubServiceInterface { private static instance: GitHubService; private _octokit: Octokit; private mapper = getGitHubResponseMapper(); private rateLimiter = getGitHubRateLimiter(); private _config = getApplicationConfiguration(); private lastConfigRefresh: number = Date.now(); } ``` -------------------------------- ### Creating and Merging a Pull Request Workflow Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Illustrates the steps for creating a pull request and then merging it. ```typescript // Create PR const createResult = await createRepositoryPullRequest({ owner: "anthropics", repo: "anthropic-sdk-python", title: "feat: New feature", head: "feature/new-feature", base: "main" }); if (createResult.resultSuccessful) { const prNumber = createResult.resultData.pullRequest.number; // Merge PR const mergeResult = await mergeRepositoryPullRequest({ owner: "anthropics", repo: "anthropic-sdk-python", pull_number: prNumber, merge_method: "squash" }); } ``` -------------------------------- ### ApplicationConfiguration Interface Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Defines the complete application configuration, extending environment configuration. ```typescript interface ApplicationConfiguration extends ApplicationEnvironmentConfiguration { maxRetries: number; } ``` -------------------------------- ### StructuredLoggingUtility Class Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Provides structured logging with severity levels and context. ```typescript class StructuredLoggingUtility { static recordDebugEntry(message: string, context?: Record): void static recordInfoEntry(message: string, context?: Record): void static recordWarnEntry(message: string, context?: Record): void static recordErrorEntry(message: string, context?: Record): void static recordFatalEntry(message: string, context?: Record): void } ``` -------------------------------- ### Project Directory Structure Source: https://github.com/cyanheads/github-mcp-server/blob/main/docs/tree.md This is the directory structure of the github-mcp-server project, showing the organization of source files, scripts, and configuration. ```tree github-mcp-server ├── docs └── tree.md ├── logs ├── scripts ├── clean.ts └── tree.ts ├── src ├── configuration │ ├── application.config.ts │ ├── configuration.types.ts │ ├── environment.config.ts │ └── index.export.ts ├── dependencyInjection │ └── tool.registry.ts ├── features │ ├── branchManagement │ │ ├── modifications │ │ │ ├── createBranch │ │ │ │ ├── create.branch.operation.ts │ │ │ │ ├── create.branch.types.ts │ │ │ │ └── index.export.ts │ │ │ ├── deleteBranch │ │ │ │ ├── delete.branch.operation.ts │ │ │ │ ├── delete.branch.types.ts │ │ │ │ └── index.export.ts │ │ │ └── index.export.ts │ │ ├── resources │ │ │ ├── listBranches │ │ │ │ ├── index.export.ts │ │ │ │ ├── list.branches.operation.ts │ │ │ │ └── list.branches.types.ts │ │ │ └── index.export.ts │ │ └── index.export.ts │ ├── fileManagement │ │ ├── modifications │ │ │ ├── updateFile │ │ │ │ ├── index.export.ts │ │ │ │ ├── update.file.operation.ts │ │ │ │ └── update.file.types.ts │ │ │ └── index.export.ts │ │ └── index.export.ts │ ├── issueManagement │ │ ├── modifications │ │ │ ├── createIssue │ │ │ │ ├── create.issue.operation.ts │ │ │ │ ├── create.issue.types.ts │ │ │ │ └── index.export.ts │ │ │ └── index.export.ts │ │ ├── resources │ │ │ ├── listIssues │ │ │ │ ├── index.export.ts │ │ │ │ ├── list.issues.operation.ts │ │ │ │ └── list.issues.types.ts │ │ │ └── index.export.ts │ │ └── index.export.ts │ ├── pullRequestManagement │ │ ├── modifications │ │ │ ├── createPullRequest │ │ │ │ ├── create.pull.request.operation.ts │ │ │ │ ├── create.pull.request.types.ts │ │ │ │ └── index.export.ts │ │ │ ├── mergePullRequest │ │ │ │ ├── index.export.ts │ │ │ │ ├── merge.pull.request.operation.ts │ │ │ │ └── merge.pull.request.types.ts │ │ │ ├── updatePullRequest │ │ │ │ ├── index.export.ts │ │ │ │ ├── update.pull.request.operation.ts │ │ │ │ └── update.pull.request.types.ts │ │ │ └── index.export.ts │ │ ├── resources │ │ │ ├── listPullRequests │ │ │ │ ├── index.export.ts │ │ │ │ ├── list.pull.requests.operation.ts │ │ │ │ └── list.pull.requests.types.ts │ │ │ └── index.export.ts │ │ └── index.export.ts │ ├── releaseManagement │ │ ├── modifications │ │ │ ├── createRelease │ │ │ │ ├── create.release.operation.ts │ │ │ │ ├── create.release.types.ts │ │ │ │ └── index.export.ts │ │ │ └── index.export.ts │ │ └── index.export.ts │ ├── repositoryManagement │ │ ├── modifications │ │ │ └── createRepository │ │ │ │ ├── create.repository.operation.ts │ │ │ │ ├── create.repository.types.ts │ │ │ │ └── index.export.ts │ │ ├── resources │ │ │ ├── getRepository │ │ │ │ ├── get.repository.operation.ts │ │ │ │ ├── get.repository.types.ts │ │ │ │ └── index.export.ts │ │ │ └── listRepositories │ │ │ │ ├── index.export.ts │ │ │ │ ├── list.repositories.operation.ts │ │ │ │ └── list.repositories.types.ts │ │ └── index.export.ts │ └── index.export.ts ├── services │ └── githubAccess │ │ ├── github.api.types.ts │ │ ├── github.rate.limiter.ts │ │ ├── github.response.mapper.ts │ │ ├── github.service.ts │ │ ├── github.service.types.ts │ │ └── index.export.ts ├── types │ ├── entity.definition.types.ts │ ├── error.definition.types.ts │ └── operation.result.types.ts ├── utilities │ ├── error.handling.utility.ts │ ├── logger.utility.ts │ ├── promise.utility.ts │ ├── structured.logging.utility.ts │ ├── type.casting.utility.ts │ └── validation.utility.ts ├── application.entry.ts ├── index.ts └── types.ts ├── .env.example ├── LICENSE ├── package-lock.json ├── package.json ├── README.md └── tsconfig.json ``` -------------------------------- ### createRepositorySchema Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/types.md Zod schema for validating input to the create_repository tool, allowing optional description and private flag. ```typescript const createRepositorySchema = z.object({ name: z.string().min(1, "Repository name is required"), description: z.string().optional(), private: z.boolean().optional() }); ``` -------------------------------- ### Create Repository Issue Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Creates a new issue in a repository with optional labels. ```typescript createRepositoryIssue( params: CreateIssueParams ): Promise> ``` ```json { "type": "object", "properties": { "owner": { "type": "string" }, "repo": { "type": "string" }, "title": { "type": "string" }, "body": { "type": "string" }, "labels": { "type": "array", "items": { "type": "string" } } }, "required": ["owner", "repo", "title"] } ``` ```typescript interface CreateIssueResponseType { issue: GitHubIssueEntity; repository: { owner: string; name: string }; creationTimestamp: string; } ``` ```typescript const result = await tool.execute({ owner: "anthropics", repo: "anthropic-sdk-python", title: "Bug: TypeError in message handling", body: "When calling client.messages.create(), a TypeError occurs...", labels: ["bug", "critical"] }); ``` -------------------------------- ### RateLimitingConfiguration Interface Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Defines the structure for rate limiting configuration. ```typescript interface RateLimitingConfiguration { enabled: boolean; minRemaining: number; resetBufferMs: number; } ``` -------------------------------- ### Error Creation Hierarchy Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Illustrates the flow for creating standardized errors based on the type of exception caught. ```text Try operation ↓ [Catches exception] ↓ Is it a Zod validation error? Yes → createValidationError() No → Continue ↓ Is it from GitHub API? Yes → createGithubApiError() No → Continue ↓ Is it an authentication issue? Yes → createAuthenticationError() No → Continue ↓ wrapExceptionAsStandardizedError() ↓ createFailureResult(error) ↓ logError() ↓ Return to MCP client ``` -------------------------------- ### Feature Module Layer Directory Structure Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Illustrates the directory structure for implementing domain-specific operations following an atomic feature architecture. ```tree src/features/ ├── repositoryManagement/ │ ├── resources/ # Read-only operations │ │ ├── getRepository/ │ │ ├── listRepositories/ │ │ └── index.export.ts │ ├── modifications/ # Write operations │ │ ├── createRepository/ │ │ └── index.export.ts │ └── index.export.ts ├── branchManagement/ │ ├── resources/ │ │ ├── listBranches/ │ │ └── index.export.ts │ ├── modifications/ │ │ ├── createBranch/ │ │ ├── deleteBranch/ │ │ └── index.export.ts │ └── index.export.ts └── [issueManagement, pullRequestManagement, fileManagement, releaseManagement]/ ``` -------------------------------- ### Retry Strategy Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Describes the retry strategy for transient failures, employing exponential backoff. ```text Attempt 1: Immediate Attempt 2: Wait 1 second Attempt 3: Wait 2 seconds Attempt 4: Wait 4 seconds Failed → Return error to caller ``` -------------------------------- ### ApplicationEnvironmentConfiguration Interface Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Defines the structure for environment-specific application configuration. ```typescript interface ApplicationEnvironmentConfiguration { githubToken: string; logLevel: string; serverName: string; serverVersion: string; apiTimeoutMs: number; rateLimiting: RateLimitingConfiguration; } ``` -------------------------------- ### getRepositorySchema Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/types.md Zod schema for validating input to the get_repository tool, requiring owner and repo. ```typescript const getRepositorySchema = z.object({ owner: z.string().min(1, "Owner is required"), repo: z.string().min(1, "Repository name is required") }); ``` -------------------------------- ### getGitHubResponseMapper() Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md Returns the response mapper instance. ```typescript function getGitHubResponseMapper(): ResponseMapper ``` -------------------------------- ### Parsing RATE_LIMIT_RESET_BUFFER_MS Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md Parses the RATE_LIMIT_RESET_BUFFER_MS environment variable, with a default value of 5000ms. ```typescript const rateLimitResetBufferMs = parseNumericEnv( getEnvVariable('RATE_LIMIT_RESET_BUFFER_MS', false), 5000 ); ``` -------------------------------- ### List Repository Issues Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Lists issues in a repository with optional filtering. ```typescript listRepositoryIssues( params: ListIssuesParams ): Promise>> ``` ```json { "type": "object", "properties": { "owner": { "type": "string" }, "repo": { "type": "string" }, "state": { "type": "string", "enum": ["open", "closed", "all"] }, "labels": { "type": "array", "items": { "type": "string" } } }, "required": ["owner", "repo"] } ``` ```typescript const result = await tool.execute({ owner: "anthropics", repo: "anthropic-sdk-python", state: "open", labels: ["bug"] }); ``` -------------------------------- ### Core Modules Directory Structure Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md Details the organization of core modules, including application entry, configuration, dependency injection, services, types, and utilities. ```tree src/ ├── application.entry.ts # MCP server initialization ├── configuration/ # Configuration loading │ ├── application.config.ts │ ├── environment.config.ts │ └── configuration.types.ts ├── dependencyInjection/ # Tool registry │ └── tool.registry.ts ├── services/githubAccess/ # GitHub service │ ├── github.service.ts │ ├── github.service.types.ts │ ├── github.rate.limiter.ts │ └── github.response.mapper.ts ├── types/ # Core types │ ├── entity.definition.types.ts │ ├── error.definition.types.ts │ └── operation.result.types.ts └── utilities/ # Helper functions ├── structured.logging.utility.ts ├── error.handling.utility.ts ├── validation.utility.ts ├── promise.utility.ts ├── type.casting.utility.ts └── logger.utility.ts ``` -------------------------------- ### Singleton Access Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/services-utilities.md The service uses the singleton pattern to maintain a single Octokit instance across the application. ```typescript static getInstance(): GitHubService { if (!GitHubService.instance) { GitHubService.instance = new GitHubService(); } return GitHubService.instance; } ``` -------------------------------- ### create_pull_request Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Creates a new pull request. ```typescript createRepositoryPullRequest( params: CreatePullRequestParams ): Promise> ``` ```json { "type": "object", "properties": { "owner": { "type": "string" }, "repo": { "type": "string" }, "title": { "type": "string" }, "head": { "type": "string" }, "base": { "type": "string" }, "body": { "type": "string" } }, "required": ["owner", "repo", "title", "head", "base"] } ``` ```typescript interface CreatePullRequestResponseType { pullRequest: GitHubPullRequestEntity; repository: { owner: string; name: string }; creationTimestamp: string; } ``` ```typescript const result = await tool.execute({ owner: "anthropics", repo: "anthropic-sdk-python", title: "feat: Add streaming message support", head: "feature/streaming", base: "main", body: "This PR adds support for streaming messages..." }); ``` -------------------------------- ### Rate Limit Enabled Parsing Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/configuration.md This TypeScript code snippet demonstrates parsing the RATE_LIMIT_ENABLED environment variable into a boolean value, with a default of true. ```typescript const rateLimitEnabled = parseBooleanEnv( getEnvVariable('RATE_LIMIT_ENABLED', false), true ); ``` -------------------------------- ### createGithubApiError() Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/errors.md Creates a GitHub API error object. ```typescript static createGithubApiError( message: string, context?: Record ): StandardizedApplicationErrorObject ``` ```typescript const error = ApplicationErrorHandlingUtility.createGithubApiError( 'Repository not found', { owner: 'anthropics', repo: 'sdk', status: 404 } ); ``` -------------------------------- ### GitHubRepositoryEntity Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/types.md Represents a GitHub repository. ```typescript interface GitHubRepositoryEntity { repositoryId: number; repositoryName: string; repositoryFullName: string; repositoryUrl: string; isPrivate: boolean; description?: string; createdAt: string; updatedAt: string; } ``` -------------------------------- ### createBranchSchema Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/types.md Zod schema for validating input to the create_branch tool, requiring owner, repo, branch name, and SHA. ```typescript const createBranchSchema = z.object({ owner: z.string().min(1, "Owner is required"), repo: z.string().min(1, "Repository name is required"), branch: z.string().min(1, "Branch name is required"), sha: z.string().min(1, "SHA is required") }); ``` -------------------------------- ### createSuccessResult() Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/errors.md Creates a successful operation result. ```typescript static createSuccessResult(data: DataType): OperationResult ``` -------------------------------- ### Rate Limiting Logic Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/architecture-patterns.md Outlines the logic for the rate limiter, which prevents exceeding GitHub's request limits by checking remaining requests and waiting if necessary. ```text Check remaining requests ↓ If remaining <= MIN_RATE_LIMIT_REMAINING (50) Yes → Calculate wait time ↓ Wait until reset + buffer No → Proceed immediately ↓ Execute API call ``` -------------------------------- ### createIssueSchema Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/types.md Zod schema for validating input to the create_issue tool, requiring owner, repo, and title, with optional body and labels. ```typescript const createIssueSchema = z.object({ owner: z.string().min(1, "Owner is required"), repo: z.string().min(1, "Repository name is required"), title: z.string().min(1, "Title is required"), body: z.string().optional(), labels: z.array(z.string()).optional() }); ``` -------------------------------- ### Operation Response Pattern Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/README.md The standard pattern for successful operation responses, including entity data, repository information, and a timestamp. ```typescript { resultSuccessful: true, resultData: { [entity]: EntityType, repository: { owner: string; name: string }, [timestamp]: string // ISO 8601 } } ``` -------------------------------- ### List Branches Source: https://github.com/cyanheads/github-mcp-server/blob/main/_autodocs/api-reference-tools.md Lists all branches in a repository with optional filtering by protection status. ```typescript listRepositoryBranches( params: ListBranchesParams ): Promise>> ``` ```json { "type": "object", "properties": { "owner": { "type": "string" }, "repo": { "type": "string" }, "protected": { "type": "boolean" }, "per_page": { "type": "number" } }, "required": ["owner", "repo"] } ``` ```typescript const result = await tool.execute({ owner: "anthropics", repo: "anthropic-sdk-python", protected: true, per_page: 50 }); ```