File size: 11,333 Bytes
cf1146d
 
77a6957
cf1146d
 
 
e196851
cf1146d
a2c5052
 
a9aa3fa
3bfea7d
a2c5052
abce07a
3bfea7d
1b3f5fd
abce07a
 
cf1146d
a2c5052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
559bce8
abce07a
559bce8
 
 
a2c5052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf1146d
a2c5052
 
 
 
 
 
 
 
6af1f7e
a2c5052
cf1146d
a2c5052
abce07a
a2c5052
 
 
 
a9aa3fa
cf1146d
 
a2c5052
 
 
 
1b3f5fd
a2c5052
abce07a
a2c5052
 
 
 
 
 
cf1146d
 
 
 
 
a2c5052
cf1146d
 
 
a2c5052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf1146d
 
 
a2c5052
abce07a
 
 
a2c5052
 
 
 
 
 
 
 
 
 
 
6af1f7e
a2c5052
6af1f7e
cf1146d
a2c5052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf1146d
a2c5052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cf1146d
a2c5052
 
 
 
 
cf1146d
 
a2c5052
 
 
 
cf1146d
a2c5052
 
 
cf1146d
 
a9aa3fa
a2c5052
cf1146d
a2c5052
 
 
cf1146d
 
 
a2c5052
 
77a6957
a2c5052
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
const express = require('express');
const cors = require('cors');
// Dynamic import for node-fetch
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

const app = express();
const PORT = process.env.PORT || 7860;

// --- 1. CONFIGURATION ---
app.set('trust proxy', 1); // Required for HF Spaces
app.use(express.json({ limit: '10mb' }));

// --- 2. CORS (Global) ---
app.use(cors({
  origin: '*',
  methods: ['POST', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'MCP-Protocol-Version'],
}));

// --- 3. AUTH MIDDLEWARE ---
// Secures the MCP server so only you (via Gemini CLI) can use it.
const authMiddleware = (req, res, next) => {
  const expectedSecret = process.env.MCP_AUTH_TOKEN;
  
  // If no secret is set in env, allow open access (Warning logged)
  if (!expectedSecret) {
    // console.warn("[WARN] No MCP_AUTH_TOKEN set. Server is open.");
    return next();
  }

  const authHeader = req.headers['authorization'];
  if (!authHeader || !authHeader.startsWith('Bearer ') || authHeader.split(' ')[1] !== expectedSecret) {
    console.error(`[AUTH] Unauthorized access attempt`);
    return res.status(401).json({
      jsonrpc: "2.0",
      id: null,
      error: { code: -32000, message: "Unauthorized: Invalid or missing MCP_AUTH_TOKEN" }
    });
  }
  next();
};

// --- 4. LOGGING ---
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
});

// --- 5. GITHUB API HELPER ---
const callGitHub = async (endpoint, method = 'GET', body = null) => {
  const token = process.env.GH_TOKEN;
  if (!token) throw new Error("Server configuration error: GH_TOKEN is missing.");

  const url = endpoint.startsWith('http') ? endpoint : `https://api.github.com${endpoint}`;
  
  const headers = {
    'Authorization': `Bearer ${token}`,
    'Accept': 'application/vnd.github.v3+json',
    'User-Agent': 'HuggingFace-MCP-Server',
    'X-GitHub-Api-Version': '2022-11-28'
  };

  const options = {
    method,
    headers,
    body: body ? JSON.stringify(body) : undefined
  };

  const response = await fetch(url, options);

  if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`GitHub API ${response.status}: ${errorText}`);
  }

  return response.json();
};

// --- 6. MAIN MCP ENDPOINT ---
app.post('/mcp', authMiddleware, async (req, res) => {
  try {
    const { id, method, params } = req.body;
    const requestId = id !== undefined ? id : null;

    // Helper to send success
    const send = (result) => res.json({ jsonrpc: "2.0", id: requestId, result });
    
    // Helper to send error
    const error = (code, msg) => res.json({ jsonrpc: "2.0", id: requestId, error: { code, message: msg } });

    console.log(`[POST] Method: ${method}`);

    // --- A. HANDSHAKE & LIFECYCLE ---
    if (method === 'initialize') {
      return send({
        protocolVersion: "2024-11-05",
        capabilities: { tools: {}, resources: {}, prompts: {} },
        serverInfo: { name: "github-mcp-versatile", version: "2.0.0" }
      });
    }

    if (method === 'notifications/initialized') return send(true);
    
    // Crucial for Gemini CLI connection stability
    if (method === 'ping') return send({});

    // --- B. TOOL LIST ---
    if (method === 'tools/list') {
      return send({
        tools: [
          // 1. ISSUES
          {
            name: "list_issues",
            description: "List issues in a repo.",
            inputSchema: {
              type: "object",
              properties: {
                owner: { type: "string" },
                repo: { type: "string" },
                state: { type: "string", enum: ["open", "closed", "all"], default: "open" }
              },
              required: ["owner", "repo"]
            }
          },
          {
            name: "create_issue",
            description: "Create a new issue.",
            inputSchema: {
              type: "object",
              properties: {
                owner: { type: "string" },
                repo: { type: "string" },
                title: { type: "string" },
                body: { type: "string" }
              },
              required: ["owner", "repo", "title"]
            }
          },
          // 2. FILES & CODE
          {
            name: "read_file",
            description: "Read the contents of a specific file.",
            inputSchema: {
              type: "object",
              properties: {
                owner: { type: "string" },
                repo: { type: "string" },
                path: { type: "string", description: "Path to file (e.g. src/index.js)" },
                branch: { type: "string", description: "Branch or commit SHA (default: main)" }
              },
              required: ["owner", "repo", "path"]
            }
          },
          {
            name: "list_files",
            description: "Get the file tree (recursive) to understand repo structure.",
            inputSchema: {
              type: "object",
              properties: {
                owner: { type: "string" },
                repo: { type: "string" },
                branch: { type: "string", default: "main" },
                recursive: { type: "boolean", default: true }
              },
              required: ["owner", "repo"]
            }
          },
          {
            name: "search_code",
            description: "Search for code within a repository.",
            inputSchema: {
              type: "object",
              properties: {
                q: { type: "string", description: "Search query (e.g. 'function login')" },
                owner: { type: "string" },
                repo: { type: "string" }
              },
              required: ["q", "owner", "repo"]
            }
          },
          // 3. PULL REQUESTS
          {
            name: "list_prs",
            description: "List Pull Requests.",
            inputSchema: {
              type: "object",
              properties: {
                owner: { type: "string" },
                repo: { type: "string" },
                state: { type: "string", enum: ["open", "closed", "all"], default: "open" }
              },
              required: ["owner", "repo"]
            }
          },
          {
            name: "create_pr",
            description: "Create a Pull Request.",
            inputSchema: {
              type: "object",
              properties: {
                owner: { type: "string" },
                repo: { type: "string" },
                title: { type: "string" },
                head: { type: "string", description: "The name of the branch where your changes are implemented." },
                base: { type: "string", description: "The name of the branch you want the changes pulled into." },
                body: { type: "string" }
              },
              required: ["owner", "repo", "title", "head", "base"]
            }
          }
        ]
      });
    }

    // --- C. TOOL EXECUTION ---
    if (method === 'tools/call') {
      const { name, arguments: args } = params || {};
      
      try {
        let resultData;

        // --- Logic: ISSUES ---
        if (name === "list_issues") {
          const data = await callGitHub(`/repos/${args.owner}/${args.repo}/issues?state=${args.state || 'open'}&per_page=10`);
          resultData = data.map(i => ({ number: i.number, title: i.title, state: i.state, url: i.html_url }));
        }
        else if (name === "create_issue") {
          const data = await callGitHub(`/repos/${args.owner}/${args.repo}/issues`, 'POST', {
            title: args.title, body: args.body
          });
          resultData = { message: "Issue Created", url: data.html_url, number: data.number };
        }

        // --- Logic: FILES ---
        else if (name === "read_file") {
          // GitHub API returns content in Base64
          const ref = args.branch ? `?ref=${args.branch}` : '';
          const data = await callGitHub(`/repos/${args.owner}/${args.repo}/contents/${args.path}${ref}`);
          
          if (Array.isArray(data)) return error(-32000, "Path is a directory, not a file.");
          if (!data.content) return error(-32000, "File content empty or binary.");

          const decodedContent = Buffer.from(data.content, 'base64').toString('utf-8');
          // Truncate if huge to save tokens
          const safeContent = decodedContent.length > 20000 ? decodedContent.substring(0, 20000) + "\n...[Truncated]" : decodedContent;
          resultData = safeContent;
        }
        else if (name === "list_files") {
          const ref = args.branch || 'main';
          // Get the tree SHA first, or just assume main/master
          // To be simple, we use the trees API which requires the SHA of the branch.
          // Fallback: Use the 'contents' API recursively? No, that's heavy.
          // Better approach for LLM: Get the HEAD commit SHA first.
          
          // 1. Get Branch SHA
          const branchData = await callGitHub(`/repos/${args.owner}/${args.repo}/git/ref/heads/${ref}`);
          const sha = branchData.object.sha;

          // 2. Get Tree
          const recursive = args.recursive ? '?recursive=1' : '';
          const treeData = await callGitHub(`/repos/${args.owner}/${args.repo}/git/trees/${sha}${recursive}`);
          
          // Filter to just paths to save tokens
          resultData = treeData.tree.map(t => t.path).slice(0, 200); // Limit to 200 files
        }
        else if (name === "search_code") {
          const q = `${args.q} repo:${args.owner}/${args.repo}`;
          const data = await callGitHub(`/search/code?q=${encodeURIComponent(q)}&per_page=5`);
          resultData = data.items.map(i => ({ name: i.name, path: i.path, url: i.html_url }));
        }

        // --- Logic: PULL REQUESTS ---
        else if (name === "list_prs") {
          const data = await callGitHub(`/repos/${args.owner}/${args.repo}/pulls?state=${args.state || 'open'}&per_page=10`);
          resultData = data.map(i => ({ number: i.number, title: i.title, state: i.state, url: i.html_url }));
        }
        else if (name === "create_pr") {
          const data = await callGitHub(`/repos/${args.owner}/${args.repo}/pulls`, 'POST', {
            title: args.title, head: args.head, base: args.base, body: args.body
          });
          resultData = { message: "PR Created", url: data.html_url, number: data.number };
        }
        
        else {
          return error(-32601, `Tool ${name} not found`);
        }

        // Return Standard Success Response
        return send({
          content: [{ type: "text", text: typeof resultData === 'string' ? resultData : JSON.stringify(resultData, null, 2) }],
          isError: false
        });

      } catch (err) {
        return error(-32000, `Execution Error: ${err.message}`);
      }
    }

    return error(-32601, "Method not found");

  } catch (err) {
    console.error(err);
    res.status(500).json({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal Server Error" } });
  }
});

// 7. HEALTH CHECK
app.use((req, res) => res.status(200).send("GitHub MCP Active"));

app.listen(PORT, '0.0.0.0', () => console.log(`Server running on ${PORT}`));