forked from JayArrowz/mcp-osrs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
584 lines (525 loc) · 22.3 KB
/
Copy pathindex.ts
File metadata and controls
584 lines (525 loc) · 22.3 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
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from 'zod';
import axios from 'axios';
import { zodToJsonSchema } from 'zod-to-json-schema';
import fs from 'fs';
import path from 'path';
import readline from 'readline';
import { fileURLToPath } from 'url';
import { getStats, getStatsByGamemode } from 'osrs-json-hiscores';
import { searchItems, getLatest, getTimeSeries } from './ge-prices.js';
import { SearchGeItemsSchema, GeLatestSchema, GeTimeSeriesSchema } from './ge-prices.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const DATA_DIR = path.join(__dirname, 'data');
const responseToString = (response: any) => {
const contentText = typeof response === 'string' ? response : JSON.stringify(response);
return {
content: [{ type: "text", text: contentText }]
};
};
const osrsApiClient = axios.create({
baseURL: 'https://oldschool.runescape.wiki/api.php',
params: {
format: 'json'
}
});
const OsrsWikiSearchSchema = z.object({
search: z.string().describe("The term to search for on the OSRS Wiki"),
limit: z.number().int().min(1).max(50).optional().describe("Number of results to return (1-50)"),
offset: z.number().int().min(0).optional().describe("Offset for pagination (0-based)")
});
const OsrsWikiGetPageInfoSchema = z.object({
titles: z.string().describe("Comma-separated list of page titles to get info for (e.g., Dragon_scimitar,Abyssal_whip)")
});
const OsrsWikiParsePageSchema = z.object({
page: z.string().describe("The exact title of the wiki page to parse (e.g., 'Dragon scimitar', 'Abyssal whip'). Case-sensitive.")
});
const FileSearchSchema = z.object({
query: z.string().describe("The term to search for in the file"),
page: z.number().int().min(1).optional().default(1).describe("Page number for pagination"),
pageSize: z.number().int().min(1).max(100).optional().default(10).describe("Number of results per page")
});
const GenericFileSearchSchema = z.object({
filename: z.string().describe("The filename to search in the data directory (e.g., 'varptypes.txt')"),
query: z.string().describe("The term to search for in the file"),
page: z.number().int().min(1).optional().default(1).describe("Page number for pagination"),
pageSize: z.number().int().min(1).max(100).optional().default(10).describe("Number of results per page")
});
const FileDetailsSchema = z.object({
filename: z.string().describe("The filename to get details for in the data directory")
});
const ListDataFilesSchema = z.object({
fileType: z.string().optional().describe("Optional filter for file type (e.g., 'txt')")
});
const LookupPlayerSchema = z.object({
playerName: z.string().describe("The RuneScape username to look up"),
gamemode: z.enum(['main', 'ironman', 'hardcore', 'ultimate', 'deadman', 'seasonal']).optional().describe("Game mode to check (defaults to auto-detect)")
});
function convertZodToJsonSchema(schema: z.ZodType<any>) {
const jsonSchema = zodToJsonSchema(schema);
delete jsonSchema.$schema;
delete jsonSchema.definitions;
return {
...jsonSchema
};
}
const server = new Server(
{
name: "mcp-osrs",
version: "0.1.0"
},
{
capabilities: {
tools: {}
}
}
);
/**
* Score how well a line matches a search term.
* Returns 0 if no match, higher = better.
*/
export function fuzzyScore(text: string, pattern: string): number {
const t = text.toLowerCase();
const p = pattern.toLowerCase();
// Exact substring — best
if (t.includes(p)) return 100;
// All whitespace/underscore-split tokens present as substrings
const tokens = p.split(/[\s_]+/).filter(Boolean);
if (tokens.length > 1 && tokens.every(tok => t.includes(tok))) return 75;
// Character subsequence match (handles typos / partial queries)
let score = 0;
let pIdx = 0;
let consecutive = 0;
for (let i = 0; i < t.length && pIdx < p.length; i++) {
if (t[i] === p[pIdx]) {
score += 1 + consecutive;
consecutive++;
pIdx++;
} else {
consecutive = 0;
}
}
if (pIdx < p.length) return 0; // not all chars matched
return Math.min(50, Math.floor((score / p.length) * 20));
}
/**
* Search through a file for matching lines
* @param filePath Path to the file to search
* @param searchTerm Term to search for
* @param page Page number for pagination
* @param pageSize Number of results per page
* @returns Object containing results and pagination info
*/
export async function searchFile(filePath: string, searchTerm: string, page: number = 1, pageSize: number = 10): Promise<any> {
searchTerm = searchTerm.replace(/ /g, "_");
return new Promise((resolve, reject) => {
if (!fs.existsSync(filePath)) {
reject(new Error(`File not found: ${filePath}`));
return;
}
const results: {line: string, lineNumber: number, score: number}[] = [];
const fileStream = fs.createReadStream(filePath);
const rl = readline.createInterface({
input: fileStream,
crlfDelay: Infinity
});
let lineNumber = 0;
rl.on('line', (line) => {
lineNumber++;
const score = fuzzyScore(line, searchTerm);
if (score > 0) {
results.push({ line, lineNumber, score });
}
});
rl.on('close', () => {
results.sort((a, b) => b.score - a.score);
const totalResults = results.length;
const totalPages = Math.ceil(totalResults / pageSize);
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
const paginatedResults = results.slice(startIndex, endIndex);
// Process the results to extract key-value pairs if possible
const formattedResults = paginatedResults.map(({ score, ...result }) => {
// Try to format as key-value pair (common for ID data files)
const parts = result.line.split(/\s+/);
if (parts.length >= 2) {
const id = parts[0];
const value = parts.slice(1).join(' ');
return {
...result,
id,
value,
formatted: `${id}\t${value}`
};
}
return result;
});
resolve({
results: formattedResults,
pagination: {
page,
pageSize,
totalResults,
totalPages,
hasNextPage: page < totalPages,
hasPreviousPage: page > 1
}
});
});
rl.on('error', (err) => {
reject(err);
});
});
}
/**
* Check if a file exists in the data directory
* @param filename The filename to check
* @returns Boolean indicating if the file exists
*/
export function fileExists(filename: string): boolean {
const filePath = path.join(DATA_DIR, filename);
return fs.existsSync(filePath);
}
/**
* Get data file details
* @param filename The filename to get details for
* @returns Object with file details
*/
export function getFileDetails(filename: string): any {
try {
const filePath = path.join(DATA_DIR, filename);
if (!fs.existsSync(filePath)) {
return { exists: false };
}
const stats = fs.statSync(filePath);
const lineCount = getFileLineCount(filePath);
return {
exists: true,
size: stats.size,
lineCount,
created: stats.birthtime,
lastModified: stats.mtime
};
} catch (error) {
console.error(`Error getting file details for ${filename}:`, error);
return { exists: false, error: 'Error getting file details' };
}
}
/**
* Get the number of lines in a file
* @param filePath Path to the file
* @returns Number of lines in the file
*/
function getFileLineCount(filePath: string): number {
try {
const content = fs.readFileSync(filePath, 'utf8');
return content.split('\n').length;
} catch (error) {
console.error(`Error counting lines in ${filePath}:`, error);
return 0;
}
}
/**
* List all data files in the data directory
* @param fileType Optional filter for file type
* @returns Array of file names
*/
export function listDataFiles(fileType?: string): string[] {
try {
const files = fs.readdirSync(DATA_DIR);
if (fileType) {
return files.filter(file => file.endsWith(`.${fileType}`));
}
return files;
} catch (error) {
console.error("Error listing data files:", error);
return [];
}
}
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "osrs_wiki_search",
description: "Search the OSRS Wiki for pages matching a search term.",
inputSchema: convertZodToJsonSchema(OsrsWikiSearchSchema),
},
{
name: "osrs_wiki_get_page_info",
description: "Get information about specific pages on the OSRS Wiki.",
inputSchema: convertZodToJsonSchema(OsrsWikiGetPageInfoSchema),
},
{
name: "osrs_wiki_parse_page",
description: "Get the parsed HTML content of a specific OSRS Wiki page.",
inputSchema: convertZodToJsonSchema(OsrsWikiParsePageSchema),
},
{
name: "search_varptypes",
description: "Search the varptypes.txt file for player variables (varps) that store player state and progress.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_varbittypes",
description: "Search the varbittypes.txt file for variable bits (varbits) that store individual bits from varps.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_iftypes",
description: "Search the iftypes.txt file for interface definitions used in the game's UI.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_invtypes",
description: "Search the invtypes.txt file for inventory type definitions in the game.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_loctypes",
description: "Search the loctypes.txt file for location/object type definitions in the game world.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_npctypes",
description: "Search the npctypes.txt file for NPC (non-player character) definitions.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_objtypes",
description: "Search the objtypes.txt file for object/item definitions in the game.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_rowtypes",
description: "Search the rowtypes.txt file for row definitions used in various interfaces.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_seqtypes",
description: "Search the seqtypes.txt file for animation sequence definitions.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_soundtypes",
description: "Search the soundtypes.txt file for sound effect definitions in the game.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_spottypes",
description: "Search the spottypes.txt file for spot animation (graphical effect) definitions.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_spritetypes",
description: "Search the spritetypes.txt file for sprite image definitions used in the interface.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_tabletypes",
description: "Search the tabletypes.txt file for interface tab definitions.",
inputSchema: convertZodToJsonSchema(FileSearchSchema),
},
{
name: "search_data_file",
description: "Search any file in the data directory for matching entries.",
inputSchema: convertZodToJsonSchema(GenericFileSearchSchema),
},
{
name: "get_file_details",
description: "Get details about a file in the data directory.",
inputSchema: convertZodToJsonSchema(FileDetailsSchema),
},
{
name: "list_data_files",
description: "List available data files in the data directory.",
inputSchema: convertZodToJsonSchema(ListDataFilesSchema),
},
{
name: "lookup_player",
description: "Look up an OSRS player's stats (skills, bosses, clue scrolls, and activities) from the official hiscores.",
inputSchema: convertZodToJsonSchema(LookupPlayerSchema),
},
{
name: "search_ge_items",
description: "Search for Grand Exchange tradeable items by name. Uses an exact/prefix/substring match. Returns item IDs, names, buy limits, and alch values.",
inputSchema: convertZodToJsonSchema(SearchGeItemsSchema),
},
{
name: "get_ge_latest",
description: "Get the latest Grand Exchange high and low prices for a specific item by its ID.",
inputSchema: convertZodToJsonSchema(GeLatestSchema),
},
{
name: "get_ge_timeseries",
description: "Get historical time-series price data for an item at a given interval (5m, 1h, 6h, 24h). Returns up to 365 data points.",
inputSchema: convertZodToJsonSchema(GeTimeSeriesSchema),
},
]
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
switch (name) {
case "osrs_wiki_search":
const { search, limit = 10, offset = 0 } = OsrsWikiSearchSchema.parse(args);
const searchResponse = await osrsApiClient.get('', {
params: {
action: 'query',
list: 'search',
srsearch: search,
srlimit: limit,
sroffset: offset,
srprop: 'snippet|titlesnippet|sectiontitle'
}
});
return responseToString(searchResponse.data);
case "osrs_wiki_get_page_info":
const { titles } = OsrsWikiGetPageInfoSchema.parse(args);
const pageInfoResponse = await osrsApiClient.get('', {
params: {
action: 'query',
prop: 'info',
titles: titles
}
});
return responseToString(pageInfoResponse.data);
case "osrs_wiki_parse_page":
const { page } = OsrsWikiParsePageSchema.parse(args);
const parseResponse = await osrsApiClient.get('', {
params: {
action: 'parse',
page: page,
prop: 'text',
formatversion: 2
}
});
return responseToString(parseResponse.data?.parse?.text || 'Page content not found.');
case "search_varptypes":
case "search_varbittypes":
case "search_iftypes":
case "search_invtypes":
case "search_loctypes":
case "search_npctypes":
case "search_objtypes":
case "search_rowtypes":
case "search_seqtypes":
case "search_soundtypes":
case "search_spottypes":
case "search_spritetypes":
case "search_tabletypes":
const { query, page: filePage = 1, pageSize: filePageSize = 10 } = FileSearchSchema.parse(args);
const filename = `${name.replace('search_', '')}.txt`;
const filePath = path.join(DATA_DIR, filename);
if (!fileExists(filename)) {
return responseToString({ error: `${filename} not found in data directory` });
}
const fileResults = await searchFile(filePath, query, filePage, filePageSize);
return responseToString(fileResults);
case "search_data_file":
const { filename: genericFilename, query: searchQuery, page: genericFilePage = 1, pageSize: genericFilePageSize = 10 } = GenericFileSearchSchema.parse(args);
// Security check to prevent directory traversal
if (genericFilename.includes('..') || genericFilename.includes('/') || genericFilename.includes('\\')) {
throw new Error('Invalid filename');
}
if (!fileExists(genericFilename)) {
return responseToString({ error: `${genericFilename} not found in data directory` });
}
const genericFilePath = path.join(DATA_DIR, genericFilename);
const genericFileResults = await searchFile(genericFilePath, searchQuery, genericFilePage, genericFilePageSize);
return responseToString(genericFileResults);
case "get_file_details":
const { filename: detailsFilename } = FileDetailsSchema.parse(args);
// Security check to prevent directory traversal
if (detailsFilename.includes('..') || detailsFilename.includes('/') || detailsFilename.includes('\\')) {
throw new Error('Invalid filename');
}
const details = getFileDetails(detailsFilename);
return responseToString(details);
case "list_data_files":
const { fileType } = ListDataFilesSchema.parse(args);
const files = listDataFiles(fileType);
return responseToString({ files, path: DATA_DIR });
case "lookup_player":
const { playerName, gamemode } = LookupPlayerSchema.parse(args);
let playerStats: any;
if (gamemode) {
playerStats = await getStatsByGamemode(playerName, gamemode);
} else {
playerStats = await getStats(playerName);
}
return responseToString(playerStats);
case "search_ge_items": {
const { query, page: gePage, pageSize: gePageSize } = SearchGeItemsSchema.parse(args);
const geResults = await searchItems(query, gePage, gePageSize);
return responseToString(geResults);
}
case "get_ge_latest": {
const { itemId } = GeLatestSchema.parse(args);
const latest = await getLatest(itemId);
return responseToString(latest);
}
case "get_ge_timeseries": {
const { itemId: tsItemId, timestep } = GeTimeSeriesSchema.parse(args);
const series = await getTimeSeries(tsItemId, timestep);
return responseToString(series);
}
default:
throw new Error(`Unknown tool: ${name}`);
}
} catch (error) {
if (error instanceof z.ZodError) {
throw new Error(
`Invalid arguments: ${error.errors
.map((e) => `${e.path.join(".")}: ${e.message}`)
.join(", ")}`
);
}
const err = error as any;
if (axios.isAxiosError(err)) {
console.error("Axios Error Details:", {
message: err.message,
url: err.config?.url,
method: err.config?.method,
params: err.config?.params,
data: err.config?.data,
responseStatus: err.response?.status,
responseData: err.response?.data,
stack: err.stack
});
throw new Error(`Error executing tool ${name}: ${err.message}${err.response?.data ? ` - Wiki Response: ${JSON.stringify(err.response.data)}` : ''}`);
} else {
console.error("Error details:", {
message: err.message,
stack: err.stack,
name: err.name,
fullError: JSON.stringify(err, Object.getOwnPropertyNames(err), 2)
});
throw new Error(`Error executing tool ${name}: ${err.message}`);
}
}
});
async function main() {
try {
//console.log("Starting MCP OSRS Server...");
const transport = new StdioServerTransport();
await server.connect(transport);
//console.log("MCP OSRS Server running on stdio");
} catch (error) {
console.error("Error during startup:", error);
process.exit(1);
}
}
if (!process.env.JEST_WORKER_ID) {
main().catch((error) => {
console.error("Fatal error in main():", error);
process.exit(1);
});
}