-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
649 lines (565 loc) · 20.8 KB
/
server.ts
File metadata and controls
649 lines (565 loc) · 20.8 KB
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
#!/usr/bin/env bun
/**
* GitHub Channel — GitHub notifications for Claude Code
*
* An MCP channel plugin that polls the GitHub REST API for events
* (pushes, PRs, workflow runs, issues) and delivers them as channel
* notifications to Claude Code sessions.
*
* Usage:
* # In .mcp.json:
* { "command": "bun", "args": ["vendor/bearly/tools/github-channel.ts"] }
*
* # With options:
* bun vendor/bearly/tools/github-channel.ts --repos beorn/km --poll-interval 30
*
* # Launch Claude Code with the channel:
* claude --dangerously-load-development-channels server:github
*/
import { Server } from "@modelcontextprotocol/sdk/server/index.js"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { ListToolsRequestSchema, CallToolRequestSchema } from "@modelcontextprotocol/sdk/types.js"
import { execSync } from "node:child_process"
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"
import { dirname, resolve } from "node:path"
import { parseArgs } from "node:util"
// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------
const { values: args } = parseArgs({
options: {
repos: { type: "string", default: process.env.GITHUB_REPOS },
"poll-interval": { type: "string", default: process.env.GITHUB_POLL_INTERVAL ?? "30" },
events: { type: "string", default: process.env.GITHUB_EVENTS ?? "push,workflow_run,pull_request,issues" },
},
strict: false,
})
const POLL_INTERVAL_SEC = parseInt(String(args["poll-interval"]), 10) || 30
const EVENT_TYPES = String(args.events ?? "push,workflow_run,pull_request,issues")
.split(",")
.filter(Boolean)
// ---------------------------------------------------------------------------
// GitHub auth
// ---------------------------------------------------------------------------
function getGitHubToken(): string {
if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN
try {
return execSync("gh auth token", { encoding: "utf-8" }).trim()
} catch {
throw new Error("No GITHUB_TOKEN env var and `gh auth token` failed. Set GITHUB_TOKEN or run `gh auth login`.")
}
}
const GITHUB_TOKEN = getGitHubToken()
const GITHUB_HEADERS = {
Authorization: `Bearer ${GITHUB_TOKEN}`,
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"User-Agent": "bearly-github-channel/0.1.0",
}
// ---------------------------------------------------------------------------
// Repo detection
// ---------------------------------------------------------------------------
function detectRepoFromGit(): string | null {
try {
const url = execSync("git remote get-url origin", { encoding: "utf-8" }).trim()
// Handle SSH: git@github.com:owner/repo.git
const sshMatch = url.match(/github\.com[:/](.+?)(?:\.git)?$/)
if (sshMatch) return sshMatch[1] ?? null
// Handle HTTPS: https://github.com/owner/repo.git
const httpsMatch = url.match(/github\.com\/(.+?)(?:\.git)?$/)
if (httpsMatch) return httpsMatch[1] ?? null
} catch {
// Not a git repo or no remote
}
return null
}
function getRepos(): string[] {
if (args.repos) return String(args.repos).split(",").filter(Boolean)
const detected = detectRepoFromGit()
if (detected) return [detected]
throw new Error("No --repos specified and could not auto-detect from git remote. Pass --repos owner/repo.")
}
const REPOS = getRepos()
// ---------------------------------------------------------------------------
// Cursor persistence
// ---------------------------------------------------------------------------
function findBeadsDir(): string {
let dir = process.cwd()
while (dir !== "/") {
const candidate = resolve(dir, ".beads")
if (existsSync(candidate)) return candidate
dir = dirname(dir)
}
const fallback = resolve(process.cwd(), ".beads")
mkdirSync(fallback, { recursive: true })
return fallback
}
const CURSOR_PATH = resolve(findBeadsDir(), "github-cursor.json")
interface CursorState {
// Per-repo last-seen event ID
repos: Record<string, { lastEventId: string; lastPollAt: string }>
}
function loadCursor(): CursorState {
try {
if (existsSync(CURSOR_PATH)) {
return JSON.parse(readFileSync(CURSOR_PATH, "utf-8")) as CursorState
}
} catch {
// Corrupt file — start fresh
}
return { repos: {} }
}
function saveCursor(state: CursorState): void {
writeFileSync(CURSOR_PATH, JSON.stringify(state, null, 2))
}
const cursorState = loadCursor()
// ---------------------------------------------------------------------------
// GitHub API helpers
// ---------------------------------------------------------------------------
interface GitHubEvent {
id: string
type: string
actor: { login: string }
repo: { name: string }
payload: Record<string, unknown>
created_at: string
}
interface WorkflowRun {
id: number
name: string
status: string
conclusion: string | null
html_url: string
head_branch: string
head_sha: string
run_number: number
created_at: string
updated_at: string
actor: { login: string }
}
interface PullRequest {
number: number
title: string
state: string
html_url: string
user: { login: string }
draft: boolean
created_at: string
updated_at: string
head: { ref: string }
base: { ref: string }
requested_reviewers: Array<{ login: string }>
mergeable_state?: string
}
async function ghFetch<T>(path: string): Promise<T> {
const url = path.startsWith("https://") ? path : `https://api.github.com${path}`
const res = await fetch(url, { headers: GITHUB_HEADERS })
if (!res.ok) {
const body = await res.text()
throw new Error(`GitHub API ${res.status}: ${body.slice(0, 200)}`)
}
return res.json() as Promise<T>
}
async function fetchRepoEvents(repo: string): Promise<GitHubEvent[]> {
return ghFetch<GitHubEvent[]>(`/repos/${repo}/events?per_page=30`)
}
async function fetchWorkflowRuns(repo: string, status?: string): Promise<WorkflowRun[]> {
const params = new URLSearchParams({ per_page: "20" })
if (status) params.set("status", status)
const data = await ghFetch<{ workflow_runs: WorkflowRun[] }>(`/repos/${repo}/actions/runs?${params}`)
return data.workflow_runs
}
async function fetchOpenPRs(repo: string): Promise<PullRequest[]> {
return ghFetch<PullRequest[]>(`/repos/${repo}/pulls?state=open&per_page=20&sort=updated&direction=desc`)
}
// ---------------------------------------------------------------------------
// Event formatting
// ---------------------------------------------------------------------------
function formatEvent(event: GitHubEvent): { line: string; type: string; url: string } | null {
const actor = event.actor.login
const repo = event.repo.name
const payload = event.payload
switch (event.type) {
case "PushEvent": {
if (!EVENT_TYPES.includes("push")) return null
const commits = payload.commits as Array<{ sha: string; message: string }> | undefined
const count = (payload.size as number) ?? commits?.length ?? 0
const branch = (payload.ref as string)?.replace("refs/heads/", "") ?? "unknown"
const lastMsg = commits?.[commits.length - 1]?.message?.split("\n")[0] ?? ""
const url = `https://github.com/${repo}/compare/${(payload.before as string)?.slice(0, 7)}...${(payload.head as string)?.slice(0, 7)}`
return {
line: `${actor} pushed ${count} commit${count !== 1 ? "s" : ""} to ${branch} — ${lastMsg}`,
type: "push",
url,
}
}
case "PullRequestEvent": {
if (!EVENT_TYPES.includes("pull_request")) return null
const pr = payload.pull_request as { number: number; title: string; html_url: string } | undefined
const action = payload.action as string
if (!pr) return null
return {
line: `[pr] ${actor} ${action} PR #${pr.number}: ${pr.title}`,
type: "pr",
url: pr.html_url,
}
}
case "PullRequestReviewEvent": {
if (!EVENT_TYPES.includes("pull_request")) return null
const review = payload.review as { state: string; html_url: string } | undefined
const prNum = (payload.pull_request as { number: number })?.number
const prTitle = (payload.pull_request as { title: string })?.title
if (!review) return null
return {
line: `[review] ${actor} ${review.state} review on PR #${prNum}: ${prTitle}`,
type: "pr",
url: review.html_url,
}
}
case "PullRequestReviewCommentEvent": {
if (!EVENT_TYPES.includes("pull_request")) return null
const comment = payload.comment as { html_url: string; body: string } | undefined
const prNumC = (payload.pull_request as { number: number })?.number
if (!comment) return null
const body = (comment.body.split("\n")[0] ?? "").slice(0, 80)
return {
line: `[pr-comment] ${actor} commented on PR #${prNumC}: ${body}`,
type: "pr",
url: comment.html_url,
}
}
case "IssuesEvent": {
if (!EVENT_TYPES.includes("issues")) return null
const issue = payload.issue as { number: number; title: string; html_url: string } | undefined
const issueAction = payload.action as string
if (!issue) return null
return {
line: `[issue] ${actor} ${issueAction} #${issue.number}: ${issue.title}`,
type: "issue",
url: issue.html_url,
}
}
case "IssueCommentEvent": {
if (!EVENT_TYPES.includes("issues")) return null
const issueC = payload.issue as { number: number; title: string } | undefined
const commentC = payload.comment as { html_url: string; body: string } | undefined
if (!issueC || !commentC) return null
const bodyC = (commentC.body.split("\n")[0] ?? "").slice(0, 80)
return {
line: `[issue-comment] ${actor} on #${issueC.number}: ${bodyC}`,
type: "issue",
url: commentC.html_url,
}
}
default:
return null
}
}
// ---------------------------------------------------------------------------
// Recent events buffer (for github_status tool)
// ---------------------------------------------------------------------------
interface RecentEvent {
repo: string
line: string
type: string
url: string
ts: string
}
const recentEvents: RecentEvent[] = []
const MAX_RECENT = 50
function addRecentEvent(event: RecentEvent): void {
recentEvents.unshift(event)
if (recentEvents.length > MAX_RECENT) recentEvents.length = MAX_RECENT
}
// ---------------------------------------------------------------------------
// MCP Server
// ---------------------------------------------------------------------------
const instructions = `GitHub notifications arrive as <channel source="github" type="push|pr|workflow|issue" repo="..." url="...">.
This channel monitors GitHub for:
- **Push events** — new commits pushed to branches
- **Workflow runs** — CI/CD completions (especially failures)
- **Pull request activity** — opened, merged, review requested, comments
- **Issue activity** — opened, closed, assigned, commented
Use the tools to query GitHub directly:
- \`github_status\` — recent events summary
- \`github_runs\` — workflow runs (filter by status: failure, success, in_progress)
- \`github_prs\` — open PRs with review status
Repos being monitored: ${REPOS.join(", ")}
React to workflow failures immediately — they likely need attention. PR reviews and comments
may need a response. Push events are informational unless they conflict with your current work.`
const mcp = new Server(
{ name: "events", version: "0.1.0" },
{
capabilities: {
experimental: { "claude/channel": {} },
tools: {},
},
instructions,
},
)
// ---------------------------------------------------------------------------
// Tools
// ---------------------------------------------------------------------------
mcp.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: "github_status",
description: "Show recent GitHub events summary across monitored repos",
inputSchema: {
type: "object" as const,
properties: {
repo: { type: "string", description: "Filter to specific repo (owner/name)" },
limit: { type: "number", description: "Max events to show (default: 20)" },
},
},
},
{
name: "github_runs",
description: "List recent workflow runs with status/conclusion",
inputSchema: {
type: "object" as const,
properties: {
repo: { type: "string", description: "Repo to query (default: first monitored repo)" },
status: {
type: "string",
description: "Filter by status",
enum: ["completed", "in_progress", "queued", "failure", "success"],
},
limit: { type: "number", description: "Max runs to show (default: 10)" },
},
},
},
{
name: "github_prs",
description: "List open PRs with review status",
inputSchema: {
type: "object" as const,
properties: {
repo: { type: "string", description: "Repo to query (default: first monitored repo)" },
},
},
},
],
}))
mcp.setRequestHandler(CallToolRequestSchema, async (req) => {
const { name, arguments: toolArgs } = req.params
const a = (toolArgs ?? {}) as Record<string, unknown>
switch (name) {
case "github_status": {
const limit = (a.limit as number) ?? 20
const repo = a.repo as string | undefined
const filtered = repo ? recentEvents.filter((e) => e.repo === repo) : recentEvents
const events = filtered.slice(0, limit)
if (events.length === 0) {
return {
content: [
{
type: "text",
text: JSON.stringify({
events: [],
repos: REPOS,
message: "No events captured yet. Events arrive via polling every " + POLL_INTERVAL_SEC + "s.",
}),
},
],
}
}
const lines = events.map((e) => `${e.ts} ${e.repo} ${e.line} ${e.url}`)
return {
content: [
{
type: "text",
text: JSON.stringify({ repos: REPOS, count: events.length, events: lines }, null, 2),
},
],
}
}
case "github_runs": {
const repo = (a.repo as string) ?? REPOS[0]
const limit = (a.limit as number) ?? 10
const statusFilter = a.status as string | undefined
// The API status param only accepts: completed, in_progress, queued, waiting, requested, pending
// "failure" and "success" are conclusions, not statuses
let apiStatus: string | undefined
let conclusionFilter: string | undefined
if (statusFilter === "failure" || statusFilter === "success") {
apiStatus = "completed"
conclusionFilter = statusFilter
} else {
apiStatus = statusFilter
}
const runs = await fetchWorkflowRuns(repo, apiStatus)
let filtered = runs
if (conclusionFilter) {
filtered = runs.filter((r) => r.conclusion === conclusionFilter)
}
filtered = filtered.slice(0, limit)
const formatted = filtered.map((r) => ({
id: r.id,
name: r.name,
status: r.status,
conclusion: r.conclusion,
branch: r.head_branch,
run: r.run_number,
actor: r.actor.login,
url: r.html_url,
updated: r.updated_at,
}))
return { content: [{ type: "text", text: JSON.stringify({ repo, runs: formatted }, null, 2) }] }
}
case "github_prs": {
const repo = (a.repo as string) ?? REPOS[0]
const prs = await fetchOpenPRs(repo)
const formatted = prs.map((pr) => ({
number: pr.number,
title: pr.title,
author: pr.user.login,
branch: `${pr.head.ref} → ${pr.base.ref}`,
draft: pr.draft,
reviewers: pr.requested_reviewers.map((r) => r.login),
url: pr.html_url,
updated: pr.updated_at,
}))
return { content: [{ type: "text", text: JSON.stringify({ repo, prs: formatted }, null, 2) }] }
}
default:
throw new Error(`Unknown tool: ${name}`)
}
})
// ---------------------------------------------------------------------------
// Polling loop — fetch GitHub events and push as channel notifications
// ---------------------------------------------------------------------------
async function pollGitHubEvents(): Promise<void> {
for (const repo of REPOS) {
try {
const events = await fetchRepoEvents(repo)
const repoCursor = cursorState.repos[repo]
const lastSeenId = repoCursor?.lastEventId
// Find new events (events are newest-first from the API)
const newEvents: GitHubEvent[] = []
for (const event of events) {
if (event.id === lastSeenId) break
newEvents.push(event)
}
// On first poll, don't deliver historical events — just set the cursor
if (!lastSeenId) {
if (events.length > 0) {
cursorState.repos[repo] = {
lastEventId: events[0]!.id,
lastPollAt: new Date().toISOString(),
}
saveCursor(cursorState)
}
continue
}
// Process newest-last so notifications arrive in chronological order
for (const event of newEvents.reverse()) {
const formatted = formatEvent(event)
if (!formatted) continue
const meta: Record<string, string> = {
from: "github",
type: formatted.type,
repo,
url: formatted.url,
}
await mcp.notification({
method: "notifications/claude/channel",
params: { content: formatted.line, meta },
})
addRecentEvent({
repo,
line: formatted.line,
type: formatted.type,
url: formatted.url,
ts: event.created_at,
})
}
// Update cursor
if (events.length > 0) {
cursorState.repos[repo] = {
lastEventId: events[0]!.id,
lastPollAt: new Date().toISOString(),
}
saveCursor(cursorState)
}
} catch (err) {
process.stderr.write(`[github] Error polling ${repo}: ${err instanceof Error ? err.message : err}\n`)
}
}
}
// Also poll workflow runs for failures (events API doesn't always capture these promptly)
async function pollWorkflowFailures(): Promise<void> {
for (const repo of REPOS) {
if (!EVENT_TYPES.includes("workflow_run")) continue
try {
const runs = await fetchWorkflowRuns(repo, "completed")
const failures = runs.filter((r) => r.conclusion === "failure")
// Only notify about recent failures (last 5 minutes)
const cutoff = Date.now() - 5 * 60 * 1000
const recent = failures.filter((r) => new Date(r.updated_at).getTime() > cutoff)
for (const run of recent.slice(0, 3)) {
// Check if we already notified about this run
if (recentEvents.some((e) => e.url === run.html_url)) continue
const line = `[workflow] ${run.name} #${run.run_number} FAILED on ${run.head_branch} (${run.actor.login})`
await mcp.notification({
method: "notifications/claude/channel",
params: {
content: line,
meta: {
from: "github",
type: "workflow",
repo,
url: run.html_url,
},
},
})
addRecentEvent({
repo,
line,
type: "workflow",
url: run.html_url,
ts: run.updated_at,
})
}
} catch (err) {
process.stderr.write(
`[github] Error polling workflows for ${repo}: ${err instanceof Error ? err.message : err}\n`,
)
}
}
}
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
process.stderr.write(`[github] Monitoring repos: ${REPOS.join(", ")}\n`)
process.stderr.write(`[github] Poll interval: ${POLL_INTERVAL_SEC}s\n`)
process.stderr.write(`[github] Event types: ${EVENT_TYPES.join(", ")}\n`)
process.stderr.write(`[github] Cursor file: ${CURSOR_PATH}\n`)
// Initial poll
void pollGitHubEvents()
// Regular polling
const eventPollInterval = setInterval(() => void pollGitHubEvents(), POLL_INTERVAL_SEC * 1000)
// Workflow failure polling (every 60s — separate from events since it's a different endpoint)
const workflowPollInterval = setInterval(() => void pollWorkflowFailures(), 60_000)
// Initial workflow poll after a short delay
setTimeout(() => void pollWorkflowFailures(), 5_000)
// Cleanup on exit
let cleaned = false
function cleanup(): void {
if (cleaned) return
cleaned = true
clearInterval(eventPollInterval)
clearInterval(workflowPollInterval)
saveCursor(cursorState)
}
process.on("SIGINT", () => {
cleanup()
process.exit(0)
})
process.on("SIGTERM", () => {
cleanup()
process.exit(0)
})
process.on("exit", cleanup)
// Connect to Claude Code
await mcp.connect(new StdioServerTransport())