Open History to see the last commit
1import { toolDefinition } from '@tanstack/ai'
2import { z } from 'zod'
3
4const GITHUB_API_BASE = 'https://api.github.com'
5const FETCH_TIMEOUT = 15000 // 15 second timeout per request
6
7function getGitHubHeaders(): HeadersInit {
8 const token = process.env.GITHUB_TOKEN
9 if (!token) {
10 throw new Error('GITHUB_TOKEN environment variable is required')
11 }
12 return {
13 Authorization: `Bearer ${token}`,
14 Accept: 'application/vnd.github+json',
15 'X-GitHub-Api-Version': '2022-11-28',
16 }
17}
18
19/**
20 * Fetch with timeout - prevents hanging on network issues
21 */
22async function fetchWithTimeout(
23 url: string,
24 options: RequestInit = {},
25): Promise<Response> {
26 const controller = new AbortController()
27 const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT)
28
29 try {
30 const response = await fetch(url, {
31 ...options,
32 signal: controller.signal,
33 })
34 return response
35 } catch (error) {
36 if (error instanceof Error && error.name === 'AbortError') {
37 throw new Error(`Request timed out after ${FETCH_TIMEOUT}ms`)
38 }
39 throw error
40 } finally {
41 clearTimeout(timeoutId)
42 }
43}
44
45// Schema definitions for reuse
46const repoSchema = z.object({
47 id: z.number(),
48 name: z.string(),
49 full_name: z.string(),
50 description: z.string().nullable(),
51 stargazers_count: z.number(),
52 forks_count: z.number(),
53 updated_at: z.string(),
54 pushed_at: z.string(),
55 language: z.string().nullable(),
56 topics: z.array(z.string()),
57})
58
59const repoDetailSchema = z.object({
60 id: z.number(),
61 name: z.string(),
62 full_name: z.string(),
63 description: z.string().nullable(),
64 stargazers_count: z.number(),
65 forks_count: z.number(),
66 watchers_count: z.number(),
67 open_issues_count: z.number(),
68 created_at: z.string(),
69 updated_at: z.string(),
70 pushed_at: z.string(),
71 subscribers_count: z.number(),
72 license: z
73 .object({
74 name: z.string(),
75 })
76 .nullable(),
77})
78
79const releaseSchema = z.object({
80 id: z.number(),
81 tag_name: z.string(),
82 name: z.string().nullable(),
83 body: z.string().nullable(),
84 published_at: z.string(),
85 prerelease: z.boolean(),
86 draft: z.boolean(),
87})
88
89const contributorSchema = z.object({
90 login: z.string(),
91 contributions: z.number(),
92 avatar_url: z.string(),
93})
94
95// 1. Get starred repositories for a user
96export const getStarredReposTool = toolDefinition({
97 name: 'getStarredRepos',
98 description:
99 'Fetch GitHub starred repositories for a user. Returns repos with star counts, languages, and activity dates.',
100 inputSchema: z.object({
101 username: z.string().describe('GitHub username'),
102 perPage: z.number().optional().default(100).describe('Results per page'),
103 page: z.number().optional().default(1).describe('Page number'),
104 }),
105 outputSchema: z.array(repoSchema),
106}).server(async ({ username, perPage = 100, page = 1 }) => {
107 const url = `${GITHUB_API_BASE}/users/${username}/starred?per_page=${perPage}&page=${page}`
108 const response = await fetchWithTimeout(url, { headers: getGitHubHeaders() })
109
110 if (!response.ok) {
111 throw new Error(
112 `GitHub API error: ${response.status} ${response.statusText}`,
113 )
114 }
115
116 const data = await response.json()
117 return data.map((repo: Record<string, unknown>) => ({
118 id: repo.id,
119 name: repo.name,
120 full_name: repo.full_name,
121 description: repo.description,
122 stargazers_count: repo.stargazers_count,
123 forks_count: repo.forks_count,
124 updated_at: repo.updated_at,
125 pushed_at: repo.pushed_at,
126 language: repo.language,
127 topics: repo.topics || [],
128 }))
129})
130
131// 2. Get detailed repository information
132export const getRepoDetailsTool = toolDefinition({
133 name: 'getRepoDetails',
134 description:
135 'Get detailed information about a specific GitHub repository including stars, forks, issues, and license.',
136 inputSchema: z.object({
137 owner: z.string().describe('Repository owner (user or org)'),
138 repo: z.string().describe('Repository name'),
139 }),
140 outputSchema: repoDetailSchema,
141}).server(async ({ owner, repo }) => {
142 const url = `${GITHUB_API_BASE}/repos/${owner}/${repo}`
143 const response = await fetchWithTimeout(url, { headers: getGitHubHeaders() })
144
145 if (!response.ok) {
146 throw new Error(
147 `GitHub API error: ${response.status} ${response.statusText}`,
148 )
149 }
150
151 const data = await response.json()
152 return {
153 id: data.id,
154 name: data.name,
155 full_name: data.full_name,
156 description: data.description,
157 stargazers_count: data.stargazers_count,
158 forks_count: data.forks_count,
159 watchers_count: data.watchers_count,
160 open_issues_count: data.open_issues_count,
161 created_at: data.created_at,
162 updated_at: data.updated_at,
163 pushed_at: data.pushed_at,
164 subscribers_count: data.subscribers_count,
165 license: data.license ? { name: data.license.name } : null,
166 }
167})
168
169// 3. Get repository releases
170export const getRepoReleasesTool = toolDefinition({
171 name: 'getRepoReleases',
172 description:
173 'Get releases for a repository including version tags, release notes, and publish dates.',
174 inputSchema: z.object({
175 owner: z.string().describe('Repository owner'),
176 repo: z.string().describe('Repository name'),
177 perPage: z.number().optional().default(30).describe('Results per page'),
178 }),
179 outputSchema: z.array(releaseSchema),
180}).server(async ({ owner, repo, perPage = 30 }) => {
181 const url = `${GITHUB_API_BASE}/repos/${owner}/${repo}/releases?per_page=${perPage}`
182 const response = await fetchWithTimeout(url, { headers: getGitHubHeaders() })
183
184 if (!response.ok) {
185 throw new Error(
186 `GitHub API error: ${response.status} ${response.statusText}`,
187 )
188 }
189
190 const data = await response.json()
191 return data.map((release: Record<string, unknown>) => ({
192 id: release.id,
193 tag_name: release.tag_name,
194 name: release.name,
195 body: release.body,
196 published_at: release.published_at,
197 prerelease: release.prerelease,
198 draft: release.draft,
199 }))
200})
201
202// 4. Get repository contributors
203export const getRepoContributorsTool = toolDefinition({
204 name: 'getRepoContributors',
205 description:
206 'Get top contributors for a repository with their contribution counts.',
207 inputSchema: z.object({
208 owner: z.string().describe('Repository owner'),
209 repo: z.string().describe('Repository name'),
210 perPage: z.number().optional().default(30).describe('Results per page'),
211 }),
212 outputSchema: z.array(contributorSchema),
213}).server(async ({ owner, repo, perPage = 30 }) => {
214 const url = `${GITHUB_API_BASE}/repos/${owner}/${repo}/contributors?per_page=${perPage}`
215 const response = await fetchWithTimeout(url, { headers: getGitHubHeaders() })
216
217 if (!response.ok) {
218 throw new Error(
219 `GitHub API error: ${response.status} ${response.statusText}`,
220 )
221 }
222
223 const data = await response.json()
224 return data.map((contributor: Record<string, unknown>) => ({
225 login: contributor.login,
226 contributions: contributor.contributions,
227 avatar_url: contributor.avatar_url,
228 }))
229})
230
231// 5. Search GitHub repositories
232export const searchRepositoriesTool = toolDefinition({
233 name: 'searchRepositories',
234 description:
235 'Search GitHub repositories by query. Supports language filters, sorting by stars/forks/updated.',
236 inputSchema: z.object({
237 query: z
238 .string()
239 .describe('Search query (e.g., "tanstack language:typescript")'),
240 sort: z
241 .enum(['stars', 'forks', 'updated'])
242 .optional()
243 .describe('Sort field'),
244 order: z.enum(['asc', 'desc']).optional().default('desc').describe('Order'),
245 perPage: z.number().optional().default(30).describe('Results per page'),
246 }),
247 outputSchema: z.object({
248 total_count: z.number(),
249 items: z.array(
250 z.object({
251 id: z.number(),
252 name: z.string(),
253 full_name: z.string(),
254 description: z.string().nullable(),
255 stargazers_count: z.number(),
256 forks_count: z.number(),
257 language: z.string().nullable(),
258 }),
259 ),
260 }),
261}).server(async ({ query, sort, order = 'desc', perPage = 30 }) => {
262 let url = `${GITHUB_API_BASE}/search/repositories?q=${encodeURIComponent(query)}&per_page=${perPage}&order=${order}`
263 if (sort) {
264 url += `&sort=${sort}`
265 }
266
267 const response = await fetchWithTimeout(url, { headers: getGitHubHeaders() })
268
269 if (!response.ok) {
270 throw new Error(
271 `GitHub API error: ${response.status} ${response.statusText}`,
272 )
273 }
274
275 const data = await response.json()
276 return {
277 total_count: data.total_count,
278 items: data.items.map((item: Record<string, unknown>) => ({
279 id: item.id,
280 name: item.name,
281 full_name: item.full_name,
282 description: item.description,
283 stargazers_count: item.stargazers_count,
284 forks_count: item.forks_count,
285 language: item.language,
286 })),
287 }
288})
289
290// Export all GitHub tools as a collection
291export const githubTools = [
292 getStarredReposTool,
293 getRepoDetailsTool,
294 getRepoReleasesTool,
295 getRepoContributorsTool,
296 searchRepositoriesTool,
297]