-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecosystem-activity-tool.ts
More file actions
268 lines (240 loc) · 7.83 KB
/
ecosystem-activity-tool.ts
File metadata and controls
268 lines (240 loc) · 7.83 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
import type { FastMCP } from "fastmcp";
import { z } from "zod";
import { gateAuth } from "./github-auth.js";
import {
classifyError,
graphqlQuery,
parallelApi,
resolveLocalRepoRemote,
} from "./github-client.js";
import {
errorRespond,
jsonRespond,
type McpErrorEnvelope,
mkLocalRepoNoRemote,
truncateText,
} from "./json.js";
import { FormatSchema, LocalOrRemoteRepoSchema } from "./schemas.js";
import { extractFirstPR, parseSince } from "./utils.js";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
interface CommitHistoryNode {
oid: string;
messageHeadline: string;
committedDate: string;
author: { name: string | null; user: { login: string } | null };
}
interface HistoryQueryResult {
repository: {
defaultBranchRef: {
name: string;
target: {
history: {
nodes: CommitHistoryNode[];
};
} | null;
} | null;
};
}
interface EcosystemCommit {
owner: string;
repo: string;
sha7: string;
message: string;
author: string;
date: string;
pr: { number: number } | null;
}
interface RepoCommitResult {
owner: string;
repo: string;
commitCount: number;
error?: McpErrorEnvelope;
commits: EcosystemCommit[];
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
async function fetchRepoCommits(
owner: string,
repo: string,
sinceIso: string,
paths: string[] | undefined,
maxCommits: number,
grepRe: RegExp | undefined,
): Promise<RepoCommitResult> {
const pathsToFetch = paths && paths.length > 0 ? paths : [undefined];
// Fetch history per path (or once if no path filter), then deduplicate by SHA
const allNodes = new Map<string, CommitHistoryNode>();
try {
for (const path of pathsToFetch) {
const pathClause = path ? `, path: "${path}"` : "";
const query = `query($owner:String!,$repo:String!){
repository(owner:$owner,name:$repo){
defaultBranchRef{
name
target{
...on Commit{
history(first:${maxCommits},since:"${sinceIso}"${pathClause}){
nodes{
oid messageHeadline committedDate
author{ name user{ login } }
}
}
}
}
}
}
}`;
const data = await graphqlQuery<HistoryQueryResult>(query, { owner, repo });
const nodes = data.repository.defaultBranchRef?.target?.history.nodes ?? [];
for (const n of nodes) {
allNodes.set(n.oid, n);
}
}
} catch (err) {
return { owner, repo, commitCount: 0, error: classifyError(err), commits: [] };
}
const sorted = [...allNodes.values()].sort(
(a, b) => new Date(b.committedDate).getTime() - new Date(a.committedDate).getTime(),
);
const commits: EcosystemCommit[] = sorted
.filter((n) => !grepRe || grepRe.test(n.messageHeadline))
.slice(0, maxCommits)
.map((n) => {
const prNum = extractFirstPR(n.messageHeadline);
return {
owner,
repo,
sha7: n.oid.substring(0, 7),
message: n.messageHeadline,
author: n.author.user?.login ?? n.author.name ?? "unknown",
date: n.committedDate,
pr: prNum !== undefined ? { number: prNum } : null,
};
});
return {
owner,
repo,
commitCount: commits.length,
commits,
};
}
// ---------------------------------------------------------------------------
// Tool registration
// ---------------------------------------------------------------------------
export function registerEcosystemActivityTool(server: FastMCP): void {
server.addTool({
name: "ecosystem_activity",
description:
"Chronological commit feed across multiple repos, filterable by path or commit-message regex.",
annotations: { readOnlyHint: true },
parameters: z.object({
repos: z
.array(LocalOrRemoteRepoSchema)
.min(1)
.max(20)
.describe("1–20 repos. Each is { owner, repo } or { localPath }."),
since: z.string().describe("ISO8601 or relative duration (e.g. '48h', '7d')."),
paths: z.array(z.string()).optional().describe("Limit to commits touching these paths."),
grep: z.string().optional().describe("Client-side regex filter on commit subjects."),
maxCommitsPerRepo: z
.number()
.int()
.min(1)
.max(200)
.optional()
.default(50)
.describe("Max commits per repo."),
format: FormatSchema,
}),
execute: async (args) => {
const auth = gateAuth();
if (!auth.ok) return errorRespond(auth.envelope);
const sinceIso = parseSince(args.since);
const grepRe = args.grep ? new RegExp(args.grep, "i") : undefined;
const repoResults = await parallelApi(args.repos, async (repoRef) => {
let owner: string;
let repo: string;
if ("localPath" in repoRef) {
const resolved = resolveLocalRepoRemote(repoRef.localPath);
if (!resolved) {
return {
owner: "unknown",
repo: repoRef.localPath,
commitCount: 0,
error: mkLocalRepoNoRemote(repoRef.localPath),
commits: [],
} as RepoCommitResult;
}
owner = resolved.owner;
repo = resolved.repo;
} else {
owner = repoRef.owner;
repo = repoRef.repo;
}
return fetchRepoCommits(owner, repo, sinceIso, args.paths, args.maxCommitsPerRepo, grepRe);
});
// Merge + sort all commits by date desc
const allCommits = repoResults
.flatMap((r) => r.commits)
.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
// Summary
const repoBreakdown: Record<string, number> = {};
for (const r of repoResults) {
if (r.commitCount > 0) repoBreakdown[r.repo] = r.commitCount;
}
const repoSummaries = repoResults.map((r) => ({
owner: r.owner,
repo: r.repo,
commitCount: r.commitCount,
...(r.error ? { error: r.error } : {}),
}));
const result = {
since: sinceIso,
repos: repoSummaries,
commits: allCommits,
summary: {
totalCommits: allCommits.length,
repoBreakdown,
},
};
if (args.format === "json") return jsonRespond(result);
// -----------------------------------------------------------------------
// Markdown output
// -----------------------------------------------------------------------
const lines: string[] = [];
lines.push("# Ecosystem Activity");
lines.push("");
lines.push(
`**Since:** ${sinceIso} · **${allCommits.length} commits** across ${repoResults.length} repos`,
);
if (allCommits.length === 0) {
lines.push("");
lines.push("*(no commits in range)*");
} else {
lines.push("");
lines.push("| Date | Repo | SHA | Message | Author |");
lines.push("|------|------|-----|---------|--------|");
for (const c of allCommits) {
const date = c.date.substring(0, 10);
const msg = truncateText(c.message, 70);
const prSuffix = c.pr ? ` (#${c.pr.number})` : "";
lines.push(
`| ${date} | ${c.owner}/${c.repo} | \`${c.sha7}\` | ${msg}${prSuffix} | ${c.author} |`,
);
}
}
const errored = repoResults.filter((r) => r.error);
if (errored.length > 0) {
lines.push("");
lines.push("## Errors");
for (const r of errored) {
lines.push(`- ${r.owner}/${r.repo}: (${r.error?.code}) ${r.error?.message}`);
}
}
return lines.join("\n");
},
});
}