-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmcp.ts
More file actions
executable file
·567 lines (503 loc) · 16.5 KB
/
mcp.ts
File metadata and controls
executable file
·567 lines (503 loc) · 16.5 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
#!/usr/bin/env deno run --allow-net --allow-run
import { McpServer } from "npm:@modelcontextprotocol/sdk@1.16.0/server/mcp.js";
import { StdioServerTransport } from "npm:@modelcontextprotocol/sdk@1.16.0/server/stdio.js";
import { z } from "npm:zod@^3";
import {
formatDiscoveredPackages,
formatPackageComparison,
formatPackageDetails,
formatPackageDownloads,
formatScopePackages,
formatSearchResults,
formatSimilarPackages
} from "./format.ts";
import {
findSimilarPackages,
getErrorMessage,
getPackageDetails,
getPackageDocs,
getPackageDownloadSummary,
getPackageFile,
getPackageInfoDirect,
getScopePackages,
getSearchCapabilities,
ORAMA_INDEX_ID,
queryOrama,
relevanceSearch
} from "./common.ts";
// Create an MCP server
const server = new McpServer({
name: "JSR",
version: "0.0.1",
description: "JSR search and discovery tools"
});
server.tool("package_docs", {
module: z.string().describe("The module to document, example @std/path"),
}, async ({ module }) => {
try {
const result = await getPackageDocs(module);
return ({
content: [{ type: "text", text: result }],
});
} catch (error) {
return {
content: [{
type: "text",
text: `Error getting docs for ${module}: ${getErrorMessage(error)}`
}],
isError: true
};
}
});
if (Deno.permissions.querySync({ name: "run" }).state === "granted") {
server.tool("search", {
query: z.string().describe("Search query for JSR packages"),
limit: z.number().optional().default(10).describe("Maximum number of results (default: 10)")
}, async ({ query, limit }) => {
try {
const results = await queryOrama(query, { limit });
// Convert enhanced hits to the format expected by formatSearchResults
const packages = results.hits?.map((hit: any) => {
const pkg = hit.document;
const downloads = hit.downloads;
return {
id: pkg.id,
name: pkg.name,
scope: pkg.scope,
description: pkg.description,
score: hit.score,
runtimeCompat: pkg.runtimeCompat,
updatedAt: pkg.updatedAt,
latestVersion: pkg.latestVersion || downloads?.latestVersion || 'Unknown',
// Include download information from enhanced results
totalDownloads: downloads?.totalDownloads || 0,
recentDownloads: downloads?.recentDownloads || 0
};
}) || [];
const summary = formatSearchResults(query, packages);
return {
content: [{
type: "text",
text: summary
}],
meta: {
searchQuery: query,
totalResults: packages.length,
packages: packages
}
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error searching JSR packages: ${getErrorMessage(error)}`
}],
isError: true
};
}
});
}
server.tool("find_similar", {
packageName: z.string().describe("Name of the JSR package to find similar packages for (e.g., '@std/http', 'netsaur')"),
limit: z.number().optional().default(6).describe("Maximum number of similar packages (default: 6)")
}, async ({ packageName, limit }) => {
try {
const results = await findSimilarPackages(packageName, { limit });
if (results.error) {
return {
content: [{
type: "text",
text: `Package "${packageName}" not found in JSR registry.`
}],
isError: true
};
}
const originalPkg = results.originalPackage;
// findSimilarPackages already returns enhanced hits with download information
const similarPackages = results.hits?.map((hit: any) => {
const pkg = hit.document;
const downloads = hit.downloads;
return {
id: pkg.id,
name: pkg.name,
scope: pkg.scope,
description: pkg.description,
score: hit.score,
runtimeCompat: pkg.runtimeCompat,
updatedAt: pkg.updatedAt,
latestVersion: pkg.latestVersion || downloads?.latestVersion || 'Unknown',
// Include download information from enhanced results
totalDownloads: downloads?.totalDownloads || 0,
recentDownloads: downloads?.recentDownloads || 0
};
}) || [];
const summary = formatSimilarPackages(originalPkg, similarPackages);
return {
content: [{
type: "text",
text: summary
}],
meta: {
originalPackage: originalPkg,
similarPackages: similarPackages,
totalResults: similarPackages.length
}
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error finding similar packages to "${packageName}": ${getErrorMessage(error)}`
}],
isError: true
};
}
});
server.tool("discover", {
category: z.string().describe("Category or use case to discover packages for (e.g., 'web frameworks', 'testing', 'database', 'machine learning')"),
limit: z.number().optional().default(8).describe("Maximum number of packages to discover (default: 8)")
}, async ({ category, limit }) => {
try {
const results = await relevanceSearch(category, { limit });
// Convert enhanced hits to the format expected by formatDiscoveredPackages
const packages = results.hits?.map((hit: any) => {
const pkg = hit.document;
const downloads = hit.downloads;
return {
id: pkg.id,
name: pkg.name,
scope: pkg.scope,
description: pkg.description,
score: hit.score,
runtimeCompat: pkg.runtimeCompat,
updatedAt: pkg.updatedAt,
latestVersion: pkg.latestVersion || downloads?.latestVersion || 'Unknown',
// Include download information from enhanced results
totalDownloads: downloads?.totalDownloads || 0,
recentDownloads: downloads?.recentDownloads || 0
};
}) || [];
// Group packages by scope for better organization
const packagesByScope = packages.reduce((acc: any, pkg: any) => {
const scope = pkg.scope || 'unscoped';
if (!acc[scope]) acc[scope] = [];
acc[scope].push(pkg);
return acc;
}, {});
const summary = formatDiscoveredPackages(category, packages);
return {
content: [{
type: "text",
text: summary
}],
meta: {
category: category,
totalResults: packages.length,
packages: packages,
packagesByScope: packagesByScope
}
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error discovering packages for "${category}": ${getErrorMessage(error)}`
}],
isError: true
};
}
});
// Package comparison tool
server.tool("compare", {
packages: z.array(z.string()).describe("Array of package names to compare (e.g., ['@std/http', '@hono/hono'])"),
}, async ({ packages }) => {
try {
const packageDetails: any[] = [];
for (const pkgName of packages) {
try {
// Parse package name to extract scope and name
const match = pkgName.match(/^@?([^/]+)\/(.+)$/);
if (!match) {
packageDetails.push({
id: pkgName,
found: false,
error: "Invalid package format. Use @scope/name or scope/name"
});
continue;
}
const [, scope, name] = match;
// First try exact lookup using direct JSR API
try {
const pkg = await getPackageInfoDirect(scope, name);
const details = await getPackageDetails(scope, name);
const downloadSummary = await getPackageDownloadSummary(scope, name);
packageDetails.push({
id: `@${scope}/${name}`,
name: name,
scope: scope,
description: details.description,
runtimeCompat: details.runtimeCompat,
score: details.score,
latestVersion: pkg.latest,
recentDownloads: downloadSummary.recentDownloads,
totalDownloads: downloadSummary.totalDownloads,
updatedAt: details.updatedAt,
versionCount: details.versionCount,
found: true
});
} catch (_directError: unknown) {
// Fallback to search if direct lookup fails
const searchResult = await queryOrama(pkgName, {
limit: 1,
mode: "fulltext",
boost: { name: 10, id: 8, scope: 5 } // Much higher exact match priority
});
if (searchResult.hits?.[0]) {
const pkg = searchResult.hits[0].document;
packageDetails.push({
id: pkg.id,
name: pkg.name,
scope: pkg.scope,
description: pkg.description,
runtimeCompat: pkg.runtimeCompat,
score: pkg.score,
found: true,
fallback: true
});
} else {
packageDetails.push({
id: pkgName,
found: false,
error: "Package not found"
});
}
}
} catch (error: unknown) {
packageDetails.push({
id: pkgName,
found: false,
error: getErrorMessage(error),
});
}
}
const foundPackages = packageDetails.filter(pkg => pkg.found);
const notFound = packageDetails.filter(pkg => !pkg.found);
const comparison = formatPackageComparison(foundPackages, notFound);
return {
content: [{
type: "text",
text: comparison
}],
meta: {
comparedPackages: packages,
foundPackages: foundPackages,
notFoundPackages: notFound
}
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error comparing packages: ${getErrorMessage(error)}`
}],
isError: true
};
}
});
// Browse packages in a JSR scope
server.tool("scope_packages", {
scope: z.string().describe("JSR scope name (e.g., 'std', 'orgsoft', 'denosaurs')"),
}, async ({ scope }) => {
try {
const scopeName = scope.startsWith("@") ? scope.slice(1) : scope;
const data = await getScopePackages(scopeName);
const packages = data.items?.map((pkg) => ({
name: pkg.name,
description: pkg.description,
latestVersion: pkg.latestVersion,
score: pkg.score,
versionCount: pkg.versionCount,
dependencyCount: pkg.dependencyCount,
dependentCount: pkg.dependentCount,
runtimeCompat: pkg.runtimeCompat,
githubRepository: pkg.githubRepository,
updatedAt: pkg.updatedAt,
isArchived: pkg.isArchived
})) || [];
const summary = formatScopePackages(scopeName, packages);
return {
content: [{ type: "text", text: summary }],
meta: {
scope: scopeName,
totalPackages: data.total,
packages
}
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error fetching packages for scope '@${scope}': ${getErrorMessage(error)}`
}],
isError: true
};
}
});
// Get detailed package information
server.tool("package_details", {
scope: z.string().describe("JSR scope name (e.g., 'std', 'orgsoft')"),
packageName: z.string().describe("Package name (e.g., 'http', 'dsbuild')")
}, async ({ scope, packageName }) => {
try {
const scopeName = scope.startsWith("@") ? scope.slice(1) : scope;
const pkg = await getPackageDetails(scopeName, packageName);
const downloadSummary = await getPackageDownloadSummary(scopeName, packageName);
const meta = await getPackageInfoDirect(scopeName, packageName);
const details = formatPackageDetails(pkg, downloadSummary, meta);
return {
content: [{ type: "text", text: details }],
meta: {
package: pkg,
downloadSummary,
metadata: meta
}
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error fetching details for @${scope}/${packageName}: ${getErrorMessage(error)}`
}],
isError: true
};
}
});
// Get package download statistics
server.tool("package_downloads", {
scope: z.string().describe("JSR scope name (e.g., 'std', 'orgsoft')"),
packageName: z.string().describe("Package name (e.g., 'http', 'dsbuild')")
}, async ({ scope, packageName }) => {
try {
const scopeName = scope.startsWith("@") ? scope.slice(1) : scope;
const summary = await getPackageDownloadSummary(scopeName, packageName);
const report = formatPackageDownloads(scopeName, packageName, summary);
return {
content: [{ type: "text", text: report }],
meta: {
scope: scopeName,
packageName,
summary
}
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error fetching download stats for @${scope}/${packageName}: ${getErrorMessage(error)}`
}],
isError: true
};
}
});
server.tool("search_status", {}, async () => {
try {
const capabilities = await getSearchCapabilities();
const timestamp = new Date().toISOString();
const status = `# 🔧 JSR Search Status
## Connection Status
- **Status**: ✅ Connected to Orama Cloud
- **Timestamp**: ${timestamp}
- **Index ID**: ${ORAMA_INDEX_ID}
## Search Capabilities
- **Fulltext Search**: ✅ Available (Sample: ${capabilities.sample || 'N/A'})
## Available MCP Tools
### Search & Discovery
- \`search\` - Search JSR packages by keywords
- \`find_similar\` - Find packages similar to a specific one
- \`discover\` - Discover packages by category or use case
- \`compare\` - Compare multiple packages side-by-side
### Scope & Package Browsing
- \`scope_packages\` - Browse all packages in a JSR scope
- \`package_details\` - Get detailed package information with metadata
- \`package_downloads\` - View package download statistics
### Direct Access
- \`package_file\` - Access source code files from packages
- \`package_docs\` - Get package documentation
### Meta
- \`search_status\` - Check search capabilities (this tool)
## How It Works
This MCP server provides two data sources:
1. **Orama Cloud Search** (${ORAMA_INDEX_ID}) - Fulltext search with relevance scoring
2. **JSR API Direct** (https://api.jsr.io) - Real-time scope/package browsing and download stats
No separate API server required - everything connects directly to external APIs.`;
return {
content: [{ type: "text", text: status }],
meta: {
timestamp,
indexId: ORAMA_INDEX_ID,
capabilities
}
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error checking search status: ${getErrorMessage(error)}`
}],
isError: true
};
}
});
server.tool("package_file", {
scope: z.string().describe("JSR scope name (e.g., 'std', 'hono')"),
packageName: z.string().describe("Package name (e.g., 'http', 'hono')"),
version: z.string().describe("Package version (e.g., '1.0.0', 'latest')"),
filePath: z.string().describe("File path within package (e.g., 'src/index.ts', 'mod.ts')")
}, async ({ scope, packageName, version, filePath }) => {
try {
const scopeName = scope.startsWith("@") ? scope.slice(1) : scope;
// If version is 'latest', get the actual latest version
let actualVersion: string | undefined = version;
if (version === 'latest') {
const meta = await getPackageInfoDirect(scopeName, packageName);
actualVersion = meta.latest;
}
if (!actualVersion) {
throw new Error("Package version not found");
}
const fileContent = await getPackageFile(scopeName, packageName, actualVersion, filePath);
const response = `# 📄 @${scopeName}/${packageName}@${actualVersion}/${filePath}
\`\`\`typescript
${fileContent}
\`\`\`
**File URL**: https://jsr.io/@${scopeName}/${packageName}/${actualVersion}/${filePath}
💡 **Use \`package_meta\` to see all available versions and files for this package.**`;
return {
content: [{ type: "text", text: response }],
meta: {
scope: scopeName,
packageName,
version: actualVersion,
filePath,
fileSize: fileContent.length
}
};
} catch (error) {
return {
content: [{
type: "text",
text: `Error fetching file @${scope}/${packageName}@${version}/${filePath}: ${getErrorMessage(error)}`
}],
isError: true
};
}
});
export const main = async () => {
const transport = new StdioServerTransport();
console.error("🚀 JSR MCP Server starting...");
console.error("📦 Tools: search, find_similar, discover, compare, scope_packages, package_details, package_downloads, package_file, package_docs, search_status");
await server.connect(transport);
}
if (import.meta.main) {
main();
}