1.0.3 • Published 8 months ago

@amr.manojkumar/test-project v1.0.3

Weekly downloads
-
License
MIT
Repository
github
Last release
8 months ago

GitHub MCP Client

A Node.js client library for Model Context Protocol (MCP) with GitHub integration. This package allows you to build AI-powered applications that can interact with GitHub repositories, pull requests, issues, and more through the Model Context Protocol.

Installation

npm install github-mcp-client

Features

  • Seamless integration with GitHub API via MCP
  • Support for various GitHub operations (repositories, branches, PRs, issues, etc.)
  • Multiple client classes for different use cases
  • TypeScript support with full type definitions
  • Context-aware AI interactions
  • Customizable tool registry for extending functionality

Quick Start

import { MCPHost } from 'github-mcp-client';
import dotenv from 'dotenv';

// Load environment variables
dotenv.config();

async function main() {
  // Create an instance of MCPHost
  const host = MCPHost.getInstance({
    serverUrl: process.env.MCP_SERVER_URL || 'http://localhost:3005/mcp',
    openaiApiKey: process.env.OPENAI_API_KEY,
    model: 'gpt-4o-mini',
    temperature: 0.7,
    maxTokens: 1500
  });

  // Initialize the host
  await host.initialize();

  // Define system context for the AI
  const systemContext = `You are a GitHub automation assistant.
  You can help with various GitHub tasks like creating repositories,
  branches, and pull requests.`;

  // Execute a task
  const result = await host.executeTask(
    "Create a new branch called 'feature/add-login' in the repository 'owner/repo'",
    systemContext
  );

  console.log('Task executed:', result);

  // Disconnect when done
  await host.disconnect();
}

main().catch(console.error);

Integration with Express.js

Here's how to use the GitHub MCP Client in an Express.js middleware:

import express from 'express';
import { MCPHost } from 'github-mcp-client';
import dotenv from 'dotenv';

dotenv.config();

const app = express();
app.use(express.json());

// Create and initialize the MCP host
const host = MCPHost.getInstance({
  serverUrl: process.env.MCP_SERVER_URL,
  openaiApiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-4o-mini',
  temperature: 0.7,
  maxTokens: 1500
});

// Initialize host when the server starts
(async () => {
  try {
    await host.initialize();
    console.log('MCP Host initialized successfully');
  } catch (error) {
    console.error('Failed to initialize MCP Host:', error);
    process.exit(1);
  }
})();

// Example middleware for GitHub automation
app.post('/api/github/automate', async (req, res) => {
  try {
    const { task, context } = req.body;
    
    if (!task) {
      return res.status(400).json({ error: 'Task is required' });
    }
    
    const defaultContext = `You are a GitHub automation assistant helping with repository tasks.`;
    const result = await host.executeTask(task, context || defaultContext);
    
    res.json(result);
  } catch (error) {
    console.error('Error executing task:', error);
    res.status(500).json({ error: 'Failed to execute task' });
  }
});

// Integration with React frontend
app.post('/api/github/analyze', async (req, res) => {
  try {
    const { repositoryUrl, question } = req.body;
    
    if (!repositoryUrl || !question) {
      return res.status(400).json({ error: 'Repository URL and question are required' });
    }
    
    // Extract owner and repo from URL
    const urlParts = repositoryUrl.split('/');
    const owner = urlParts[urlParts.length - 2];
    const repo = urlParts[urlParts.length - 1];
    
    const context = `You are analyzing the GitHub repository ${owner}/${repo}.
    Answer the following question based on the repository contents.`;
    
    const result = await host.executeTask(question, context);
    
    res.json(result);
  } catch (error) {
    console.error('Error analyzing repository:', error);
    res.status(500).json({ error: 'Failed to analyze repository' });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

React.js Integration Example

Here's a simple React component that interacts with the Express middleware:

import React, { useState } from 'react';
import axios from 'axios';

function GitHubAutomation() {
  const [task, setTask] = useState('');
  const [result, setResult] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    setError('');
    
    try {
      const response = await axios.post('/api/github/automate', { 
        task,
        context: 'You are helping to automate GitHub tasks efficiently and accurately.'
      });
      
      setResult(response.data);
    } catch (err) {
      setError(err.response?.data?.error || 'An error occurred');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className="github-automation">
      <h2>GitHub Automation</h2>
      <form onSubmit={handleSubmit}>
        <div className="form-group">
          <label htmlFor="task">Describe your GitHub task:</label>
          <textarea
            id="task"
            value={task}
            onChange={(e) => setTask(e.target.value)}
            rows={4}
            className="form-control"
            placeholder="E.g., Create a branch named 'feature/user-auth' in repository 'myorg/myrepo'"
            required
          />
        </div>
        <button type="submit" className="btn btn-primary" disabled={loading}>
          {loading ? 'Processing...' : 'Execute Task'}
        </button>
      </form>
      
      {error && <div className="alert alert-danger mt-3">{error}</div>}
      
      {result && (
        <div className="result mt-4">
          <h3>Task Results:</h3>
          <pre>{JSON.stringify(result, null, 2)}</pre>
        </div>
      )}
    </div>
  );
}

export default GitHubAutomation;

Advanced Usage

For more advanced use cases, the library provides specialized host classes:

EnhancedMCPHost

import { EnhancedMCPHost } from 'github-mcp-client';

const host = EnhancedMCPHost.getInstance({
  serverUrl: process.env.MCP_SERVER_URL,
  openaiApiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-4o-mini',
  temperature: 0.7,
  maxTokens: 1500
});

await host.initialize();

// Execute with base context and additional task-specific context
const result = await host.executeTask(
  "Update the README.md file",
  "You are a technical writer assisting with documentation.",
  "The README should include installation instructions and usage examples."
);

ContextAwareMcpHost

import { ContextAwareMcpHost, ContextPriority } from 'github-mcp-client';

const host = ContextAwareMcpHost.getInstance({
  serverUrl: process.env.MCP_SERVER_URL,
  openaiApiKey: process.env.OPENAI_API_KEY,
  model: 'gpt-4o-mini',
  temperature: 0.7,
  maxTokens: 1500,
  maxContextSize: 90000,
  includePreviousResults: true
});

await host.initialize();

// Set system context
host.setSystemContext("You are a code review assistant.");

// Add file context
host.addFileContext(
  "src/components/Button.tsx",
  "// Button component code...",
  ContextPriority.HIGH
);

// Execute a task with the accumulated context
const result = await host.executeTask(
  "Review the Button component and suggest improvements."
);

MCP Server

This client library requires an MCP server to function. You can set up your own MCP server or use a hosted solution. Refer to the MCP documentation for more details on server setup.

Environment Variables

The library uses the following environment variables:

  • MCP_SERVER_URL: URL of the MCP server
  • OPENAI_API_KEY: API key for OpenAI

License

MIT