UNPKG

octocode-mcp

Version:

Model Context Protocol (MCP) server for advanced GitHub repository analysis, code discovery, and npm package exploration. Provides AI assistants with powerful tools to search, analyze, and understand codebases across GitHub and npm ecosystems.

1,005 lines (818 loc) 277 kB
#!/usr/bin/env node import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'; import z from 'zod'; import NodeCache from 'node-cache'; import crypto from 'crypto'; import { exec } from 'child_process'; import { promisify } from 'util'; const TOOL_NAMES = { // GitHub Search API (/search/*) GITHUB_SEARCH_CODE: 'github_search_code', GITHUB_SEARCH_REPOS: 'github_search_repositories', GITHUB_SEARCH_COMMITS: 'github_search_commits', GITHUB_SEARCH_ISSUES: 'github_search_issues', GITHUB_SEARCH_PULL_REQUESTS: 'github_search_pull_requests', GITHUB_SEARCH_TOPICS: 'github_search_topics', GITHUB_SEARCH_USERS: 'github_search_users', // GitHub Repository API (/repos/*) GITHUB_GET_REPOSITORY: 'github_get_repository', GITHUB_GET_CONTENTS: 'github_get_contents', GITHUB_GET_FILE_CONTENT: 'github_get_file_content', // GitHub Users API (/user/*) GITHUB_GET_USER_ORGS: 'github_get_user_organizations', // System & API Status API_STATUS_CHECK: 'api_status_check', // npm Registry API - Comprehensive NPM_SEARCH_PACKAGES: 'npm_search_packages', NPM_GET_PACKAGE: 'npm_get_package', NPM_ANALYZE_DEPENDENCIES: 'npm_analyze_dependencies', // npm Registry API - Focused (minimal token usage) NPM_GET_REPOSITORY: 'npm_get_repository', NPM_GET_DEPENDENCIES: 'npm_get_dependencies', NPM_GET_BUGS: 'npm_get_bugs', NPM_GET_README: 'npm_get_readme', NPM_GET_VERSIONS: 'npm_get_versions', NPM_GET_AUTHOR: 'npm_get_author', NPM_GET_LICENSE: 'npm_get_license', NPM_GET_HOMEPAGE: 'npm_get_homepage', NPM_GET_ID: 'npm_get_id', NPM_GET_RELEASES: 'npm_get_releases', NPM_GET_ENGINES: 'npm_get_engines', NPM_GET_EXPORTS: 'npm_get_exports'}; const PROMPT_SYSTEM_PROMPT = `**Universal Research Intelligence Engine** - Comprehensive discovery, analysis, and insights across all domains of knowledge. ## 🛠️ CRITICAL: API STATUS VERIFICATION FIRST **MANDATORY FIRST STEP:** Always begin research sessions with ${TOOL_NAMES.API_STATUS_CHECK} to: - Verify GitHub CLI authentication (gh auth status) - Confirm NPM registry connectivity (npm ping) - Analyze real-time GitHub API rate limits across all endpoints - Get intelligent research strategy recommendations based on current API capacity **RESEARCH STRATEGY ADAPTATION:** - **READY Status**: Proceed with comprehensive multi-tool research - **LIMITED Status**: Use targeted searches, avoid broad exploration - **NOT_READY Status**: Guide user through authentication/connectivity setup **API-AWARE RESEARCH PLANNING:** - Code Search < 5 remaining → Use repository browsing instead - Search API < 20 remaining → Focus on specific repositories - Core API < 200 remaining → Minimize repository exploration - NPM disconnected → GitHub-only research mode ## ADAPTIVE RESEARCH METHODOLOGY ### SEMANTIC TOPIC DETECTION & ADAPTATION Automatically detect query intent and adapt research strategy: **TECHNOLOGY & SOFTWARE** → NPM packages, GitHub repositories, code implementations, documentation **ACADEMIC & RESEARCH** → GitHub topics, research repositories, academic projects, papers **BUSINESS & ORGANIZATIONS** → Company repositories, organizational projects, business tools **CREATIVE & MEDIA** → Creative coding, media projects, artistic repositories, design systems **EDUCATION & LEARNING** → Educational resources, tutorials, learning materials, course content **SCIENCE & DATA** → Data science projects, scientific computing, research datasets, analysis tools **GENERAL KNOWLEDGE** → Any topic through GitHub's vast ecosystem of projects and discussions ### UNIVERSAL RESEARCH DIMENSIONS Every query requires investigation across multiple dimensions: **1. DISCOVERY & EXPLORATION** - Find relevant projects, packages, and implementations - Identify multiple approaches and methodologies - Locate official vs community resources - Discover edge cases and alternative solutions **2. ECOSYSTEM ANALYSIS** - Understand relationships and dependencies - Analyze community adoption and trends - Evaluate maintenance and support status - Assess quality and reliability indicators **3. QUALITY & CREDIBILITY ASSESSMENT** - Project quality and architecture evaluation - Performance characteristics and benchmarks - Documentation completeness and clarity - Community engagement and activity levels **4. CONTEXTUAL INTELLIGENCE** - Trade-offs vs alternative approaches - Scalability and practical considerations - Integration complexity and requirements - Learning curve and accessibility **5. STRATEGIC INSIGHTS** - Future trends and evolution patterns - Community momentum and backing - Suitability for different use cases - Migration paths and compatibility ## INTELLIGENT TOOL SELECTION STRATEGY ### SEMANTIC QUERY ANALYSIS Analyze query semantics to determine optimal tool combination: **PACKAGE/LIBRARY QUERIES** → NPM-first approach **PROJECT/REPOSITORY QUERIES** → GitHub repository search **TOPIC/CONCEPT QUERIES** → GitHub topics exploration **IMPLEMENTATION QUERIES** → Code search and file extraction **PROBLEM/SOLUTION QUERIES** → Issues and discussions search **PEOPLE/EXPERTISE QUERIES** → User and organization discovery ### ADAPTIVE SEARCH PATTERNS **FOR TECHNOLOGY TOPICS:** - ${TOOL_NAMES.NPM_SEARCH_PACKAGES} → Package ecosystem discovery - ${TOOL_NAMES.GITHUB_SEARCH_TOPICS} → Technology landscape mapping - ${TOOL_NAMES.GITHUB_SEARCH_CODE} → Implementation patterns - ${TOOL_NAMES.GITHUB_SEARCH_REPOS} → Project repositories **FOR RESEARCH/ACADEMIC TOPICS:** - ${TOOL_NAMES.GITHUB_SEARCH_TOPICS} → Research area exploration - ${TOOL_NAMES.GITHUB_SEARCH_REPOS} → Academic projects and papers - ${TOOL_NAMES.GITHUB_SEARCH_CODE} → Research implementations - ${TOOL_NAMES.GITHUB_SEARCH_USERS} → Researcher discovery **FOR BUSINESS/ORGANIZATIONAL TOPICS:** - ${TOOL_NAMES.GITHUB_GET_USER_ORGS} → Organization discovery - ${TOOL_NAMES.GITHUB_SEARCH_REPOS} → Company projects - ${TOOL_NAMES.GITHUB_SEARCH_CODE} → Internal implementations - ${TOOL_NAMES.GITHUB_SEARCH_ISSUES} → Business discussions **FOR CREATIVE/MEDIA TOPICS:** - ${TOOL_NAMES.GITHUB_SEARCH_TOPICS} → Creative technology trends - ${TOOL_NAMES.GITHUB_SEARCH_REPOS} → Creative projects and tools - ${TOOL_NAMES.GITHUB_SEARCH_CODE} → Creative implementations - ${TOOL_NAMES.NPM_SEARCH_PACKAGES} → Creative libraries and tools ## UNIVERSAL BOOLEAN SEARCH INTELLIGENCE ### SEMANTIC EXPANSION PATTERNS Automatically enhance queries with domain-appropriate boolean operators: **UNIVERSAL DOMAIN PATTERNS:** - **Core Concepts**: "primary_term OR synonym OR variation OR abbreviation" - **Quality Focus**: "concept OR approach OR method OR technique NOT test NOT demo" - **Comprehensive Coverage**: "topic OR field OR domain OR area OR discipline" - **Implementation Focus**: "solution OR tool OR system OR framework OR platform" **ADAPTIVE SEMANTIC ENHANCEMENT:** - **Academic/Research**: "research OR study OR analysis OR investigation OR methodology" - **Creative/Artistic**: "creative OR artistic OR design OR visual OR aesthetic OR expression" - **Business/Professional**: "business OR professional OR commercial OR enterprise OR industry" - **Educational/Learning**: "education OR learning OR tutorial OR guide OR instruction OR knowledge" - **Technical/Scientific**: "technical OR scientific OR systematic OR analytical OR computational" - **Social/Community**: "social OR community OR collaborative OR public OR collective" **CONTEXTUAL BOOLEAN PATTERNS:** - **Problem-Solving**: "solution OR approach OR method OR strategy OR technique" - **Tool Discovery**: "tool OR utility OR application OR platform OR system OR framework" - **Knowledge Seeking**: "guide OR tutorial OR documentation OR resource OR reference" - **Community Building**: "community OR collaboration OR network OR group OR organization" - **Innovation Exploration**: "innovation OR experimental OR cutting-edge OR emerging OR novel" ## ADAPTIVE RESEARCH WORKFLOWS ### DISCOVERY INTENT DETECTION Automatically route based on query patterns: **"Find [topic] tools/resources"** → Package + Topic + Repository Discovery **"How to [accomplish/solve]"** → Content search + Community discussions + Documentation **"Who works on [topic]"** → User + Organization + Contributor Discovery **"What's trending in [domain]"** → Topic + Popular projects + Recent activity **"Compare [A] vs [B]"** → Multi-target analysis + Community discussions **"Learn about [concept]"** → Educational resources + Documentation + Examples **"Research [topic]"** → Academic projects + Data + Methodology discovery **"Create [something]"** → Tools + Frameworks + Creative resources **"Analyze [subject]"** → Data tools + Visualization + Analytics resources ### CONTEXTUAL WORKFLOW ADAPTATION **DISCOVERY QUERIES:** 1. Topic landscape mapping (${TOOL_NAMES.GITHUB_SEARCH_TOPICS}) 2. Resource discovery (${TOOL_NAMES.NPM_SEARCH_PACKAGES}) 3. Project exploration (${TOOL_NAMES.GITHUB_SEARCH_REPOS}) 4. Content analysis (${TOOL_NAMES.GITHUB_SEARCH_CODE}) **RESEARCH QUERIES:** 1. Domain exploration (${TOOL_NAMES.GITHUB_SEARCH_TOPICS}) 2. Academic project discovery (${TOOL_NAMES.GITHUB_SEARCH_REPOS}) 3. Methodology analysis (${TOOL_NAMES.GITHUB_SEARCH_CODE}) 4. Expert network discovery (${TOOL_NAMES.GITHUB_SEARCH_USERS}) **SOLUTION QUERIES:** 1. Resource identification (${TOOL_NAMES.NPM_SEARCH_PACKAGES}) 2. Project discovery (${TOOL_NAMES.GITHUB_SEARCH_REPOS}) 3. Implementation analysis (${TOOL_NAMES.GITHUB_SEARCH_CODE}) 4. Community support (${TOOL_NAMES.GITHUB_SEARCH_ISSUES}) ## SEMANTIC PROPOSITION FRAMEWORK ### DYNAMIC GUIDANCE SYSTEM Provide context-aware recommendations based on detected domain: **UNIVERSAL PROPOSITIONS:** - "Consider quality indicators and community engagement" - "Evaluate approach diversity and methodological rigor" - "Assess resource accessibility and learning curve" - "Review documentation completeness and clarity" **RESEARCH PROPOSITIONS:** - "Examine methodology and experimental design" - "Evaluate data quality and reproducibility" - "Consider peer validation and citation patterns" - "Assess theoretical foundations and practical applications" **CREATIVE PROPOSITIONS:** - "Explore artistic expression and creative possibilities" - "Consider aesthetic principles and design philosophy" - "Evaluate creative tools and workflow integration" - "Assess community engagement and inspiration sources" **BUSINESS PROPOSITIONS:** - "Analyze market adoption and practical viability" - "Evaluate cost-benefit and resource requirements" - "Consider scalability and implementation complexity" - "Assess competitive landscape and differentiation" **EDUCATIONAL PROPOSITIONS:** - "Examine learning pathways and skill progression" - "Evaluate pedagogical approach and accessibility" - "Consider prerequisite knowledge and learning curve" - "Assess practical application and real-world relevance" **COMMUNITY PROPOSITIONS:** - "Explore collaboration opportunities and network effects" - "Evaluate community health and engagement patterns" - "Consider contribution pathways and skill development" - "Assess social impact and collective benefit" ## UNIVERSAL ANTI-HALLUCINATION SAFEGUARDS ### DOMAIN-AGNOSTIC VALIDATION - **Existence Verification**: Confirm resources exist before deep analysis - **Cross-Reference Validation**: Verify findings across multiple sources - **Community Consensus**: Check for widespread adoption vs niche experiments - **Recency Assessment**: Evaluate currency and maintenance status - **Authority Validation**: Assess source credibility and expertise ### PROGRESSIVE REFINEMENT STRATEGY - **Broad Discovery**: Start with general terms and concepts - **Semantic Expansion**: Add related terms and variations - **Context Filtering**: Apply domain-specific filters and exclusions - **Quality Assessment**: Evaluate results for relevance and quality - **Deep Analysis**: Extract detailed insights from validated sources ## INTELLIGENT RESULT SYNTHESIS ### MULTI-DIMENSIONAL ANALYSIS For every comprehensive answer, provide: **LANDSCAPE OVERVIEW** - Current state of the domain/topic - Key players and influential projects - Trending approaches and methodologies - Community dynamics and adoption patterns **PRACTICAL INSIGHTS** - Actionable recommendations with rationale - Common challenges and solution approaches - Best practices and proven patterns - Learning resources and next steps **STRATEGIC CONTEXT** - Future trends and evolution directions - Trade-offs and decision frameworks - Suitability for different use cases - Risk assessment and mitigation strategies **COMMUNITY INTELLIGENCE** - Expert contributors and thought leaders - Active discussions and debates - Collaborative opportunities and networks - Knowledge gaps and research opportunities ## ADAPTIVE ERROR RECOVERY ### SEMANTIC FALLBACK STRATEGIES When primary searches fail, automatically adapt: **TERM EXPANSION**: Broaden to related concepts and synonyms **DOMAIN SHIFTING**: Explore adjacent fields and applications **ABSTRACTION LEVELS**: Move between specific and general concepts **TEMPORAL ADJUSTMENT**: Consider historical vs cutting-edge approaches **COMMUNITY PIVOTING**: Shift from technical to social/community aspects ### INTELLIGENT GUIDANCE Provide domain-appropriate suggestions for: - Alternative search strategies - Related topics worth exploring - Community resources and experts - Learning pathways and next steps **OUTPUT GOAL**: Comprehensive, accurate, and actionable insights across any domain of knowledge, leveraging GitHub's vast ecosystem of human knowledge and collaboration.`; const TOOL_DESCRIPTIONS = { [TOOL_NAMES.NPM_SEARCH_PACKAGES]: `**Universal Package Discovery Engine** - Intelligent resource discovery with semantic understanding across all domains. **🧠 SEMANTIC PACKAGE INTELLIGENCE:** - **DOMAIN-ADAPTIVE SEARCH**: Automatically detects query intent and adapts search strategy - **UNIVERSAL RESOURCE DISCOVERY**: Finds packages, tools, libraries, frameworks across any field - **INTELLIGENT CATEGORIZATION**: Understands technology, creative, business, educational, scientific packages - **CONTEXTUAL RECOMMENDATIONS**: Provides domain-specific guidance and alternatives **🎯 ADAPTIVE SEARCH STRATEGIES:** - **TECHNOLOGY PACKAGES** → Development tools, frameworks, libraries, utilities - **CREATIVE PACKAGES** → Design tools, media processing, artistic frameworks, generators - **BUSINESS PACKAGES** → Analytics, automation, productivity, management tools - **EDUCATIONAL PACKAGES** → Learning resources, documentation generators, tutorial tools - **SCIENTIFIC PACKAGES** → Data analysis, visualization, computation, research tools - **UTILITY PACKAGES** → General-purpose tools, helpers, converters, processors **🚀 INTELLIGENT QUERY OPTIMIZATION:** 1. **Single Terms**: "visualization", "automation", "analysis", "design" 2. **Combined Concepts**: "data-visualization", "workflow-automation", "content-management" 3. **Domain Bridging**: Technical terms → accessible language, specific → general 4. **Semantic Expansion**: Core concept → related terms → ecosystem discovery **💡 UNIVERSAL SEARCH PATTERNS:** - **"data visualization"** → Charts, graphs, dashboards, plotting tools - **"content management"** → CMS, publishing, editorial, workflow tools - **"image processing"** → Graphics, filters, conversion, manipulation tools - **"workflow automation"** → Task runners, schedulers, pipeline tools - **"learning resources"** → Educational, tutorial, documentation tools **🌍 CROSS-DOMAIN EXAMPLES:** - **CREATIVE DOMAIN**: "design OR graphics OR visual OR creative OR artistic" - **BUSINESS DOMAIN**: "management OR analytics OR productivity OR automation" - **RESEARCH DOMAIN**: "analysis OR data OR research OR scientific OR academic" - **EDUCATIONAL DOMAIN**: "learning OR tutorial OR education OR documentation" - **UTILITY DOMAIN**: "tool OR utility OR helper OR converter OR processor" **🔧 ORGANIZATIONAL INTELLIGENCE:** - **@organization/** packages → Triggers private/enterprise discovery workflow - **Internal/Private** indicators → Activates organizational context search - **Enterprise** patterns → Suggests organizational repository exploration **⚡ SEARCH OPTIMIZATION:** - **0 results** → Broader terms, ecosystem exploration, alternative approaches - **1-20 results** → IDEAL scope for detailed analysis and comparison - **100+ results** → More specific terms, domain filters, focused refinement - **Organizational scope** → Private package discovery, enterprise workflows **🔄 INTELLIGENT FALLBACK STRATEGIES:** When package search yields insufficient results: 1. **Ecosystem Exploration** → Related technology/domain discovery 2. **Repository Search** → Direct project/tool discovery 3. **Topic Analysis** → Domain terminology and trend identification 4. **Community Discovery** → Expert and organization identification 5. **Content Search** → Implementation and usage pattern analysis 6. **Discussion Mining** → Problem-solving and solution discovery **🎨 DOMAIN-SPECIFIC INTELLIGENCE:** - **Creative Tools**: Design, media, art, visualization, creative coding - **Business Solutions**: Analytics, automation, management, productivity - **Research Instruments**: Data analysis, computation, visualization, modeling - **Educational Resources**: Learning, documentation, tutorials, guides - **Utility Collections**: Helpers, converters, processors, generators **INPUT**: Any concept, tool, or resource need across any domain **OUTPUT**: Comprehensive package ecosystem with domain-adapted insights and alternatives`, [TOOL_NAMES.NPM_ANALYZE_DEPENDENCIES]: `**CRITICAL: Package security analysis** - Essential for package evaluation and organizational detection. **WHEN TO USE:** ALWAYS after ${TOOL_NAMES.NPM_SEARCH_PACKAGES} for complete assessment. **ANALYSIS:** Security vulnerabilities, dependency tree, license compatibility, bundle impact, organization detection (@company/). **ORGANIZATIONAL CONTEXT:** Private packages → Check ${TOOL_NAMES.GITHUB_GET_USER_ORGS} for access **KNOWN LIMITATION:** Some NPM audit failures may occur (package-specific). Bundle analysis and dependency tree remain reliable.`, [TOOL_NAMES.GITHUB_SEARCH_TOPICS]: `**Universal Topic Discovery Engine** - Comprehensive ecosystem exploration with semantic intelligence across all domains. **🧠 SEMANTIC TOPIC INTELLIGENCE:** - **DOMAIN-AGNOSTIC DISCOVERY**: Explores any field, discipline, or area of interest - **ECOSYSTEM MAPPING**: Reveals relationships, trends, and communities across topics - **CONTEXTUAL UNDERSTANDING**: Adapts recommendations based on query domain and intent - **CROSS-POLLINATION**: Discovers unexpected connections between different fields **🎯 UNIVERSAL EXPLORATION PATTERNS:** - **SINGLE TERMS**: "sustainability", "automation", "creativity", "wellness", "education" - **COMPOUND CONCEPTS**: "machine-learning", "user-experience", "data-science", "digital-art" - **DOMAIN BRIDGING**: Technical ↔ Creative ↔ Business ↔ Academic ↔ Social **🌍 CROSS-DOMAIN TOPIC DISCOVERY:** - **TECHNOLOGY DOMAINS**: "ai", "blockchain", "iot", "cybersecurity", "cloud-computing" - **CREATIVE DOMAINS**: "design", "art", "music", "writing", "photography", "animation" - **BUSINESS DOMAINS**: "entrepreneurship", "marketing", "finance", "management", "strategy" - **ACADEMIC DOMAINS**: "research", "education", "science", "mathematics", "psychology" - **SOCIAL DOMAINS**: "community", "activism", "sustainability", "health", "culture" - **LIFESTYLE DOMAINS**: "fitness", "cooking", "travel", "productivity", "mindfulness" **🚀 INTELLIGENT SEARCH STRATEGIES:** 1. **Broad Discovery**: Start with core concepts to map the landscape 2. **Semantic Expansion**: Related terms, synonyms, and variations 3. **Community Identification**: Active projects, contributors, and organizations 4. **Trend Analysis**: Emerging topics, popular projects, and growth patterns 5. **Cross-Domain Connections**: Unexpected intersections and collaborations **💡 ADAPTIVE TOPIC PATTERNS:** - **"sustainability"** → Environmental, green-tech, renewable, climate, conservation - **"creativity"** → Art, design, innovation, expression, generative, artistic - **"wellness"** → Health, fitness, mental-health, mindfulness, nutrition - **"automation"** → Workflow, productivity, efficiency, tools, processes - **"learning"** → Education, tutorial, knowledge, skill-development, training **🔍 DISCOVERY METHODOLOGIES:** - **ECOSYSTEM EXPLORATION**: Map entire domains and their sub-communities - **TREND IDENTIFICATION**: Spot emerging topics and growing communities - **COMMUNITY MAPPING**: Find active contributors and thought leaders - **RESOURCE DISCOVERY**: Locate tools, frameworks, and learning materials - **COLLABORATION OPPORTUNITIES**: Identify potential partnerships and projects **⚡ SEARCH OPTIMIZATION STRATEGIES:** - **1-10 TOPICS**: Perfect scope for deep domain analysis - **10+ TOPICS**: Rich ecosystem with multiple exploration paths - **Featured/Curated**: High-quality, community-validated topics - **Repository Count**: Indicates community size and activity level **🎨 DOMAIN-SPECIFIC INTELLIGENCE:** - **CREATIVE EXPLORATION**: Art, design, media, expression, aesthetics - **BUSINESS INTELLIGENCE**: Strategy, operations, innovation, market trends - **RESEARCH DISCOVERY**: Academic, scientific, experimental, methodological - **EDUCATIONAL RESOURCES**: Learning, teaching, knowledge transfer, skill building - **SOCIAL IMPACT**: Community, activism, sustainability, social good - **PERSONAL DEVELOPMENT**: Wellness, productivity, skills, lifestyle, growth **🔄 PROGRESSIVE DISCOVERY WORKFLOW:** 1. **Core Topic Exploration** → Understand the fundamental landscape 2. **Related Topic Discovery** → Find adjacent and complementary areas 3. **Community Identification** → Locate active contributors and projects 4. **Resource Mapping** → Discover tools, frameworks, and materials 5. **Trend Analysis** → Identify emerging patterns and opportunities 6. **Cross-Domain Bridging** → Find unexpected connections and innovations **🌟 UNIVERSAL APPLICATIONS:** - **Research Planning**: Explore academic and scientific domains - **Business Strategy**: Identify market trends and opportunities - **Creative Inspiration**: Discover artistic and design communities - **Learning Pathways**: Find educational resources and skill development - **Community Building**: Locate like-minded individuals and organizations - **Innovation Discovery**: Spot emerging technologies and methodologies **INPUT**: Any topic, concept, interest, or domain of inquiry **OUTPUT**: Comprehensive ecosystem map with community insights, trends, and exploration pathways`, [TOOL_NAMES.GITHUB_GET_USER_ORGS]: `**CRITICAL: Private organization discovery** - Essential for company/enterprise repository access. **AUTO-TRIGGERS:** @wix/, @company/, "I work at [Company]", "internal code", "enterprise setup" **WORKFLOW:** IMMEDIATE call when organizational context detected → Match company to organizations → Use as 'owner' parameter → Enable private repository access **INTEGRATION:** MANDATORY first step when private access likely needed`, [TOOL_NAMES.GITHUB_GET_REPOSITORY]: `**CRITICAL FIRST STEP** - Required before all GitHub file operations, but ONLY after discovery. **PURPOSE:** Discover default branch and repository metadata to prevent tool failures. **MANDATORY PREREQUISITES:** Repository owner/name MUST be discovered first through: 1. ${TOOL_NAMES.NPM_SEARCH_PACKAGES} → ${TOOL_NAMES.NPM_GET_PACKAGE} (for packages) 2. ${TOOL_NAMES.GITHUB_SEARCH_TOPICS} (for ecosystem discovery) 3. ${TOOL_NAMES.GITHUB_SEARCH_REPOS} (last resort) **REQUIRED BEFORE:** ${TOOL_NAMES.GITHUB_SEARCH_CODE}, ${TOOL_NAMES.GITHUB_GET_CONTENTS}, ${TOOL_NAMES.GITHUB_GET_FILE_CONTENT} **CRITICAL:** NEVER call with guessed repository names. ALWAYS use discovery workflow first.`, [TOOL_NAMES.GITHUB_SEARCH_CODE]: `**Universal Content Discovery Engine** - Intelligent search with automatic domain adaptation and semantic understanding. **🧠 SEMANTIC QUERY INTELLIGENCE - ADAPTS TO ANY DOMAIN:** - **AUTOMATIC DOMAIN DETECTION**: Analyzes query intent and adapts search strategy accordingly - **UNIVERSAL BOOLEAN ENHANCEMENT**: Converts any query into optimal boolean patterns for maximum efficiency - **CROSS-DOMAIN EXPERTISE**: Handles technology, research, business, creative, educational, scientific topics - **CONTEXTUAL INTELLIGENCE**: Provides domain-specific guidance based on query semantics **🎯 ADAPTIVE SEMANTIC PATTERNS:** - **TECHNOLOGY QUERIES** → "framework OR library OR tool OR implementation NOT tutorial" - **RESEARCH QUERIES** → "study OR analysis OR research OR investigation NOT example" - **BUSINESS QUERIES** → "solution OR strategy OR management OR process NOT demo" - **CREATIVE QUERIES** → "design OR art OR creative OR visual NOT template" - **EDUCATIONAL QUERIES** → "learning OR education OR tutorial OR guide NOT test" - **SCIENTIFIC QUERIES** → "data OR analysis OR algorithm OR method NOT mock" **🚀 INTELLIGENT QUERY OPTIMIZATION:** - **Semantic Expansion**: Automatically adds synonyms and variations based on domain - **Context Enrichment**: Suggests related terms specific to the detected topic area - **Quality Filtering**: Adds appropriate exclusions (NOT test, NOT example, NOT demo) - **Progressive Refinement**: Starts broad, then narrows based on results **🔧 UNIVERSAL BOOLEAN INTELLIGENCE:** - **COVERAGE PATTERNS**: "primary_term OR synonym OR variation OR abbreviation" - **PRECISION PATTERNS**: "specific_concept AND context AND domain NOT noise" - **QUALITY PATTERNS**: "topic NOT test NOT example NOT demo NOT tutorial" - **DOMAIN PATTERNS**: "core_concept OR related_field OR application_area" **💡 SEMANTIC DOMAIN EXAMPLES:** - **"machine learning"** → "ml OR ai OR algorithm OR model OR neural NOT tutorial" - **"climate change"** → "climate OR environment OR warming OR carbon NOT simulation" - **"marketing strategy"** → "marketing OR strategy OR campaign OR brand NOT template" - **"data visualization"** → "visualization OR chart OR graph OR dashboard NOT example" - **"user experience"** → "ux OR ui OR design OR usability OR interface NOT mockup" **🎨 CREATIVE DOMAIN INTELLIGENCE:** - **Art & Design**: "creative OR artistic OR visual OR aesthetic OR design" - **Music & Audio**: "music OR audio OR sound OR composition OR production" - **Writing & Content**: "writing OR content OR narrative OR storytelling OR editorial" - **Media & Video**: "video OR media OR film OR animation OR production" **🔬 ACADEMIC DOMAIN INTELLIGENCE:** - **Research**: "research OR study OR analysis OR investigation OR methodology" - **Science**: "scientific OR experiment OR hypothesis OR data OR evidence" - **Mathematics**: "mathematical OR algorithm OR computation OR formula OR proof" - **Social Sciences**: "social OR behavioral OR psychological OR cultural OR demographic" **🏢 BUSINESS DOMAIN INTELLIGENCE:** - **Management**: "management OR leadership OR strategy OR operations OR planning" - **Finance**: "financial OR economic OR investment OR budget OR revenue" - **Marketing**: "marketing OR advertising OR branding OR promotion OR customer" - **Analytics**: "analytics OR metrics OR performance OR tracking OR insights" **🌍 UNIVERSAL FALLBACK STRATEGIES:** - **Term Simplification**: Complex phrases → core concepts - **Semantic Broadening**: Specific terms → general categories - **Cross-Domain Bridging**: Technical terms → common language - **Progressive Refinement**: General → specific based on results **⚡ EFFICIENCY GUARANTEES:** - **3-5x Performance**: Boolean queries consistently outperform simple text - **Automatic Enhancement**: Every query gets optimized for maximum results - **Smart Fallbacks**: Multiple strategies ensure you always get insights - **Domain Adaptation**: Recommendations tailored to your specific field **🔍 ANTI-HALLUCINATION SAFEGUARDS:** - **Existence Verification**: Confirms content exists before deep analysis - **Semantic Validation**: Checks query makes sense in detected domain - **Progressive Discovery**: Starts broad, narrows based on actual results - **Cross-Reference**: Validates findings across multiple sources **INPUT**: Any query in any domain - technology, research, business, creative, educational, scientific **OUTPUT**: Comprehensive, domain-adapted search results with intelligent insights and next steps`, [TOOL_NAMES.GITHUB_GET_FILE_CONTENT]: `**Complete code extraction** - Fetch full working implementations. **CRITICAL WORKFLOW:** MANDATORY discovery → ${TOOL_NAMES.GITHUB_GET_REPOSITORY} → Find files with ${TOOL_NAMES.GITHUB_SEARCH_CODE} or ${TOOL_NAMES.GITHUB_GET_CONTENTS} → Extract with this tool **AUTO-RECOVERY:** Specified branch → main → master → develop → trunk → try without ref **ENHANCED ERROR HANDLING:** Provides detailed guidance when files don't exist, with alternative discovery methods **ORGANIZATIONAL CONTEXT:** Private repositories → Use ${TOOL_NAMES.GITHUB_GET_USER_ORGS} for access **CRITICAL:** NEVER guess file paths. Use structure exploration or code search first.`, [TOOL_NAMES.GITHUB_GET_CONTENTS]: `**Repository structure exploration** - Strategic directory navigation. **CRITICAL:** MANDATORY ${TOOL_NAMES.GITHUB_GET_REPOSITORY} FIRST for branch discovery. **EXPLORATION:** Root analysis → Source discovery (src/, lib/, components/) → Validation (test/, examples/) **AUTO-RECOVERY:** Specified branch → main → master → develop → trunk → try without ref`, [TOOL_NAMES.GITHUB_SEARCH_ISSUES]: `**Problem discovery** - Issue search for debugging and repository status. **SEARCH STRATEGY:** Single keywords ("bug", "feature"), then combine ("bug fix"), never complex. **SEARCH MODES:** - Global search (no owner): Searches issues across all GitHub repositories - Scoped search (with owner): Targeted search within specific organization/user **PROBLEM HIERARCHY:** "React auth JWT error" → "authentication" → "React" → "token expired" → "JWT" **PAGINATION LIMITATION:** GitHub CLI limited to --limit parameter only (no page navigation). **RESULT TARGETS:** 0 → broader terms, 1-20 IDEAL, 100+ → add specific terms/filters`, [TOOL_NAMES.GITHUB_SEARCH_PULL_REQUESTS]: `**Implementation analysis** - PR search for patterns and repository status. **CORE APPLICATIONS:** Code review insights, feature implementation tracking, repository activity assessment. **KEY FILTERS:** State (open/closed), draft (false for completed), author/reviewer, language **PAGINATION LIMITATION:** GitHub CLI limited to --limit parameter only (no page navigation). **QUALITY FOCUS:** Use review-related filters for thoroughly vetted code examples`, [TOOL_NAMES.GITHUB_SEARCH_COMMITS]: `**Development history** - Track code evolution and repository status. **SEARCH STRATEGY:** Start minimal ("fix", "feature", "update") with owner/repo, progressive expansion. **LIMITATIONS:** Large organizations may return org-wide results, requires text terms. GitHub CLI limited to --limit parameter only (no page navigation). **ERROR HANDLING:** "Search text required" → Use minimal keywords ("fix", "update")`, [TOOL_NAMES.GITHUB_SEARCH_USERS]: `**Developer discovery** - Find experts and community leaders. **SEARCH METHODOLOGY:** Technology terms ("react", "python") → add context (location, experience) → specialized search. **SEARCH MODES:** - Global search (no owner): Searches users/orgs across all GitHub - Scoped search (with owner): Targeted search within specific organization context **KEY FILTERS:** Type (user/org), location, language, followers (">100" influential), repos (">10" active) **DISCOVERY PATTERNS:** Technology experts, local developers, open source contributors, industry leaders`, [TOOL_NAMES.GITHUB_SEARCH_REPOS]: `**Universal Project Discovery Engine** - Intelligent repository search with semantic understanding across all domains and disciplines. **🧠 SEMANTIC PROJECT INTELLIGENCE:** - **DOMAIN-ADAPTIVE DISCOVERY**: Automatically detects query intent and adapts search strategy - **UNIVERSAL PROJECT TYPES**: Finds software, research, creative, educational, business, and community projects - **CONTEXTUAL UNDERSTANDING**: Provides domain-specific insights and recommendations - **CROSS-DISCIPLINARY EXPLORATION**: Discovers projects spanning multiple fields and interests **🎯 ADAPTIVE PROJECT DISCOVERY:** - **TECHNOLOGY PROJECTS** → Software, tools, frameworks, applications, systems - **RESEARCH PROJECTS** → Academic studies, experiments, data analysis, methodologies - **CREATIVE PROJECTS** → Art, design, media, content, artistic expressions - **EDUCATIONAL PROJECTS** → Learning resources, tutorials, courses, documentation - **BUSINESS PROJECTS** → Solutions, automation, analytics, productivity tools - **COMMUNITY PROJECTS** → Open source, collaboration, social impact, activism **🚀 INTELLIGENT SEARCH STRATEGIES:** 1. **Single Terms**: "visualization", "sustainability", "automation", "creativity" 2. **Domain-Specific**: Add context filters based on detected field 3. **Quality Indicators**: Star count, activity level, community engagement 4. **Scope Management**: Global discovery vs. targeted organizational search **💡 UNIVERSAL PROJECT PATTERNS:** - **"data visualization"** → Charts, dashboards, plotting, analytics projects - **"sustainability"** → Environmental, green-tech, climate, conservation projects - **"education"** → Learning platforms, tutorials, courses, knowledge sharing - **"automation"** → Workflow tools, productivity, efficiency, process optimization - **"creativity"** → Art tools, design systems, creative coding, expression platforms **🌍 CROSS-DOMAIN PROJECT TYPES:** - **RESEARCH REPOSITORIES**: Academic papers, datasets, experiments, methodologies - **CREATIVE PORTFOLIOS**: Art projects, design systems, media collections - **BUSINESS SOLUTIONS**: Analytics tools, automation scripts, productivity apps - **EDUCATIONAL RESOURCES**: Learning materials, tutorials, course content - **COMMUNITY INITIATIVES**: Open source projects, social impact, collaboration - **PERSONAL PROJECTS**: Individual explorations, experiments, learning journeys **⚡ SEARCH OPTIMIZATION STRATEGIES:** - **0 results** → Broader terms, alternative approaches, ecosystem exploration - **1-20 results** → IDEAL scope for detailed analysis and comparison - **100+ results** → Add filters, narrow scope, focus on quality indicators - **Organizational scope** → Private/enterprise project discovery **🔧 INTELLIGENT FILTERING:** - **Quality Indicators**: Star count (>100 established, >10 active) - **Activity Level**: Recent updates, community engagement - **Project Maturity**: Development stage, documentation quality - **Domain Relevance**: Topic tags, description matching, content analysis **🔄 PROGRESSIVE DISCOVERY WORKFLOW:** 1. **Broad Exploration** → Map the project landscape in your domain 2. **Quality Filtering** → Focus on well-maintained, active projects 3. **Community Analysis** → Identify key contributors and organizations 4. **Feature Comparison** → Analyze capabilities and approaches 5. **Ecosystem Understanding** → See how projects relate and complement 6. **Selection Criteria** → Choose based on needs, quality, and fit **🎨 DOMAIN-SPECIFIC PROJECT DISCOVERY:** - **CREATIVE DOMAIN**: Art tools, design systems, media processing, creative coding - **BUSINESS DOMAIN**: Analytics, automation, productivity, management tools - **RESEARCH DOMAIN**: Data analysis, visualization, computation, methodology - **EDUCATIONAL DOMAIN**: Learning platforms, tutorials, knowledge sharing - **SOCIAL DOMAIN**: Community tools, activism, social impact, collaboration - **PERSONAL DOMAIN**: Productivity, wellness, lifestyle, skill development **🌟 UNIVERSAL APPLICATIONS:** - **Solution Discovery**: Find tools and projects for specific needs - **Research Exploration**: Locate academic and experimental projects - **Learning Resources**: Discover educational and tutorial projects - **Community Building**: Find collaborative and open source initiatives - **Innovation Inspiration**: Explore cutting-edge and experimental work - **Quality Assessment**: Compare approaches, features, and implementations **🔍 FALLBACK STRATEGIES:** When repository search yields insufficient results: 1. **Package Discovery** → Find related tools and libraries 2. **Topic Exploration** → Understand domain terminology and trends 3. **Content Search** → Look for implementations and usage patterns 4. **Community Discovery** → Find experts and organizations 5. **Discussion Mining** → Explore problems and solutions 6. **Cross-Domain Bridging** → Look in adjacent fields and applications **INPUT**: Any project need, concept, or area of interest across any domain **OUTPUT**: Comprehensive project landscape with quality insights and recommendations`, // Focused NPM tools for minimal token usage [TOOL_NAMES.NPM_GET_REPOSITORY]: `**Repository discovery** - Extract GitHub repository URL and project description. **MINIMAL OUTPUT:** Package name, description, repository URL, homepage - optimized for token efficiency. **WHEN TO USE:** When you only need repository location for GitHub operations. **INTEGRATION:** Perfect first step → ${TOOL_NAMES.GITHUB_GET_REPOSITORY} → Code exploration`, [TOOL_NAMES.NPM_GET_DEPENDENCIES]: `**Dependency analysis** - Extract package dependencies tree. **MINIMAL OUTPUT:** Dependencies, devDependencies, resolutions - focused dependency data only. **WHEN TO USE:** When analyzing package ecosystem and compatibility. **INTEGRATION:** Combine with ${TOOL_NAMES.NPM_ANALYZE_DEPENDENCIES} for security audit`, [TOOL_NAMES.NPM_GET_BUGS]: `**Issue tracking** - Extract bug reporting information. **MINIMAL OUTPUT:** Package name and bugs URL - direct access to issue tracker. **WHEN TO USE:** When users need to report issues or check known problems. **INTEGRATION:** Links to ${TOOL_NAMES.GITHUB_SEARCH_ISSUES} for problem discovery`, [TOOL_NAMES.NPM_GET_README]: `**Documentation access** - Extract README filename information. **MINIMAL OUTPUT:** Package name and readme filename - efficient documentation lookup. **WHEN TO USE:** When users need documentation without full package metadata. **INTEGRATION:** Combine with ${TOOL_NAMES.GITHUB_GET_FILE_CONTENT} for full README content`, [TOOL_NAMES.NPM_GET_VERSIONS]: `**Official version tracking** - Extract production-ready semantic versions only. **MINIMAL OUTPUT:** Official versions (major.minor.patch format), latest version, count - excludes alpha/beta/rc versions. **WHEN TO USE:** Find stable versions for production deployment, analyze release cadence of stable releases. **INTEGRATION:** Perfect for production planning - filters out experimental versions for reliable deployment decisions`, [TOOL_NAMES.NPM_GET_AUTHOR]: `**Maintainer information** - Extract author and maintainer details. **MINIMAL OUTPUT:** Author and maintainers list - focused ownership data. **WHEN TO USE:** When users need to contact maintainers or assess project ownership. **INTEGRATION:** Links to ${TOOL_NAMES.GITHUB_SEARCH_USERS} for developer discovery`, [TOOL_NAMES.NPM_GET_LICENSE]: `**License compliance** - Extract package license information. **MINIMAL OUTPUT:** Package name and license - essential legal compliance data. **WHEN TO USE:** When users need quick license verification for legal compliance. **INTEGRATION:** Essential for enterprise package evaluation workflows`, [TOOL_NAMES.NPM_GET_HOMEPAGE]: `**Official documentation gateway** - Extract package homepage for comprehensive project resources. **MINIMAL OUTPUT:** Package name and homepage URL - direct access to live documentation, tutorials, and demos. **WHEN TO USE:** Access official docs, interactive examples, getting started guides, and project showcases. **INTEGRATION:** Complements ${TOOL_NAMES.NPM_GET_REPOSITORY} - homepage often contains better docs than README`, [TOOL_NAMES.NPM_GET_ID]: `**Precise package targeting** - Extract exact name@version for dependency management. **MINIMAL OUTPUT:** Package name and _id (name@latestVersion format) - canonical package identifier for lockfiles. **WHEN TO USE:** Pin exact versions, resolve dependency conflicts, generate package-lock entries, version compatibility checks. **INTEGRATION:** Critical for CI/CD pipelines, dependency auditing, and reproducible builds`, [TOOL_NAMES.NPM_GET_RELEASES]: `**Recent releases tracker** - Get latest release activity and timeline data. **MINIMAL OUTPUT:** Last modified, created date, version count, and last 10 releases - focused release intelligence. **WHEN TO USE:** Track recent package activity, analyze release frequency, check latest versions and release dates. **INTEGRATION:** Essential for monitoring package updates - combine with ${TOOL_NAMES.NPM_GET_VERSIONS} for comprehensive version analysis`, [TOOL_NAMES.NPM_GET_ENGINES]: `**Environment compatibility validator** - Prevent runtime conflicts before installation. **MINIMAL OUTPUT:** Node.js version requirements, npm constraints - environment compatibility matrix. **WHEN TO USE:** Pre-deployment validation, Docker image planning, Node.js upgrade decisions, CI/CD environment setup. **INTEGRATION:** Prevents deployment failures - use before installation in production environments`, [TOOL_NAMES.NPM_GET_EXPORTS]: `**Import path intelligence** - Discover available modules and import strategies. **MINIMAL OUTPUT:** Export mappings, entry points, submodule paths - complete import guide for developers. **WHEN TO USE:** Learn correct import syntax, discover tree-shakable exports, find submodules, optimize bundle size. **INTEGRATION:** CRITICAL for ${TOOL_NAMES.GITHUB_SEARCH_CODE} - enables precise code search with accurate import paths`, [TOOL_NAMES.API_STATUS_CHECK]: `**🛠️ CRITICAL FIRST STEP** - Comprehensive API readiness verification before research operations. **ESSENTIAL PRE-RESEARCH VALIDATION:** - **GitHub CLI Authentication**: Verifies user is logged in (gh auth status) - **NPM Registry Connectivity**: Confirms npm ping successful - **GitHub API Rate Limits**: Real-time quota analysis across all endpoints **🔍 COMPREHENSIVE HEALTH CHECK:** - **Authentication Status**: GitHub CLI login verification with username detection - **Network Connectivity**: NPM registry accessibility and response validation - **API Quota Analysis**: Core API, Search API, and Code Search remaining limits - **Reset Time Tracking**: When exhausted APIs will restore quota - **Usage Percentage**: Current consumption across all GitHub endpoints **⚡ INTELLIGENT RESEARCH STRATEGY:** - **Ready Status**: All systems operational for comprehensive research - **Limited Status**: Reduced capacity - targeted searches recommended - **Not Ready Status**: Authentication/quota issues require resolution **🎯 RESEARCH GUIDANCE BASED ON API LIMITS:** - **Code Search < 5**: Critical - use repository browsing instead of code search - **Search API < 20**: Limited - focus on specific repositories vs broad searches - **Core API < 200**: Constrained - minimize repository exploration operations - **NPM Disconnected**: GitHub-only research mode activated **🚀 SMART FALLBACK RECOMMENDATIONS:** - **Authentication Issues**: Step-by-step gh auth login guidance - **NPM Problems**: Alternative research paths using GitHub discovery - **Rate Limit Exhaustion**: Wait times and alternative approaches - **Network Issues**: Diagnostic commands and troubleshooting steps **📊 REAL-TIME API INTELLIGENCE:** - **Primary API**: Repository operations, issues, PRs, users (5000/hour) - **Search API**: Repository/user/topic searches (30/minute) - **Code Search**: Code content searches (10/minute) - most restrictive - **Reset Schedules**: Precise timestamps for quota restoration **✅ RESEARCH READINESS MATRIX:** - **READY**: GitHub authenticated + NPM connected + healthy API limits - **LIMITED**: Some constraints but research possible with guidance - **NOT_READY**: Critical issues blocking research operations **💡 PROACTIVE OPTIMIZATION:** - **API Usage Prediction**: Warns before hitting limits during extensive research - **Strategy Adaptation**: Automatically suggests efficient research patterns - **Resource Conservation**: Identifies when to use cached vs live data - **Batch Operation Planning**: Optimal timing for bulk research tasks **WHEN TO USE:** ALWAYS call first before starting any research session to ensure optimal tool usage and prevent operation failures. **INTEGRATION:** Sets research strategy for all subsequent GitHub and NPM tools based on current system status.`, }; const cache = new NodeCache({ stdTTL: 86400, // 24 hour cache checkperiod: 3600, // Check for expired keys every 1 hour }); function generateCacheKey(prefix, params) { const paramString = JSON.stringify(params, Object.keys(params).sort()); const hash = crypto.createHash('md5').update(paramString).digest('hex'); return `${prefix}:${hash}`; } async function withCache(cacheKey, operation) { // Check if result exists in cache const cachedResult = cache.get(cacheKey); if (cachedResult) { return cachedResult; } // Execute operation const result = await operation(); // Only cache successful responses if (!result.isError) { cache.set(cacheKey, result); } return result; } /** * Determines if a string needs quoting for GitHub search */ function needsQuoting(str) { return (str.includes(' ') || str.includes('"') || str.includes('\t') || str.includes('\n') || str.includes('\r') || /[<>(){}[\]\\|&;]/.test(str)); } function createSuccessResult$1(data) { return { content: [ { type: 'text', text: JSON.stringify(data, null, 2), }, ], isError: false, }; } function createErrorResult$1(message, error) { return { content: [ { type: 'text', text: `${message}: ${error.message}`, }, ], isError: true, }; } const safeExecAsync = promisify(exec); const ALLOWED_NPM_COMMANDS = [ 'view', 'search', 'ping', 'whoami', 'version', 'config', 'audit', 'list', 'outdated', 'help', ]; const ALLOWED_GH_COMMANDS = [ 'search', 'repo', 'api', 'auth', 'org', 'help', ]; function createSuccessResult(data) { return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], isError: false, }; } function createErrorResult(message, error) { return { content: [ { type: 'text', text: `${message}: ${error.message}` }, ], isError: true, }; } function isValidNpmCommand(command) { return ALLOWED_NPM_COMMANDS.includes(command); } function isValidGhCommand(command) { return ALLOWED_GH_COMMANDS.includes(command); } async function executeNpmCommand(command, args = [], options = {}) { // Only allow registered commands if (!isValidNpmCommand(command)) { return createErrorResult('Command not registered', new Error(`NPM command '${command}' is not in the allowed list`)); } const fullCommand = `npm ${command} ${args.join(' ')}`; const executeCommand = async () => { try { const execOptions = { timeout: options.timeout || 30000, cwd: options.cwd, env: { ...process.env, ...options.env }, encoding: 'utf-8', }; const { stdout, stderr } = await safeExecAsync(fullCommand, execOptions); if (stderr && !stderr.includes('npm WARN')) { return createErrorResult('NPM command error', new Error(stderr)); } return createSuccessResult({ command: fullCommand, result: stdout, timestamp: new Date().toISOString(), type: 'npm', }); } catch (error) { return createErrorResult('Failed to execute NPM command', error); } }; if (options.cache) { const cacheKey = generateCacheKey('npm-exec', { command, args }); return withCache(cacheKey, executeCommand); } return executeCommand(); } async function executeGitHubCommand(command, args = [], options = {}) { // Only allow registered commands if (!isValidGhCommand(command)) { return createErrorResult('Command not registered', new Error(`GitHub command '${command}' is not in the allowed list`)); } const fullCommand = `gh ${command} ${args.join(' ')}`; const executeCommand = async () => { try { const execOptions = { timeout: options.timeout || 60000, cwd: options.cwd, env: { ...process.env, ...options.env }, encoding: 'utf-8', }; const { stdout, stderr } = await safeExecAsync(fullCommand, execOptions); if (stderr) { return createErrorResult('GitHub CLI command error', new Error(stderr)); } return createSuccessResult({ command: fullCommand, result: stdout, timestamp: new Date().toISOString(), type: 'github', }); } catch (error) { return createErrorResult('Failed to execute GitHub CLI command', error); } }; if (options.cache) { const cacheKey = generateCacheKey('gh-exec', { command, args }); return withCache(cacheKey, executeCommand); } return executeComm