Open History to see the last commit
1import { z } from 'zod'
2import { toolDefinition } from '@tanstack/ai'
3import type { ToolExecutionContext } from '@tanstack/ai'
4
5const NPM_API_BASE = 'https://api.npmjs.org'
6const NPM_REGISTRY = 'https://registry.npmjs.org'
7const FETCH_TIMEOUT = 15000 // 15 second timeout per request
8
9/**
10 * Fetch with timeout - prevents hanging on network issues
11 */
12async function fetchWithTimeout(
13 url: string,
14 options: RequestInit = {},
15): Promise<Response> {
16 const controller = new AbortController()
17 const timeoutId = setTimeout(() => controller.abort(), FETCH_TIMEOUT)
18
19 try {
20 const response = await fetch(url, {
21 ...options,
22 signal: controller.signal,
23 })
24 return response
25 } catch (error) {
26 if (error instanceof Error && error.name === 'AbortError') {
27 throw new Error(`Request timed out after ${FETCH_TIMEOUT}ms`)
28 }
29 throw error
30 } finally {
31 clearTimeout(timeoutId)
32 }
33}
34
35// 1. Get NPM package metadata
36export const getNpmPackageInfoTool = toolDefinition({
37 name: 'getNpmPackageInfo',
38 description:
39 'Get NPM package metadata including description, version history, maintainers, and keywords.',
40 inputSchema: z.object({
41 packageName: z.string().describe('Package name'),
42 }),
43 outputSchema: z.object({
44 name: z.string(),
45 description: z.string().nullable(),
46 version: z.string(),
47 versions: z.array(z.string()),
48 maintainers: z.array(
49 z.object({
50 name: z.string(),
51 email: z.string().optional(),
52 }),
53 ),
54 repository: z
55 .object({
56 url: z.string(),
57 })
58 .nullable(),
59 keywords: z.array(z.string()),
60 time: z.record(z.string(), z.string()),
61 }),
62}).server(async ({ packageName }, context?: ToolExecutionContext) => {
63 const url = `${NPM_REGISTRY}/${encodeURIComponent(packageName)}`
64 const response = await fetchWithTimeout(url)
65
66 if (!response.ok) {
67 throw new Error(`NPM API error: ${response.status} ${response.statusText}`)
68 }
69
70 const data = await response.json()
71
72 // Get version list (limit to last 50 for performance)
73 const versionList = Object.keys(data.versions || {}).slice(-50)
74
75 const result = {
76 name: data.name,
77 description: data.description || null,
78 version: data['dist-tags']?.latest || versionList[versionList.length - 1],
79 versions: versionList,
80 maintainers: (data.maintainers || []).map(
81 (m: { name: string; email?: string }) => ({
82 name: m.name,
83 email: m.email,
84 }),
85 ),
86 repository: data.repository ? { url: data.repository.url } : null,
87 keywords: data.keywords || [],
88 time: data.time || {},
89 }
90
91 // Emit JSON data via custom event for sidebar display
92 const emitCustomEvent = context?.emitCustomEvent || (() => {})
93 emitCustomEvent('npm:data', {
94 componentType: 'packageInfo',
95 toolName: 'getNpmPackageInfo',
96 data: result,
97 })
98
99 return result
100})
101
102const comparisonPeriodSchema = z.enum(['last-week', 'last-month', 'last-year'])
103
104type NpmComparison = {
105 period: z.infer<typeof comparisonPeriodSchema>
106 packages: Array<string>
107}
108
109const npmComparisonStore = new Map<string, NpmComparison>()
110
111const generateComparisonId = () => {
112 const cryptoApi = globalThis.crypto
113 if (typeof cryptoApi.randomUUID === 'function') {
114 return cryptoApi.randomUUID()
115 }
116
117 return `${Date.now()}-${Math.random().toString(16).slice(2)}`
118}
119
120// 2. Create an NPM comparison session
121export const createNpmComparisonTool = toolDefinition({
122 name: 'createNPMComparison',
123 description:
124 'Create a comparison session and get the first comparison ID. You must call addToNPMComparison one package at a time, passing the latest ID returned each time. When you have added all packages, call executeNPMComparison with the final ID.',
125 inputSchema: z.object({
126 period: comparisonPeriodSchema
127 .default('last-month')
128 .describe('Time period for the comparison.'),
129 }),
130 outputSchema: z.object({
131 id: z
132 .string()
133 .describe(
134 'Comparison ID. Pass this ID into addToNPMComparison to add packages.',
135 ),
136 }),
137}).server(async ({ period = 'last-month' }) => {
138 const id = generateComparisonId()
139 npmComparisonStore.set(id, { period, packages: [] })
140 await Promise.resolve()
141
142 return { id }
143})
144
145// 3. Add a package to a comparison session
146export const addToNpmComparisonTool = toolDefinition({
147 name: 'addToNPMComparison',
148 description:
149 'Add exactly one package to an existing comparison session. This returns a NEW comparison ID that must be used for the next addToNPMComparison call or for executeNPMComparison. The previous ID becomes stale for subsequent steps.',
150 inputSchema: z.object({
151 id: z.string().describe('Latest comparison ID returned by the last step.'),
152 package: z.string().describe('Package name to add.'),
153 }),
154 outputSchema: z.object({
155 id: z
156 .string()
157 .describe('New comparison ID to use for the next step in the chain.'),
158 }),
159}).server(async ({ id, package: packageName }) => {
160 const comparison = npmComparisonStore.get(id)
161
162 if (!comparison) {
163 throw new Error(
164 'Unknown comparison ID. Call createNPMComparison to start a new comparison.',
165 )
166 }
167
168 const nextId = generateComparisonId()
169 npmComparisonStore.set(nextId, {
170 period: comparison.period,
171 packages: [...comparison.packages, packageName],
172 })
173 await Promise.resolve()
174
175 return { id: nextId }
176})
177
178// 4. Execute the comparison using the final ID
179export const executeNpmComparisonTool = toolDefinition({
180 name: 'executeNPMComparison',
181 description:
182 'Execute a comparison using the final comparison ID returned by addToNPMComparison. This only works after you have added all packages; it will compare download counts for the stored package list.',
183 inputSchema: z.object({
184 id: z
185 .string()
186 .describe(
187 'Final comparison ID returned after your last addToNPMComparison call.',
188 ),
189 }),
190 outputSchema: z.array(
191 z.object({
192 package: z.string(),
193 downloads: z.number(),
194 }),
195 ),
196}).server(async ({ id }, context?: ToolExecutionContext) => {
197 const comparison = npmComparisonStore.get(id)
198
199 if (!comparison) {
200 throw new Error(
201 'Unknown comparison ID. Call createNPMComparison to start a new comparison.',
202 )
203 }
204
205 if (comparison.packages.length === 0) {
206 throw new Error(
207 'No packages were added. Call addToNPMComparison at least once before executing.',
208 )
209 }
210
211 const results = await Promise.all(
212 comparison.packages.map(async (pkg) => {
213 try {
214 const url = `${NPM_API_BASE}/downloads/point/${comparison.period}/${encodeURIComponent(pkg)}`
215 const response = await fetchWithTimeout(url)
216
217 if (!response.ok) {
218 return { package: pkg, downloads: 0 }
219 }
220
221 const data = await response.json()
222 return { package: pkg, downloads: data.downloads }
223 } catch (_error) {
224 return { package: pkg, downloads: 0 }
225 }
226 }),
227 )
228
229 const sortedResults = results.sort((a, b) => b.downloads - a.downloads)
230
231 // Emit JSON data via custom event for sidebar display
232 const emitCustomEvent = context?.emitCustomEvent || (() => {})
233 emitCustomEvent('npm:data', {
234 componentType: 'compare',
235 toolName: 'executeNPMComparison',
236 data: { packages: sortedResults, period: comparison.period },
237 })
238
239 return sortedResults
240})
241
242// Export all NPM tools as a collection
243export const npmTools = [
244 getNpmPackageInfoTool,
245 createNpmComparisonTool,
246 addToNpmComparisonTool,
247 executeNpmComparisonTool,
248]