@hemingweb/wordnook-mcp 0.0.0-stage → 1.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -2
- package/bin/wordnook-mcp.js +1629 -0
- package/package.json +64 -4
- package/public/data/en-core.json.gz +0 -0
- package/public/data/en-kaikki.json.gz +0 -0
- package/public/data/en-moby.json.gz +0 -0
|
@@ -0,0 +1,1629 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/mcp/server.ts
|
|
4
|
+
import http from "node:http";
|
|
5
|
+
import { McpServer as McpServer2 } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
6
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
7
|
+
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
|
8
|
+
|
|
9
|
+
// src/mcp/loader.ts
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import zlib from "node:zlib";
|
|
13
|
+
import readline from "node:readline";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
15
|
+
|
|
16
|
+
// src/services/lemmatizer.ts
|
|
17
|
+
function getLemmas(word) {
|
|
18
|
+
const clean = word.toLowerCase().trim();
|
|
19
|
+
if (clean.length < 3) return [];
|
|
20
|
+
const candidates = /* @__PURE__ */ new Set();
|
|
21
|
+
if (clean.endsWith("ing") && clean.length > 4) {
|
|
22
|
+
const base = clean.slice(0, -3);
|
|
23
|
+
candidates.add(base);
|
|
24
|
+
candidates.add(base + "e");
|
|
25
|
+
if (base.length > 2 && base[base.length - 1] === base[base.length - 2]) {
|
|
26
|
+
candidates.add(base.slice(0, -1));
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (clean.endsWith("ies") && clean.length > 4) {
|
|
30
|
+
candidates.add(clean.slice(0, -3) + "y");
|
|
31
|
+
}
|
|
32
|
+
if (clean.endsWith("es") && clean.length > 3) {
|
|
33
|
+
candidates.add(clean.slice(0, -2));
|
|
34
|
+
candidates.add(clean.slice(0, -1));
|
|
35
|
+
}
|
|
36
|
+
if (clean.endsWith("s") && !clean.endsWith("ss") && clean.length > 3) {
|
|
37
|
+
candidates.add(clean.slice(0, -1));
|
|
38
|
+
}
|
|
39
|
+
if (clean.endsWith("ed") && clean.length > 3) {
|
|
40
|
+
const base = clean.slice(0, -2);
|
|
41
|
+
candidates.add(base);
|
|
42
|
+
candidates.add(clean.slice(0, -1));
|
|
43
|
+
if (base.length > 2 && base[base.length - 1] === base[base.length - 2]) {
|
|
44
|
+
candidates.add(base.slice(0, -1));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (clean.endsWith("ly") && clean.length > 4) {
|
|
48
|
+
const base = clean.slice(0, -2);
|
|
49
|
+
candidates.add(base);
|
|
50
|
+
if (base.endsWith("i")) {
|
|
51
|
+
candidates.add(base.slice(0, -1) + "y");
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (clean.endsWith("er") && clean.length > 4) {
|
|
55
|
+
const base = clean.slice(0, -2);
|
|
56
|
+
candidates.add(base);
|
|
57
|
+
candidates.add(clean.slice(0, -1));
|
|
58
|
+
if (base.length > 2 && base[base.length - 1] === base[base.length - 2]) {
|
|
59
|
+
candidates.add(base.slice(0, -1));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (clean.endsWith("est") && clean.length > 5) {
|
|
63
|
+
const base = clean.slice(0, -3);
|
|
64
|
+
candidates.add(base);
|
|
65
|
+
if (base.length > 2 && base[base.length - 1] === base[base.length - 2]) {
|
|
66
|
+
candidates.add(base.slice(0, -1));
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return Array.from(candidates);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// src/services/trie.ts
|
|
73
|
+
var SearchIndex = class {
|
|
74
|
+
words = [];
|
|
75
|
+
clear() {
|
|
76
|
+
this.words = [];
|
|
77
|
+
}
|
|
78
|
+
insert(word) {
|
|
79
|
+
const clean = word.trim().toLowerCase();
|
|
80
|
+
if (!clean) return;
|
|
81
|
+
const idx = this.binarySearch(clean);
|
|
82
|
+
if (idx < 0) {
|
|
83
|
+
this.words.splice(-(idx + 1), 0, clean);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
has(word) {
|
|
87
|
+
const clean = word.trim().toLowerCase();
|
|
88
|
+
if (!clean || this.words.length === 0) return false;
|
|
89
|
+
return this.binarySearch(clean) >= 0;
|
|
90
|
+
}
|
|
91
|
+
loadWords(words) {
|
|
92
|
+
const cleanSet = /* @__PURE__ */ new Set();
|
|
93
|
+
for (let i = 0; i < words.length; i++) {
|
|
94
|
+
const w = words[i].trim().toLowerCase();
|
|
95
|
+
if (w) cleanSet.add(w);
|
|
96
|
+
}
|
|
97
|
+
this.words = Array.from(cleanSet).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
|
|
98
|
+
}
|
|
99
|
+
binarySearch(target) {
|
|
100
|
+
let low = 0;
|
|
101
|
+
let high = this.words.length - 1;
|
|
102
|
+
while (low <= high) {
|
|
103
|
+
const mid = low + high >> 1;
|
|
104
|
+
const midVal = this.words[mid];
|
|
105
|
+
if (midVal === target) return mid;
|
|
106
|
+
if (midVal < target) low = mid + 1;
|
|
107
|
+
else high = mid - 1;
|
|
108
|
+
}
|
|
109
|
+
return -(low + 1);
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Predictive prefix search for autocomplete as user types (sub-millisecond O(log N))
|
|
113
|
+
*/
|
|
114
|
+
autocomplete(prefix, limit = 8) {
|
|
115
|
+
const cleanPrefix = prefix.trim().toLowerCase();
|
|
116
|
+
if (!cleanPrefix || this.words.length === 0) return [];
|
|
117
|
+
let low = 0;
|
|
118
|
+
let high = this.words.length - 1;
|
|
119
|
+
let startIdx = -1;
|
|
120
|
+
while (low <= high) {
|
|
121
|
+
const mid = low + high >> 1;
|
|
122
|
+
if (this.words[mid].startsWith(cleanPrefix)) {
|
|
123
|
+
startIdx = mid;
|
|
124
|
+
high = mid - 1;
|
|
125
|
+
} else if (this.words[mid] < cleanPrefix) {
|
|
126
|
+
low = mid + 1;
|
|
127
|
+
} else {
|
|
128
|
+
high = mid - 1;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
if (startIdx === -1) return [];
|
|
132
|
+
const results = [];
|
|
133
|
+
for (let i = startIdx; i < this.words.length && results.length < limit; i++) {
|
|
134
|
+
if (this.words[i].startsWith(cleanPrefix)) {
|
|
135
|
+
results.push({ word: this.words[i], isFuzzy: false });
|
|
136
|
+
} else {
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
return results;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Fuzzy search for typo tolerance and inflection lemmatization ("Did you mean...?")
|
|
144
|
+
*/
|
|
145
|
+
fuzzySearch(query, maxDistance = 2, limit = 6) {
|
|
146
|
+
const target = query.trim().toLowerCase();
|
|
147
|
+
if (target.length < 3 || this.words.length === 0) return [];
|
|
148
|
+
const matches = [];
|
|
149
|
+
const seenWords = /* @__PURE__ */ new Set();
|
|
150
|
+
const lemmas = getLemmas(target);
|
|
151
|
+
for (const lemma of lemmas) {
|
|
152
|
+
if (this.has(lemma) && !seenWords.has(lemma)) {
|
|
153
|
+
matches.push({ word: lemma, distance: 0 });
|
|
154
|
+
seenWords.add(lemma);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
const targetLen = target.length;
|
|
158
|
+
const firstChar = target[0];
|
|
159
|
+
for (let i = 0; i < this.words.length; i++) {
|
|
160
|
+
const candidate = this.words[i];
|
|
161
|
+
if (candidate[0] !== firstChar) continue;
|
|
162
|
+
if (seenWords.has(candidate)) continue;
|
|
163
|
+
if (Math.abs(candidate.length - targetLen) > maxDistance) continue;
|
|
164
|
+
const dist = this.levenshtein(target, candidate, maxDistance);
|
|
165
|
+
if (dist <= maxDistance && dist > 0) {
|
|
166
|
+
matches.push({ word: candidate, distance: dist });
|
|
167
|
+
seenWords.add(candidate);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (matches.length < limit) {
|
|
171
|
+
for (let i = 0; i < this.words.length; i++) {
|
|
172
|
+
const candidate = this.words[i];
|
|
173
|
+
if (candidate[0] === firstChar) continue;
|
|
174
|
+
if (seenWords.has(candidate)) continue;
|
|
175
|
+
if (Math.abs(candidate.length - targetLen) > maxDistance) continue;
|
|
176
|
+
const dist = this.levenshtein(target, candidate, maxDistance);
|
|
177
|
+
if (dist <= maxDistance && dist > 0) {
|
|
178
|
+
matches.push({ word: candidate, distance: dist });
|
|
179
|
+
seenWords.add(candidate);
|
|
180
|
+
if (matches.length >= limit * 3) break;
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
matches.sort((a, b) => a.distance - b.distance || a.word.length - b.word.length);
|
|
185
|
+
return matches.slice(0, limit).map((m) => ({
|
|
186
|
+
word: m.word,
|
|
187
|
+
score: m.distance,
|
|
188
|
+
isFuzzy: true
|
|
189
|
+
}));
|
|
190
|
+
}
|
|
191
|
+
levenshtein(a, b, maxLimit) {
|
|
192
|
+
const la = a.length;
|
|
193
|
+
const lb = b.length;
|
|
194
|
+
if (Math.abs(la - lb) > maxLimit) return maxLimit + 1;
|
|
195
|
+
let row = Array.from({ length: lb + 1 }, (_, i) => i);
|
|
196
|
+
for (let i = 1; i <= la; i++) {
|
|
197
|
+
let nextRow = [i];
|
|
198
|
+
let minInRow = nextRow[0];
|
|
199
|
+
for (let j = 1; j <= lb; j++) {
|
|
200
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
201
|
+
const val = Math.min(
|
|
202
|
+
row[j] + 1,
|
|
203
|
+
// deletion
|
|
204
|
+
nextRow[j - 1] + 1,
|
|
205
|
+
// insertion
|
|
206
|
+
row[j - 1] + cost
|
|
207
|
+
// substitution
|
|
208
|
+
);
|
|
209
|
+
nextRow[j] = val;
|
|
210
|
+
minInRow = Math.min(minInRow, val);
|
|
211
|
+
}
|
|
212
|
+
if (minInRow > maxLimit) {
|
|
213
|
+
return maxLimit + 1;
|
|
214
|
+
}
|
|
215
|
+
row = nextRow;
|
|
216
|
+
}
|
|
217
|
+
return row[lb];
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
var activeIndex = new SearchIndex();
|
|
221
|
+
|
|
222
|
+
// src/services/storage.ts
|
|
223
|
+
var FAVORITES_KEY = "wordnook_favorites";
|
|
224
|
+
var HISTORY_KEY = "wordnook_history";
|
|
225
|
+
var ACTIVE_PACK_KEY = "wordnook_active_pack";
|
|
226
|
+
var THEME_KEY = "wordnook_theme";
|
|
227
|
+
var FONT_SIZE_KEY = "wordnook_font_size";
|
|
228
|
+
var MAX_HISTORY_ITEMS = 50;
|
|
229
|
+
var DEFAULT_CURATED_WOTD_WORDS = [
|
|
230
|
+
"serendipity",
|
|
231
|
+
"ephemeral",
|
|
232
|
+
"resilience",
|
|
233
|
+
"solitude",
|
|
234
|
+
"mellifluous",
|
|
235
|
+
"eloquent",
|
|
236
|
+
"ubiquitous",
|
|
237
|
+
"pragmatic",
|
|
238
|
+
"luminous",
|
|
239
|
+
"nostalgia",
|
|
240
|
+
"catalyst",
|
|
241
|
+
"enigmatic",
|
|
242
|
+
"harmony",
|
|
243
|
+
"lucid",
|
|
244
|
+
"tenacious",
|
|
245
|
+
"sonorous",
|
|
246
|
+
"halcyon",
|
|
247
|
+
"epiphany",
|
|
248
|
+
"cadence",
|
|
249
|
+
"iridescent",
|
|
250
|
+
"benevolence",
|
|
251
|
+
"symphony",
|
|
252
|
+
"ethereal",
|
|
253
|
+
"labyrinth",
|
|
254
|
+
"tranquility",
|
|
255
|
+
"aurora",
|
|
256
|
+
"verve",
|
|
257
|
+
"zenith",
|
|
258
|
+
"quintessence"
|
|
259
|
+
];
|
|
260
|
+
var LocalStorageService = class {
|
|
261
|
+
safeSetItem(key, value) {
|
|
262
|
+
try {
|
|
263
|
+
localStorage.setItem(key, value);
|
|
264
|
+
return true;
|
|
265
|
+
} catch (e) {
|
|
266
|
+
console.warn(`Could not set localStorage item "${key}":`, e);
|
|
267
|
+
return false;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
getActivePackId() {
|
|
271
|
+
try {
|
|
272
|
+
const id = localStorage.getItem(ACTIVE_PACK_KEY) || "en-core";
|
|
273
|
+
if (id === "en-moby") return "en-core";
|
|
274
|
+
return id;
|
|
275
|
+
} catch {
|
|
276
|
+
return "en-core";
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
setActivePackId(packId) {
|
|
280
|
+
if (this.safeSetItem(ACTIVE_PACK_KEY, packId)) {
|
|
281
|
+
if (typeof window !== "undefined") {
|
|
282
|
+
window.dispatchEvent(new CustomEvent("wordnook_pack_changed", { detail: { packId } }));
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
getFavorites() {
|
|
287
|
+
try {
|
|
288
|
+
const raw = localStorage.getItem(FAVORITES_KEY);
|
|
289
|
+
return raw ? JSON.parse(raw) : [];
|
|
290
|
+
} catch {
|
|
291
|
+
return [];
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
isFavorite(word) {
|
|
295
|
+
const list = this.getFavorites();
|
|
296
|
+
const clean = word.toLowerCase().trim();
|
|
297
|
+
return list.some((item) => item.word.toLowerCase() === clean);
|
|
298
|
+
}
|
|
299
|
+
toggleFavorite(word, preview) {
|
|
300
|
+
const list = this.getFavorites();
|
|
301
|
+
const clean = word.toLowerCase().trim();
|
|
302
|
+
if (!clean) return false;
|
|
303
|
+
const existingIndex = list.findIndex((item) => item.word.toLowerCase() === clean);
|
|
304
|
+
let isSaved = false;
|
|
305
|
+
if (existingIndex >= 0) {
|
|
306
|
+
list.splice(existingIndex, 1);
|
|
307
|
+
} else {
|
|
308
|
+
list.unshift({ word: clean, savedAt: Date.now(), preview });
|
|
309
|
+
isSaved = true;
|
|
310
|
+
}
|
|
311
|
+
const ok = this.safeSetItem(FAVORITES_KEY, JSON.stringify(list));
|
|
312
|
+
if (ok && typeof window !== "undefined") {
|
|
313
|
+
window.dispatchEvent(new Event("wordnook_favorites_changed"));
|
|
314
|
+
}
|
|
315
|
+
return isSaved;
|
|
316
|
+
}
|
|
317
|
+
exportFavoritesJSON() {
|
|
318
|
+
return JSON.stringify(this.getFavorites(), null, 2);
|
|
319
|
+
}
|
|
320
|
+
importFavoritesJSON(jsonString) {
|
|
321
|
+
try {
|
|
322
|
+
const imported = JSON.parse(jsonString);
|
|
323
|
+
if (Array.isArray(imported)) {
|
|
324
|
+
const current = this.getFavorites();
|
|
325
|
+
const mergedMap = /* @__PURE__ */ new Map();
|
|
326
|
+
for (const item of [...current, ...imported]) {
|
|
327
|
+
if (item && typeof item.word === "string") {
|
|
328
|
+
const clean = item.word.trim().toLowerCase();
|
|
329
|
+
if (clean && clean.length <= 100) {
|
|
330
|
+
const preview = typeof item.preview === "string" ? item.preview.slice(0, 500) : void 0;
|
|
331
|
+
const savedAt = typeof item.savedAt === "number" && Number.isFinite(item.savedAt) ? item.savedAt : Date.now();
|
|
332
|
+
mergedMap.set(clean, { word: clean, savedAt, preview });
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
const ok = this.safeSetItem(FAVORITES_KEY, JSON.stringify(Array.from(mergedMap.values())));
|
|
337
|
+
if (ok && typeof window !== "undefined") {
|
|
338
|
+
window.dispatchEvent(new Event("wordnook_favorites_changed"));
|
|
339
|
+
}
|
|
340
|
+
return ok;
|
|
341
|
+
}
|
|
342
|
+
} catch (e) {
|
|
343
|
+
console.error("Import failed", e);
|
|
344
|
+
}
|
|
345
|
+
return false;
|
|
346
|
+
}
|
|
347
|
+
getHistory() {
|
|
348
|
+
try {
|
|
349
|
+
const raw = localStorage.getItem(HISTORY_KEY);
|
|
350
|
+
return raw ? JSON.parse(raw) : [];
|
|
351
|
+
} catch {
|
|
352
|
+
return [];
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
addToHistory(word) {
|
|
356
|
+
const clean = word.toLowerCase().trim();
|
|
357
|
+
if (!clean) return;
|
|
358
|
+
let list = this.getHistory().filter((item) => item.word.toLowerCase() !== clean);
|
|
359
|
+
list.unshift({ word: clean, searchedAt: Date.now() });
|
|
360
|
+
if (list.length > MAX_HISTORY_ITEMS) {
|
|
361
|
+
list = list.slice(0, MAX_HISTORY_ITEMS);
|
|
362
|
+
}
|
|
363
|
+
this.safeSetItem(HISTORY_KEY, JSON.stringify(list));
|
|
364
|
+
}
|
|
365
|
+
clearHistory() {
|
|
366
|
+
try {
|
|
367
|
+
localStorage.removeItem(HISTORY_KEY);
|
|
368
|
+
} catch (e) {
|
|
369
|
+
console.warn("Could not clear history", e);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
getTheme() {
|
|
373
|
+
try {
|
|
374
|
+
const val = localStorage.getItem(THEME_KEY);
|
|
375
|
+
if (val === "light" || val === "dark" || val === "system") return val;
|
|
376
|
+
return "system";
|
|
377
|
+
} catch {
|
|
378
|
+
return "system";
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
setTheme(theme) {
|
|
382
|
+
if (this.safeSetItem(THEME_KEY, theme)) {
|
|
383
|
+
if (typeof window !== "undefined") {
|
|
384
|
+
window.dispatchEvent(new CustomEvent("wordnook_theme_changed", { detail: { theme } }));
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
getFontSize() {
|
|
389
|
+
try {
|
|
390
|
+
const val = localStorage.getItem(FONT_SIZE_KEY);
|
|
391
|
+
if (val === "small" || val === "normal" || val === "large" || val === "xlarge") return val;
|
|
392
|
+
return "normal";
|
|
393
|
+
} catch {
|
|
394
|
+
return "normal";
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
setFontSize(fontSize) {
|
|
398
|
+
if (this.safeSetItem(FONT_SIZE_KEY, fontSize)) {
|
|
399
|
+
if (typeof window !== "undefined") {
|
|
400
|
+
window.dispatchEvent(new CustomEvent("wordnook_font_size_changed", { detail: { fontSize } }));
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Deterministic Word of the Day derived from the calendar date.
|
|
406
|
+
* Completely client-side and identical for all users globally offline.
|
|
407
|
+
*/
|
|
408
|
+
getWordOfTheDay(curatedList) {
|
|
409
|
+
const list = curatedList && curatedList.length > 0 ? curatedList : DEFAULT_CURATED_WOTD_WORDS;
|
|
410
|
+
const now = /* @__PURE__ */ new Date();
|
|
411
|
+
const dateSeed = now.getFullYear() * 1e4 + (now.getMonth() + 1) * 100 + now.getDate();
|
|
412
|
+
const index = Math.abs(dateSeed) % list.length;
|
|
413
|
+
return list[index];
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
var storageService = new LocalStorageService();
|
|
417
|
+
|
|
418
|
+
// src/mcp/loader.ts
|
|
419
|
+
var WordNookDataLoader = class {
|
|
420
|
+
dataDir;
|
|
421
|
+
entries = /* @__PURE__ */ new Map();
|
|
422
|
+
packEntries = /* @__PURE__ */ new Map();
|
|
423
|
+
thesaurus = /* @__PURE__ */ new Map();
|
|
424
|
+
manifests = /* @__PURE__ */ new Map();
|
|
425
|
+
searchIndex = new SearchIndex();
|
|
426
|
+
isCoreLoaded = false;
|
|
427
|
+
isThesaurusLoaded = false;
|
|
428
|
+
isKaikkiLoaded = false;
|
|
429
|
+
activePackId = "en-core";
|
|
430
|
+
constructor(options = {}) {
|
|
431
|
+
this.dataDir = this.resolveDataDirectory(options.dataDir);
|
|
432
|
+
if (options.activePack) {
|
|
433
|
+
this.activePackId = options.activePack;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
resolveDataDirectory(customDir) {
|
|
437
|
+
if (customDir) {
|
|
438
|
+
return path.resolve(customDir);
|
|
439
|
+
}
|
|
440
|
+
if (process.env.WORDNOOK_DATA_DIR) {
|
|
441
|
+
return path.resolve(process.env.WORDNOOK_DATA_DIR);
|
|
442
|
+
}
|
|
443
|
+
const candidates = [
|
|
444
|
+
path.resolve(process.cwd(), "public/data"),
|
|
445
|
+
path.resolve(process.cwd(), "data")
|
|
446
|
+
];
|
|
447
|
+
try {
|
|
448
|
+
const currentDir = path.dirname(fileURLToPath(import.meta.url));
|
|
449
|
+
candidates.push(
|
|
450
|
+
path.resolve(currentDir, "../../public/data"),
|
|
451
|
+
path.resolve(currentDir, "../public/data"),
|
|
452
|
+
path.resolve(currentDir, "../../../public/data")
|
|
453
|
+
);
|
|
454
|
+
} catch {
|
|
455
|
+
}
|
|
456
|
+
for (const dir of candidates) {
|
|
457
|
+
if (dir && fs.existsSync(dir) && fs.existsSync(path.join(dir, "en-core.json.gz"))) {
|
|
458
|
+
return dir;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
return path.resolve(process.cwd(), "public/data");
|
|
462
|
+
}
|
|
463
|
+
getDataDirectory() {
|
|
464
|
+
return this.dataDir;
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Initializes the core dictionary in-memory index
|
|
468
|
+
*/
|
|
469
|
+
async init() {
|
|
470
|
+
if (this.isCoreLoaded) return;
|
|
471
|
+
const coreFile = path.join(this.dataDir, "en-core.json.gz");
|
|
472
|
+
if (!fs.existsSync(coreFile)) {
|
|
473
|
+
throw new Error(
|
|
474
|
+
`WordNook core dictionary file not found at: ${coreFile}
|
|
475
|
+
|
|
476
|
+
To resolve this:
|
|
477
|
+
1. Generate the offline dictionary dataset by running: npm run ingest
|
|
478
|
+
2. Or specify a custom data directory with: --data-dir <path> or WORDNOOK_DATA_DIR=<path>`
|
|
479
|
+
);
|
|
480
|
+
}
|
|
481
|
+
const fileStream = fs.createReadStream(coreFile);
|
|
482
|
+
const unzipStream = zlib.createGunzip();
|
|
483
|
+
const rl = readline.createInterface({
|
|
484
|
+
input: fileStream.pipe(unzipStream),
|
|
485
|
+
crlfDelay: Infinity
|
|
486
|
+
});
|
|
487
|
+
const wordList = [];
|
|
488
|
+
for await (const line of rl) {
|
|
489
|
+
if (!line) continue;
|
|
490
|
+
try {
|
|
491
|
+
const record = JSON.parse(line);
|
|
492
|
+
if (record.type === "manifest" && record.data) {
|
|
493
|
+
this.manifests.set(record.data.id || "en-core", record.data);
|
|
494
|
+
} else if (record.type === "entry" && record.data && record.data.word) {
|
|
495
|
+
const w = record.data.word.toLowerCase().trim();
|
|
496
|
+
record.data.sourcePackId = record.data.sourcePackId || "en-core";
|
|
497
|
+
this.entries.set(w, record.data);
|
|
498
|
+
let corePack = this.packEntries.get("en-core");
|
|
499
|
+
if (!corePack) {
|
|
500
|
+
corePack = /* @__PURE__ */ new Map();
|
|
501
|
+
this.packEntries.set("en-core", corePack);
|
|
502
|
+
}
|
|
503
|
+
corePack.set(w, record.data);
|
|
504
|
+
wordList.push(w);
|
|
505
|
+
}
|
|
506
|
+
} catch {
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
this.searchIndex.loadWords(wordList);
|
|
510
|
+
this.isCoreLoaded = true;
|
|
511
|
+
if (this.activePackId && this.activePackId !== "en-core") {
|
|
512
|
+
await this.ensurePackLoaded(this.activePackId);
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Lazy-loads thesaurus data (en-moby.json.gz) into memory
|
|
517
|
+
*/
|
|
518
|
+
async ensureThesaurusLoaded() {
|
|
519
|
+
if (this.isThesaurusLoaded) return;
|
|
520
|
+
const mobyFile = path.join(this.dataDir, "en-moby.json.gz");
|
|
521
|
+
if (fs.existsSync(mobyFile)) {
|
|
522
|
+
const fileStream = fs.createReadStream(mobyFile);
|
|
523
|
+
const unzipStream = zlib.createGunzip();
|
|
524
|
+
const rl = readline.createInterface({
|
|
525
|
+
input: fileStream.pipe(unzipStream),
|
|
526
|
+
crlfDelay: Infinity
|
|
527
|
+
});
|
|
528
|
+
for await (const line of rl) {
|
|
529
|
+
if (!line) continue;
|
|
530
|
+
try {
|
|
531
|
+
const record = JSON.parse(line);
|
|
532
|
+
if (record.type === "manifest" && record.data) {
|
|
533
|
+
this.manifests.set(record.data.id || "en-moby", record.data);
|
|
534
|
+
} else if (record.type === "thesaurus" && record.data && record.data.word) {
|
|
535
|
+
const w = record.data.word.toLowerCase().trim();
|
|
536
|
+
this.thesaurus.set(w, record.data);
|
|
537
|
+
}
|
|
538
|
+
} catch {
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
this.isThesaurusLoaded = true;
|
|
543
|
+
}
|
|
544
|
+
/**
|
|
545
|
+
* Lazy-loads Kaikki Wiktionary pack (en-kaikki.json.gz) into memory
|
|
546
|
+
*/
|
|
547
|
+
async ensureKaikkiLoaded() {
|
|
548
|
+
if (this.isKaikkiLoaded) return;
|
|
549
|
+
const kaikkiFile = path.join(this.dataDir, "en-kaikki.json.gz");
|
|
550
|
+
if (fs.existsSync(kaikkiFile)) {
|
|
551
|
+
const fileStream = fs.createReadStream(kaikkiFile);
|
|
552
|
+
const unzipStream = zlib.createGunzip();
|
|
553
|
+
const rl = readline.createInterface({
|
|
554
|
+
input: fileStream.pipe(unzipStream),
|
|
555
|
+
crlfDelay: Infinity
|
|
556
|
+
});
|
|
557
|
+
const newWords = [];
|
|
558
|
+
for await (const line of rl) {
|
|
559
|
+
if (!line) continue;
|
|
560
|
+
try {
|
|
561
|
+
const record = JSON.parse(line);
|
|
562
|
+
if (record.type === "manifest" && record.data) {
|
|
563
|
+
this.manifests.set(record.data.id || "en-kaikki", record.data);
|
|
564
|
+
} else if (record.type === "entry" && record.data && record.data.word) {
|
|
565
|
+
const w = record.data.word.toLowerCase().trim();
|
|
566
|
+
record.data.sourcePackId = record.data.sourcePackId || "en-kaikki";
|
|
567
|
+
let packMap = this.packEntries.get("en-kaikki");
|
|
568
|
+
if (!packMap) {
|
|
569
|
+
packMap = /* @__PURE__ */ new Map();
|
|
570
|
+
this.packEntries.set("en-kaikki", packMap);
|
|
571
|
+
}
|
|
572
|
+
packMap.set(w, record.data);
|
|
573
|
+
if (!this.entries.has(w)) {
|
|
574
|
+
this.entries.set(w, record.data);
|
|
575
|
+
newWords.push(w);
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
} catch {
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
for (const w of newWords) {
|
|
582
|
+
this.searchIndex.insert(w);
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
this.isKaikkiLoaded = true;
|
|
586
|
+
}
|
|
587
|
+
/**
|
|
588
|
+
* Ensures a specific data pack is loaded into memory
|
|
589
|
+
*/
|
|
590
|
+
async ensurePackLoaded(packId) {
|
|
591
|
+
if (!packId || packId === "en-core") return;
|
|
592
|
+
if (packId === "en-kaikki") {
|
|
593
|
+
await this.ensureKaikkiLoaded();
|
|
594
|
+
} else if (packId === "en-moby") {
|
|
595
|
+
await this.ensureThesaurusLoaded();
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
getActivePackId() {
|
|
599
|
+
return this.activePackId;
|
|
600
|
+
}
|
|
601
|
+
async setActivePackId(packId) {
|
|
602
|
+
const cleanId = packId.trim().toLowerCase();
|
|
603
|
+
const available = this.listPacks().map((p) => p.id);
|
|
604
|
+
if (!available.includes(cleanId)) {
|
|
605
|
+
return {
|
|
606
|
+
success: false,
|
|
607
|
+
activePack: this.activePackId,
|
|
608
|
+
message: `Pack "${packId}" not found. Available packs: ${available.join(", ")}`
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
await this.ensurePackLoaded(cleanId);
|
|
612
|
+
this.activePackId = cleanId;
|
|
613
|
+
return {
|
|
614
|
+
success: true,
|
|
615
|
+
activePack: this.activePackId,
|
|
616
|
+
message: `Active dictionary pack set to "${this.activePackId}".`
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Looks up a word definition with automatic morphological lemmatization fallback.
|
|
621
|
+
* If packId is specified, searches strictly within that pack.
|
|
622
|
+
* Otherwise, searches active pack first, falling back to core dictionary.
|
|
623
|
+
*/
|
|
624
|
+
lookupWord(query, packId, includeEtymology = true) {
|
|
625
|
+
const clean = query.trim().toLowerCase();
|
|
626
|
+
if (!clean) {
|
|
627
|
+
return { found: false, originalQuery: query };
|
|
628
|
+
}
|
|
629
|
+
const explicitPack = packId ? this.packEntries.get(packId) : void 0;
|
|
630
|
+
if (packId && !explicitPack) {
|
|
631
|
+
return {
|
|
632
|
+
found: false,
|
|
633
|
+
originalQuery: query,
|
|
634
|
+
suggestions: []
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
const primaryMap = explicitPack || (this.activePackId ? this.packEntries.get(this.activePackId) : void 0) || this.entries;
|
|
638
|
+
const directEntry = primaryMap.get(clean);
|
|
639
|
+
if (directEntry) {
|
|
640
|
+
return {
|
|
641
|
+
found: true,
|
|
642
|
+
originalQuery: query,
|
|
643
|
+
isLemma: false,
|
|
644
|
+
entry: this.toUnifiedEntry(directEntry, includeEtymology)
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
if (!explicitPack && primaryMap !== this.entries) {
|
|
648
|
+
const fallbackEntry = this.entries.get(clean);
|
|
649
|
+
if (fallbackEntry) {
|
|
650
|
+
return {
|
|
651
|
+
found: true,
|
|
652
|
+
originalQuery: query,
|
|
653
|
+
isLemma: false,
|
|
654
|
+
entry: this.toUnifiedEntry(fallbackEntry, includeEtymology)
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
const lemmas = getLemmas(clean);
|
|
659
|
+
for (const lemma of lemmas) {
|
|
660
|
+
const lemmaEntry = primaryMap.get(lemma) || (!explicitPack ? this.entries.get(lemma) : void 0);
|
|
661
|
+
if (lemmaEntry) {
|
|
662
|
+
return {
|
|
663
|
+
found: true,
|
|
664
|
+
originalQuery: query,
|
|
665
|
+
isLemma: true,
|
|
666
|
+
rootWord: lemma,
|
|
667
|
+
entry: this.toUnifiedEntry(lemmaEntry, includeEtymology)
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
const suggestions = this.searchIndex.fuzzySearch(clean, 2, 5);
|
|
672
|
+
return {
|
|
673
|
+
found: false,
|
|
674
|
+
originalQuery: query,
|
|
675
|
+
suggestions
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
/**
|
|
679
|
+
* Performs prefix autocomplete and fuzzy typo matching
|
|
680
|
+
*/
|
|
681
|
+
searchWords(query, limit = 10, fuzzy = true) {
|
|
682
|
+
const clean = query.trim().toLowerCase();
|
|
683
|
+
if (!clean) return [];
|
|
684
|
+
const prefixResults = this.searchIndex.autocomplete(clean, limit);
|
|
685
|
+
if (prefixResults.length >= limit || !fuzzy) {
|
|
686
|
+
return prefixResults;
|
|
687
|
+
}
|
|
688
|
+
const seen = new Set(prefixResults.map((s) => s.word));
|
|
689
|
+
const fuzzyLimit = limit - prefixResults.length;
|
|
690
|
+
const fuzzyResults = this.searchIndex.fuzzySearch(clean, 2, fuzzyLimit);
|
|
691
|
+
const merged = [...prefixResults];
|
|
692
|
+
for (const item of fuzzyResults) {
|
|
693
|
+
if (!seen.has(item.word)) {
|
|
694
|
+
seen.add(item.word);
|
|
695
|
+
merged.push(item);
|
|
696
|
+
}
|
|
697
|
+
if (merged.length >= limit) break;
|
|
698
|
+
}
|
|
699
|
+
return merged;
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Retrieves synonyms and antonyms from both core definitions and thesaurus pack
|
|
703
|
+
*/
|
|
704
|
+
async findSynonyms(word, partOfSpeech, limit = 20) {
|
|
705
|
+
await this.ensureThesaurusLoaded();
|
|
706
|
+
const clean = word.trim().toLowerCase();
|
|
707
|
+
const synSet = /* @__PURE__ */ new Set();
|
|
708
|
+
const antSet = /* @__PURE__ */ new Set();
|
|
709
|
+
const sources = [];
|
|
710
|
+
const entry = this.entries.get(clean);
|
|
711
|
+
if (entry) {
|
|
712
|
+
sources.push("Wordset / Core Dictionary");
|
|
713
|
+
for (const m of entry.meanings || []) {
|
|
714
|
+
if (partOfSpeech && m.partOfSpeech.toLowerCase() !== partOfSpeech.toLowerCase()) {
|
|
715
|
+
continue;
|
|
716
|
+
}
|
|
717
|
+
for (const s of m.synonyms || []) synSet.add(s.toLowerCase());
|
|
718
|
+
for (const a of m.antonyms || []) antSet.add(a.toLowerCase());
|
|
719
|
+
for (const d of m.definitions || []) {
|
|
720
|
+
for (const s of d.synonyms || []) synSet.add(s.toLowerCase());
|
|
721
|
+
for (const a of d.antonyms || []) antSet.add(a.toLowerCase());
|
|
722
|
+
}
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
const moby = this.thesaurus.get(clean);
|
|
726
|
+
if (moby) {
|
|
727
|
+
sources.push("Moby Thesaurus II");
|
|
728
|
+
for (const s of moby.synonyms || []) synSet.add(s.toLowerCase());
|
|
729
|
+
for (const a of moby.antonyms || []) antSet.add(a.toLowerCase());
|
|
730
|
+
}
|
|
731
|
+
synSet.delete(clean);
|
|
732
|
+
antSet.delete(clean);
|
|
733
|
+
return {
|
|
734
|
+
word: clean,
|
|
735
|
+
synonyms: Array.from(synSet).slice(0, limit),
|
|
736
|
+
antonyms: Array.from(antSet).slice(0, limit),
|
|
737
|
+
partOfSpeech,
|
|
738
|
+
sources
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Inflection analysis using the morphological lemmatizer
|
|
743
|
+
*/
|
|
744
|
+
lemmatizeWord(word) {
|
|
745
|
+
const clean = word.trim().toLowerCase();
|
|
746
|
+
const lemmas = getLemmas(clean);
|
|
747
|
+
return {
|
|
748
|
+
word: clean,
|
|
749
|
+
lemmas
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
/**
|
|
753
|
+
* Deterministic Word of the Day derived from calendar date
|
|
754
|
+
*/
|
|
755
|
+
getWordOfTheDay(dateStr) {
|
|
756
|
+
const now = dateStr ? new Date(dateStr) : /* @__PURE__ */ new Date();
|
|
757
|
+
const dateSeed = now.getFullYear() * 1e4 + (now.getMonth() + 1) * 100 + now.getDate();
|
|
758
|
+
const index = Math.abs(dateSeed) % DEFAULT_CURATED_WOTD_WORDS.length;
|
|
759
|
+
const word = DEFAULT_CURATED_WOTD_WORDS[index];
|
|
760
|
+
const rawEntry = this.entries.get(word);
|
|
761
|
+
const isoDate = now.toISOString().split("T")[0];
|
|
762
|
+
return {
|
|
763
|
+
date: isoDate,
|
|
764
|
+
word,
|
|
765
|
+
entry: rawEntry ? this.toUnifiedEntry(rawEntry, true) : void 0
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Returns a sample of random curated words from the vocabulary
|
|
770
|
+
*/
|
|
771
|
+
getRandomWord(count = 1, minDefinitions = 1) {
|
|
772
|
+
const results = [];
|
|
773
|
+
const allWords = Array.from(this.entries.keys());
|
|
774
|
+
if (allWords.length === 0) return results;
|
|
775
|
+
const targetCount = Math.max(1, Math.min(count, 10));
|
|
776
|
+
let attempts = 0;
|
|
777
|
+
while (results.length < targetCount && attempts < targetCount * 20) {
|
|
778
|
+
attempts++;
|
|
779
|
+
const randWord = allWords[Math.floor(Math.random() * allWords.length)];
|
|
780
|
+
const raw = this.entries.get(randWord);
|
|
781
|
+
if (raw && (raw.meanings || []).length >= minDefinitions) {
|
|
782
|
+
results.push(this.toUnifiedEntry(raw, true));
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
return results;
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Lists available and loaded data packs
|
|
789
|
+
*/
|
|
790
|
+
listPacks() {
|
|
791
|
+
const list = [];
|
|
792
|
+
if (this.manifests.has("en-core")) {
|
|
793
|
+
list.push(this.manifests.get("en-core"));
|
|
794
|
+
} else {
|
|
795
|
+
list.push({
|
|
796
|
+
id: "en-core",
|
|
797
|
+
title: "English Core Dictionary",
|
|
798
|
+
type: "dictionary",
|
|
799
|
+
lang: "en-US",
|
|
800
|
+
version: "1.0.0",
|
|
801
|
+
entryCount: this.entries.size,
|
|
802
|
+
attribution: {
|
|
803
|
+
id: "wordset",
|
|
804
|
+
name: "Wordset Dictionary",
|
|
805
|
+
license: "CC-BY-SA 4.0 / WordNet 3.0",
|
|
806
|
+
url: "https://github.com/wordset/wordset-dictionary"
|
|
807
|
+
}
|
|
808
|
+
});
|
|
809
|
+
}
|
|
810
|
+
const mobyFile = path.join(this.dataDir, "en-moby.json.gz");
|
|
811
|
+
if (fs.existsSync(mobyFile)) {
|
|
812
|
+
list.push({
|
|
813
|
+
id: "en-moby",
|
|
814
|
+
title: "Moby Thesaurus II",
|
|
815
|
+
type: "thesaurus",
|
|
816
|
+
lang: "en-US",
|
|
817
|
+
version: "1.0.0",
|
|
818
|
+
entryCount: this.thesaurus.size || 30195,
|
|
819
|
+
attribution: {
|
|
820
|
+
id: "moby",
|
|
821
|
+
name: "Moby Thesaurus II by Grady Ward",
|
|
822
|
+
license: "Public Domain",
|
|
823
|
+
url: "https://www.gutenberg.org/ebooks/3202"
|
|
824
|
+
}
|
|
825
|
+
});
|
|
826
|
+
}
|
|
827
|
+
const kaikkiFile = path.join(this.dataDir, "en-kaikki.json.gz");
|
|
828
|
+
if (fs.existsSync(kaikkiFile)) {
|
|
829
|
+
list.push({
|
|
830
|
+
id: "en-kaikki",
|
|
831
|
+
title: "Wiktionary (via Kaikki.org)",
|
|
832
|
+
type: "dictionary",
|
|
833
|
+
lang: "en-US",
|
|
834
|
+
version: "1.0.0",
|
|
835
|
+
entryCount: 379894,
|
|
836
|
+
attribution: {
|
|
837
|
+
id: "kaikki",
|
|
838
|
+
name: "Kaikki.org Wiktionary Data",
|
|
839
|
+
license: "CC-BY-SA 4.0",
|
|
840
|
+
url: "https://kaikki.org/"
|
|
841
|
+
}
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
return list;
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Summarizes server memory and vocabulary statistics
|
|
848
|
+
*/
|
|
849
|
+
getStats() {
|
|
850
|
+
const loaded = ["en-core"];
|
|
851
|
+
if (this.isThesaurusLoaded) loaded.push("en-moby");
|
|
852
|
+
if (this.isKaikkiLoaded) loaded.push("en-kaikki");
|
|
853
|
+
return {
|
|
854
|
+
totalWords: this.entries.size,
|
|
855
|
+
thesaurusWords: this.thesaurus.size,
|
|
856
|
+
activePack: this.activePackId,
|
|
857
|
+
loadedPacks: loaded,
|
|
858
|
+
dataDirectory: this.dataDir
|
|
859
|
+
};
|
|
860
|
+
}
|
|
861
|
+
toUnifiedEntry(raw, includeEtymology) {
|
|
862
|
+
const entry = {
|
|
863
|
+
word: raw.word,
|
|
864
|
+
phonetic: raw.phonetic,
|
|
865
|
+
meanings: raw.meanings || []
|
|
866
|
+
};
|
|
867
|
+
if (includeEtymology && raw.etymology) {
|
|
868
|
+
entry.etymology = raw.etymology;
|
|
869
|
+
}
|
|
870
|
+
if (raw.attribution) {
|
|
871
|
+
entry.sources = [raw.attribution];
|
|
872
|
+
}
|
|
873
|
+
const thes = this.thesaurus.get(raw.word.toLowerCase());
|
|
874
|
+
if (thes) {
|
|
875
|
+
entry.thesaurus = {
|
|
876
|
+
synonyms: thes.synonyms || [],
|
|
877
|
+
antonyms: thes.antonyms || []
|
|
878
|
+
};
|
|
879
|
+
}
|
|
880
|
+
return entry;
|
|
881
|
+
}
|
|
882
|
+
};
|
|
883
|
+
|
|
884
|
+
// src/mcp/tools.ts
|
|
885
|
+
import { z } from "zod";
|
|
886
|
+
function registerTools(server, loader) {
|
|
887
|
+
server.tool(
|
|
888
|
+
"lookup_word",
|
|
889
|
+
'Look up definition, phonetics, parts of speech, examples, etymology, and synonyms for a word. Automatically handles inflected forms (e.g. "running" -> "run").',
|
|
890
|
+
{
|
|
891
|
+
word: z.string().describe("The English word to look up"),
|
|
892
|
+
packId: z.string().optional().describe("Optional specific dictionary pack ID (defaults to active pack)"),
|
|
893
|
+
includeEtymology: z.boolean().optional().default(true).describe("Whether to include etymology/origin information")
|
|
894
|
+
},
|
|
895
|
+
async ({ word, packId, includeEtymology }) => {
|
|
896
|
+
if (packId) {
|
|
897
|
+
await loader.ensurePackLoaded(packId);
|
|
898
|
+
}
|
|
899
|
+
const result = loader.lookupWord(word, packId, includeEtymology);
|
|
900
|
+
if (!result.found) {
|
|
901
|
+
let text = `### "${word}" not found in WordNook.
|
|
902
|
+
|
|
903
|
+
`;
|
|
904
|
+
if (result.suggestions && result.suggestions.length > 0) {
|
|
905
|
+
text += `**Did you mean?**
|
|
906
|
+
`;
|
|
907
|
+
for (const s of result.suggestions) {
|
|
908
|
+
text += `- **${s.word}**${s.score ? ` (edit distance: ${s.score})` : ""}
|
|
909
|
+
`;
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
return {
|
|
913
|
+
content: [{ type: "text", text }]
|
|
914
|
+
};
|
|
915
|
+
}
|
|
916
|
+
const entry = result.entry;
|
|
917
|
+
let md = "";
|
|
918
|
+
if (result.isLemma && result.rootWord) {
|
|
919
|
+
md += `> *Showing root form: **${result.rootWord}** (derived from "${result.originalQuery}")*
|
|
920
|
+
|
|
921
|
+
`;
|
|
922
|
+
}
|
|
923
|
+
md += `# ${entry.word}
|
|
924
|
+
`;
|
|
925
|
+
if (entry.phonetic) {
|
|
926
|
+
md += `*${entry.phonetic}*
|
|
927
|
+
|
|
928
|
+
`;
|
|
929
|
+
}
|
|
930
|
+
for (const m of entry.meanings || []) {
|
|
931
|
+
md += `### ${m.partOfSpeech}
|
|
932
|
+
`;
|
|
933
|
+
let defIdx = 1;
|
|
934
|
+
for (const d of m.definitions || []) {
|
|
935
|
+
md += `${defIdx++}. ${d.definition}
|
|
936
|
+
`;
|
|
937
|
+
if (d.example) {
|
|
938
|
+
md += ` > *"${d.example}"*
|
|
939
|
+
`;
|
|
940
|
+
}
|
|
941
|
+
if (d.synonyms && d.synonyms.length > 0) {
|
|
942
|
+
md += ` - **Synonyms:** ${d.synonyms.join(", ")}
|
|
943
|
+
`;
|
|
944
|
+
}
|
|
945
|
+
if (d.antonyms && d.antonyms.length > 0) {
|
|
946
|
+
md += ` - **Antonyms:** ${d.antonyms.join(", ")}
|
|
947
|
+
`;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
md += "\n";
|
|
951
|
+
}
|
|
952
|
+
if (entry.etymology) {
|
|
953
|
+
md += `### Etymology
|
|
954
|
+
${entry.etymology}
|
|
955
|
+
|
|
956
|
+
`;
|
|
957
|
+
}
|
|
958
|
+
if (entry.thesaurus && entry.thesaurus.synonyms.length > 0) {
|
|
959
|
+
md += `### Thesaurus Synonyms
|
|
960
|
+
`;
|
|
961
|
+
md += entry.thesaurus.synonyms.slice(0, 15).join(", ") + "\n\n";
|
|
962
|
+
}
|
|
963
|
+
if (entry.sources && entry.sources.length > 0) {
|
|
964
|
+
md += `---
|
|
965
|
+
*Sources: ${entry.sources.map((s) => `${s.name} (${s.license})`).join(", ")}*
|
|
966
|
+
`;
|
|
967
|
+
}
|
|
968
|
+
return {
|
|
969
|
+
content: [{ type: "text", text: md }]
|
|
970
|
+
};
|
|
971
|
+
}
|
|
972
|
+
);
|
|
973
|
+
server.tool(
|
|
974
|
+
"search_words",
|
|
975
|
+
"Prefix autocomplete and fuzzy/typo search across WordNook headwords.",
|
|
976
|
+
{
|
|
977
|
+
query: z.string().describe('The prefix or typo query (e.g. "ser" or "definately")'),
|
|
978
|
+
limit: z.number().optional().default(10).describe("Maximum number of results to return (default 10)"),
|
|
979
|
+
fuzzy: z.boolean().optional().default(true).describe("Include typo corrections / fuzzy matches if prefix yields few results")
|
|
980
|
+
},
|
|
981
|
+
async ({ query, limit, fuzzy }) => {
|
|
982
|
+
const results = loader.searchWords(query, limit, fuzzy);
|
|
983
|
+
if (results.length === 0) {
|
|
984
|
+
return {
|
|
985
|
+
content: [{ type: "text", text: `No search matches found for "${query}".` }]
|
|
986
|
+
};
|
|
987
|
+
}
|
|
988
|
+
let text = `### Search results for "${query}" (${results.length} matches):
|
|
989
|
+
|
|
990
|
+
`;
|
|
991
|
+
for (const r of results) {
|
|
992
|
+
if (r.isFuzzy) {
|
|
993
|
+
text += `- **${r.word}** (fuzzy match, score: ${r.score ?? 1})
|
|
994
|
+
`;
|
|
995
|
+
} else {
|
|
996
|
+
text += `- **${r.word}**
|
|
997
|
+
`;
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
return {
|
|
1001
|
+
content: [{ type: "text", text }]
|
|
1002
|
+
};
|
|
1003
|
+
}
|
|
1004
|
+
);
|
|
1005
|
+
server.tool(
|
|
1006
|
+
"find_synonyms",
|
|
1007
|
+
"Find synonyms and antonyms for a word, combining core definitions and the Moby Thesaurus (over 2.5 million synonyms).",
|
|
1008
|
+
{
|
|
1009
|
+
word: z.string().describe("The word to find synonyms for"),
|
|
1010
|
+
partOfSpeech: z.string().optional().describe("Optional filter by part of speech (noun, verb, adjective, adverb)"),
|
|
1011
|
+
limit: z.number().optional().default(20).describe("Maximum number of synonyms to return (default 20)")
|
|
1012
|
+
},
|
|
1013
|
+
async ({ word, partOfSpeech, limit }) => {
|
|
1014
|
+
const result = await loader.findSynonyms(word, partOfSpeech, limit);
|
|
1015
|
+
let text = `### Synonyms & Antonyms for "${result.word}"`;
|
|
1016
|
+
if (result.partOfSpeech) {
|
|
1017
|
+
text += ` (${result.partOfSpeech})`;
|
|
1018
|
+
}
|
|
1019
|
+
text += `
|
|
1020
|
+
|
|
1021
|
+
`;
|
|
1022
|
+
if (result.synonyms.length > 0) {
|
|
1023
|
+
text += `**Synonyms (${result.synonyms.length}):**
|
|
1024
|
+
`;
|
|
1025
|
+
text += result.synonyms.join(", ") + "\n\n";
|
|
1026
|
+
} else {
|
|
1027
|
+
text += `No synonyms found.
|
|
1028
|
+
|
|
1029
|
+
`;
|
|
1030
|
+
}
|
|
1031
|
+
if (result.antonyms.length > 0) {
|
|
1032
|
+
text += `**Antonyms (${result.antonyms.length}):**
|
|
1033
|
+
`;
|
|
1034
|
+
text += result.antonyms.join(", ") + "\n\n";
|
|
1035
|
+
}
|
|
1036
|
+
if (result.sources.length > 0) {
|
|
1037
|
+
text += `*Sources: ${result.sources.join(", ")}*
|
|
1038
|
+
`;
|
|
1039
|
+
}
|
|
1040
|
+
return {
|
|
1041
|
+
content: [{ type: "text", text }]
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
);
|
|
1045
|
+
server.tool(
|
|
1046
|
+
"lemmatize_word",
|
|
1047
|
+
"Strip English inflectional suffixes (-ing, -ed, -s, -ies, -ly, -er, -est) to find dictionary root lemmas.",
|
|
1048
|
+
{
|
|
1049
|
+
word: z.string().describe('The inflected word form to lemmatize (e.g. "springing", "difficulties")')
|
|
1050
|
+
},
|
|
1051
|
+
async ({ word }) => {
|
|
1052
|
+
const result = loader.lemmatizeWord(word);
|
|
1053
|
+
let text = `### Lemmatization for "${result.word}":
|
|
1054
|
+
|
|
1055
|
+
`;
|
|
1056
|
+
if (result.lemmas.length === 0) {
|
|
1057
|
+
text += `No affixes detected; word is already in base form or shorter than 3 letters.
|
|
1058
|
+
`;
|
|
1059
|
+
} else {
|
|
1060
|
+
text += `**Candidate root lemmas:**
|
|
1061
|
+
`;
|
|
1062
|
+
for (const lemma of result.lemmas) {
|
|
1063
|
+
const exists = loader.lookupWord(lemma).found;
|
|
1064
|
+
text += `- **${lemma}** ${exists ? "*(verified in dictionary)*" : "*(unverified)*"}
|
|
1065
|
+
`;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
return {
|
|
1069
|
+
content: [{ type: "text", text }]
|
|
1070
|
+
};
|
|
1071
|
+
}
|
|
1072
|
+
);
|
|
1073
|
+
server.tool(
|
|
1074
|
+
"get_word_of_the_day",
|
|
1075
|
+
"Get WordNook's offline, calendar-deterministic Word of the Day.",
|
|
1076
|
+
{
|
|
1077
|
+
date: z.string().optional().describe("Optional ISO date string (YYYY-MM-DD). Defaults to today.")
|
|
1078
|
+
},
|
|
1079
|
+
async ({ date }) => {
|
|
1080
|
+
const result = loader.getWordOfTheDay(date);
|
|
1081
|
+
let text = `### Word of the Day (${result.date}): **${result.word}**
|
|
1082
|
+
|
|
1083
|
+
`;
|
|
1084
|
+
if (result.entry) {
|
|
1085
|
+
if (result.entry.phonetic) {
|
|
1086
|
+
text += `*${result.entry.phonetic}*
|
|
1087
|
+
|
|
1088
|
+
`;
|
|
1089
|
+
}
|
|
1090
|
+
for (const m of result.entry.meanings || []) {
|
|
1091
|
+
text += `**${m.partOfSpeech}**
|
|
1092
|
+
`;
|
|
1093
|
+
for (const d of (m.definitions || []).slice(0, 2)) {
|
|
1094
|
+
text += `- ${d.definition}
|
|
1095
|
+
`;
|
|
1096
|
+
if (d.example) text += ` > *"${d.example}"*
|
|
1097
|
+
`;
|
|
1098
|
+
}
|
|
1099
|
+
}
|
|
1100
|
+
}
|
|
1101
|
+
return {
|
|
1102
|
+
content: [{ type: "text", text }]
|
|
1103
|
+
};
|
|
1104
|
+
}
|
|
1105
|
+
);
|
|
1106
|
+
server.tool(
|
|
1107
|
+
"get_random_word",
|
|
1108
|
+
"Discover serendipitous vocabulary words with full definitions.",
|
|
1109
|
+
{
|
|
1110
|
+
count: z.number().optional().default(1).describe("Number of random words (1 to 5)"),
|
|
1111
|
+
minDefinitions: z.number().optional().default(1).describe("Minimum number of definition meanings required")
|
|
1112
|
+
},
|
|
1113
|
+
async ({ count, minDefinitions }) => {
|
|
1114
|
+
const words = loader.getRandomWord(count, minDefinitions);
|
|
1115
|
+
let text = `### Random Vocabulary Selection:
|
|
1116
|
+
|
|
1117
|
+
`;
|
|
1118
|
+
for (const entry of words) {
|
|
1119
|
+
text += `## ${entry.word}`;
|
|
1120
|
+
if (entry.phonetic) text += ` *(${entry.phonetic})*`;
|
|
1121
|
+
text += `
|
|
1122
|
+
`;
|
|
1123
|
+
for (const m of entry.meanings || []) {
|
|
1124
|
+
text += `**${m.partOfSpeech}:** `;
|
|
1125
|
+
const defs = (m.definitions || []).map((d) => d.definition).join("; ");
|
|
1126
|
+
text += `${defs}
|
|
1127
|
+
`;
|
|
1128
|
+
}
|
|
1129
|
+
text += "\n";
|
|
1130
|
+
}
|
|
1131
|
+
return {
|
|
1132
|
+
content: [{ type: "text", text }]
|
|
1133
|
+
};
|
|
1134
|
+
}
|
|
1135
|
+
);
|
|
1136
|
+
server.tool(
|
|
1137
|
+
"list_packs",
|
|
1138
|
+
"List all installed, cached, and available WordNook data packs (dictionaries, thesauruses, and bilingual packs), showing the currently active pack.",
|
|
1139
|
+
{},
|
|
1140
|
+
async () => {
|
|
1141
|
+
const packs = loader.listPacks();
|
|
1142
|
+
const activePackId = loader.getActivePackId();
|
|
1143
|
+
let text = `### WordNook Reference Packs (${packs.length} available):
|
|
1144
|
+
|
|
1145
|
+
`;
|
|
1146
|
+
for (const p of packs) {
|
|
1147
|
+
const isActive = p.id === activePackId;
|
|
1148
|
+
text += `#### [${p.id}] ${p.title} (${p.type}, ${p.lang})${isActive ? " \u2B50 *(Active Pack)*" : ""}
|
|
1149
|
+
`;
|
|
1150
|
+
text += `- **Entries:** ${p.entryCount.toLocaleString()}
|
|
1151
|
+
`;
|
|
1152
|
+
text += `- **Version:** ${p.version}
|
|
1153
|
+
`;
|
|
1154
|
+
if (p.attribution) {
|
|
1155
|
+
text += `- **Attribution:** ${p.attribution.name} (${p.attribution.license})
|
|
1156
|
+
`;
|
|
1157
|
+
if (p.attribution.url) text += `- **URL:** ${p.attribution.url}
|
|
1158
|
+
`;
|
|
1159
|
+
}
|
|
1160
|
+
text += "\n";
|
|
1161
|
+
}
|
|
1162
|
+
return {
|
|
1163
|
+
content: [{ type: "text", text }]
|
|
1164
|
+
};
|
|
1165
|
+
}
|
|
1166
|
+
);
|
|
1167
|
+
server.tool(
|
|
1168
|
+
"set_active_pack",
|
|
1169
|
+
'Set the active dictionary pack for subsequent lookups (e.g. "en-kaikki" for Wiktionary with 380,000+ words, or "en-core" for the curated starter vocabulary).',
|
|
1170
|
+
{
|
|
1171
|
+
packId: z.string().describe('The ID of the dictionary pack (e.g. "en-kaikki" or "en-core")')
|
|
1172
|
+
},
|
|
1173
|
+
async ({ packId }) => {
|
|
1174
|
+
const result = await loader.setActivePackId(packId);
|
|
1175
|
+
return {
|
|
1176
|
+
content: [
|
|
1177
|
+
{
|
|
1178
|
+
type: "text",
|
|
1179
|
+
text: result.success ? `\u2705 ${result.message}` : `\u274C ${result.message}`
|
|
1180
|
+
}
|
|
1181
|
+
]
|
|
1182
|
+
};
|
|
1183
|
+
}
|
|
1184
|
+
);
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
// src/mcp/resources.ts
|
|
1188
|
+
import { ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
1189
|
+
function registerResources(server, loader) {
|
|
1190
|
+
server.resource(
|
|
1191
|
+
"definition",
|
|
1192
|
+
new ResourceTemplate("wordnook://definitions/{word}", { list: void 0 }),
|
|
1193
|
+
async (uri, { word }) => {
|
|
1194
|
+
const targetWord = Array.isArray(word) ? word[0] : word;
|
|
1195
|
+
const result = loader.lookupWord(targetWord);
|
|
1196
|
+
if (!result.found || !result.entry) {
|
|
1197
|
+
return {
|
|
1198
|
+
contents: [
|
|
1199
|
+
{
|
|
1200
|
+
uri: uri.href,
|
|
1201
|
+
mimeType: "text/markdown",
|
|
1202
|
+
text: `Entry for "${targetWord}" not found in WordNook.`
|
|
1203
|
+
}
|
|
1204
|
+
]
|
|
1205
|
+
};
|
|
1206
|
+
}
|
|
1207
|
+
const entry = result.entry;
|
|
1208
|
+
let text = `# ${entry.word}
|
|
1209
|
+
`;
|
|
1210
|
+
if (entry.phonetic) text += `*${entry.phonetic}*
|
|
1211
|
+
|
|
1212
|
+
`;
|
|
1213
|
+
for (const m of entry.meanings || []) {
|
|
1214
|
+
text += `## ${m.partOfSpeech}
|
|
1215
|
+
`;
|
|
1216
|
+
for (const d of m.definitions || []) {
|
|
1217
|
+
text += `- ${d.definition}
|
|
1218
|
+
`;
|
|
1219
|
+
if (d.example) text += ` > *"${d.example}"*
|
|
1220
|
+
`;
|
|
1221
|
+
}
|
|
1222
|
+
text += "\n";
|
|
1223
|
+
}
|
|
1224
|
+
return {
|
|
1225
|
+
contents: [
|
|
1226
|
+
{
|
|
1227
|
+
uri: uri.href,
|
|
1228
|
+
mimeType: "text/markdown",
|
|
1229
|
+
text
|
|
1230
|
+
}
|
|
1231
|
+
]
|
|
1232
|
+
};
|
|
1233
|
+
}
|
|
1234
|
+
);
|
|
1235
|
+
server.resource(
|
|
1236
|
+
"thesaurus",
|
|
1237
|
+
new ResourceTemplate("wordnook://thesaurus/{word}", { list: void 0 }),
|
|
1238
|
+
async (uri, { word }) => {
|
|
1239
|
+
const targetWord = Array.isArray(word) ? word[0] : word;
|
|
1240
|
+
const res = await loader.findSynonyms(targetWord, void 0, 30);
|
|
1241
|
+
const jsonStr = JSON.stringify(res, null, 2);
|
|
1242
|
+
return {
|
|
1243
|
+
contents: [
|
|
1244
|
+
{
|
|
1245
|
+
uri: uri.href,
|
|
1246
|
+
mimeType: "application/json",
|
|
1247
|
+
text: jsonStr
|
|
1248
|
+
}
|
|
1249
|
+
]
|
|
1250
|
+
};
|
|
1251
|
+
}
|
|
1252
|
+
);
|
|
1253
|
+
server.resource(
|
|
1254
|
+
"word-of-the-day",
|
|
1255
|
+
"wordnook://word-of-the-day",
|
|
1256
|
+
async (uri) => {
|
|
1257
|
+
const wotd = loader.getWordOfTheDay();
|
|
1258
|
+
let text = `# Word of the Day (${wotd.date}): ${wotd.word}
|
|
1259
|
+
|
|
1260
|
+
`;
|
|
1261
|
+
if (wotd.entry) {
|
|
1262
|
+
for (const m of wotd.entry.meanings || []) {
|
|
1263
|
+
text += `### ${m.partOfSpeech}
|
|
1264
|
+
`;
|
|
1265
|
+
for (const d of (m.definitions || []).slice(0, 2)) {
|
|
1266
|
+
text += `- ${d.definition}
|
|
1267
|
+
`;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
return {
|
|
1272
|
+
contents: [
|
|
1273
|
+
{
|
|
1274
|
+
uri: uri.href,
|
|
1275
|
+
mimeType: "text/markdown",
|
|
1276
|
+
text
|
|
1277
|
+
}
|
|
1278
|
+
]
|
|
1279
|
+
};
|
|
1280
|
+
}
|
|
1281
|
+
);
|
|
1282
|
+
server.resource(
|
|
1283
|
+
"server-stats",
|
|
1284
|
+
"wordnook://stats",
|
|
1285
|
+
async (uri) => {
|
|
1286
|
+
const stats = loader.getStats();
|
|
1287
|
+
return {
|
|
1288
|
+
contents: [
|
|
1289
|
+
{
|
|
1290
|
+
uri: uri.href,
|
|
1291
|
+
mimeType: "application/json",
|
|
1292
|
+
text: JSON.stringify(stats, null, 2)
|
|
1293
|
+
}
|
|
1294
|
+
]
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
);
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
// src/mcp/prompts.ts
|
|
1301
|
+
import { z as z2 } from "zod";
|
|
1302
|
+
function registerPrompts(server, loader) {
|
|
1303
|
+
server.prompt(
|
|
1304
|
+
"vocabulary_enhancer",
|
|
1305
|
+
{
|
|
1306
|
+
text: z2.string().describe("The draft sentence or passage to enhance"),
|
|
1307
|
+
tone: z2.enum(["literary", "academic", "plain"]).optional().default("literary").describe("Desired stylistic register")
|
|
1308
|
+
},
|
|
1309
|
+
({ text, tone }) => {
|
|
1310
|
+
return {
|
|
1311
|
+
messages: [
|
|
1312
|
+
{
|
|
1313
|
+
role: "user",
|
|
1314
|
+
content: {
|
|
1315
|
+
type: "text",
|
|
1316
|
+
text: `You are a master lexicographer and prose stylist using WordNook's offline dictionary.
|
|
1317
|
+
|
|
1318
|
+
Please review the following draft text and elevate its vocabulary to match a "${tone}" tone.
|
|
1319
|
+
Guidelines:
|
|
1320
|
+
- Replace vague, overused, or generic words with precise, evocative terminology.
|
|
1321
|
+
- For each suggested enhancement, reference WordNook definitions, subtle connotations, and examples.
|
|
1322
|
+
- Preserve the author's original intended meaning without over-embellishment.
|
|
1323
|
+
|
|
1324
|
+
Draft text:
|
|
1325
|
+
"""
|
|
1326
|
+
${text}
|
|
1327
|
+
"""`
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
]
|
|
1331
|
+
};
|
|
1332
|
+
}
|
|
1333
|
+
);
|
|
1334
|
+
server.prompt(
|
|
1335
|
+
"etymology_and_nuance",
|
|
1336
|
+
{
|
|
1337
|
+
wordA: z2.string().describe('First word to compare (e.g. "ephemeral")'),
|
|
1338
|
+
wordB: z2.string().describe('Second word to compare (e.g. "transient")')
|
|
1339
|
+
},
|
|
1340
|
+
({ wordA, wordB }) => {
|
|
1341
|
+
const resA = loader.lookupWord(wordA);
|
|
1342
|
+
const resB = loader.lookupWord(wordB);
|
|
1343
|
+
let context = "";
|
|
1344
|
+
if (resA.found && resA.entry) {
|
|
1345
|
+
context += `Definition of "${resA.entry.word}":
|
|
1346
|
+
`;
|
|
1347
|
+
for (const m of resA.entry.meanings || []) {
|
|
1348
|
+
for (const d of (m.definitions || []).slice(0, 2)) {
|
|
1349
|
+
context += `- [${m.partOfSpeech}] ${d.definition}
|
|
1350
|
+
`;
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
if (resA.entry.etymology) context += `Etymology: ${resA.entry.etymology}
|
|
1354
|
+
`;
|
|
1355
|
+
context += "\n";
|
|
1356
|
+
}
|
|
1357
|
+
if (resB.found && resB.entry) {
|
|
1358
|
+
context += `Definition of "${resB.entry.word}":
|
|
1359
|
+
`;
|
|
1360
|
+
for (const m of resB.entry.meanings || []) {
|
|
1361
|
+
for (const d of (m.definitions || []).slice(0, 2)) {
|
|
1362
|
+
context += `- [${m.partOfSpeech}] ${d.definition}
|
|
1363
|
+
`;
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
if (resB.entry.etymology) context += `Etymology: ${resB.entry.etymology}
|
|
1367
|
+
`;
|
|
1368
|
+
context += "\n";
|
|
1369
|
+
}
|
|
1370
|
+
return {
|
|
1371
|
+
messages: [
|
|
1372
|
+
{
|
|
1373
|
+
role: "user",
|
|
1374
|
+
content: {
|
|
1375
|
+
type: "text",
|
|
1376
|
+
text: `You are an expert etymologist and linguist.
|
|
1377
|
+
|
|
1378
|
+
Compare the subtle shades of meaning between "${wordA}" and "${wordB}".
|
|
1379
|
+
|
|
1380
|
+
${context ? `Reference Context:
|
|
1381
|
+
${context}
|
|
1382
|
+
` : ""}Analyze:
|
|
1383
|
+
1. Etymological origins and historical evolution of each word.
|
|
1384
|
+
2. Subtle differences in connotation, register, and emotional weight.
|
|
1385
|
+
3. Specific contexts where one word is preferred over the other.
|
|
1386
|
+
4. Provide contrasting example sentences for both words.`
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
]
|
|
1390
|
+
};
|
|
1391
|
+
}
|
|
1392
|
+
);
|
|
1393
|
+
server.prompt(
|
|
1394
|
+
"word_puzzle_assistant",
|
|
1395
|
+
{
|
|
1396
|
+
clue: z2.string().describe("Crossword clue or riddle text"),
|
|
1397
|
+
pattern: z2.string().optional().describe('Letter pattern with underscores for unknowns (e.g. "s_r__dip_ty")'),
|
|
1398
|
+
length: z2.number().optional().describe("Word length in characters")
|
|
1399
|
+
},
|
|
1400
|
+
({ clue, pattern, length }) => {
|
|
1401
|
+
let promptText = `Solve the following word puzzle or crossword clue using WordNook's lexicon:
|
|
1402
|
+
|
|
1403
|
+
`;
|
|
1404
|
+
promptText += `Clue: "${clue}"
|
|
1405
|
+
`;
|
|
1406
|
+
if (pattern) promptText += `Pattern: ${pattern}
|
|
1407
|
+
`;
|
|
1408
|
+
if (length) promptText += `Target Length: ${length} letters
|
|
1409
|
+
`;
|
|
1410
|
+
promptText += `
|
|
1411
|
+
Provide the most probable candidate answer(s), verify them against dictionary definitions, and explain the wordplay.`;
|
|
1412
|
+
return {
|
|
1413
|
+
messages: [
|
|
1414
|
+
{
|
|
1415
|
+
role: "user",
|
|
1416
|
+
content: {
|
|
1417
|
+
type: "text",
|
|
1418
|
+
text: promptText
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
]
|
|
1422
|
+
};
|
|
1423
|
+
}
|
|
1424
|
+
);
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
// src/mcp/server.ts
|
|
1428
|
+
async function createWordNookMcpServer(options = {}) {
|
|
1429
|
+
const loader = new WordNookDataLoader(options);
|
|
1430
|
+
await loader.init();
|
|
1431
|
+
const server = new McpServer2(
|
|
1432
|
+
{
|
|
1433
|
+
name: "wordnook",
|
|
1434
|
+
version: "1.0.21"
|
|
1435
|
+
},
|
|
1436
|
+
{
|
|
1437
|
+
capabilities: {
|
|
1438
|
+
tools: {},
|
|
1439
|
+
resources: {},
|
|
1440
|
+
prompts: {}
|
|
1441
|
+
}
|
|
1442
|
+
}
|
|
1443
|
+
);
|
|
1444
|
+
registerTools(server, loader);
|
|
1445
|
+
registerResources(server, loader);
|
|
1446
|
+
registerPrompts(server, loader);
|
|
1447
|
+
return { server, loader };
|
|
1448
|
+
}
|
|
1449
|
+
async function startStdioServer(options = {}) {
|
|
1450
|
+
const instance = await createWordNookMcpServer(options);
|
|
1451
|
+
const transport = new StdioServerTransport();
|
|
1452
|
+
await instance.server.connect(transport);
|
|
1453
|
+
instance.transport = transport;
|
|
1454
|
+
const cleanup = async () => {
|
|
1455
|
+
try {
|
|
1456
|
+
await instance.server.close();
|
|
1457
|
+
} catch {
|
|
1458
|
+
}
|
|
1459
|
+
process.exit(0);
|
|
1460
|
+
};
|
|
1461
|
+
process.on("SIGINT", cleanup);
|
|
1462
|
+
process.on("SIGTERM", cleanup);
|
|
1463
|
+
return instance;
|
|
1464
|
+
}
|
|
1465
|
+
function createHttpHandler(instance, transports, port2 = 8001) {
|
|
1466
|
+
return async (req, res) => {
|
|
1467
|
+
res.setHeader("Access-Control-Allow-Origin", "*");
|
|
1468
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
1469
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
|
|
1470
|
+
if (req.method === "OPTIONS") {
|
|
1471
|
+
res.writeHead(200).end();
|
|
1472
|
+
return;
|
|
1473
|
+
}
|
|
1474
|
+
const host = req.headers.host || `localhost:${port2}`;
|
|
1475
|
+
const url = new URL(req.url || "/", `http://${host}`);
|
|
1476
|
+
if (req.method === "GET" && (url.pathname === "/sse" || url.pathname === "/mcp")) {
|
|
1477
|
+
const transport = new SSEServerTransport("/messages", res);
|
|
1478
|
+
transports.set(transport.sessionId, transport);
|
|
1479
|
+
transport.onclose = () => {
|
|
1480
|
+
transports.delete(transport.sessionId);
|
|
1481
|
+
};
|
|
1482
|
+
await instance.server.connect(transport);
|
|
1483
|
+
return;
|
|
1484
|
+
}
|
|
1485
|
+
if (req.method === "POST" && url.pathname === "/messages") {
|
|
1486
|
+
const sessionId = url.searchParams.get("sessionId");
|
|
1487
|
+
let transport;
|
|
1488
|
+
if (sessionId) {
|
|
1489
|
+
transport = transports.get(sessionId);
|
|
1490
|
+
if (!transport) {
|
|
1491
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
1492
|
+
res.end(JSON.stringify({ error: `Session not found: ${sessionId}` }));
|
|
1493
|
+
return;
|
|
1494
|
+
}
|
|
1495
|
+
} else {
|
|
1496
|
+
if (transports.size === 0) {
|
|
1497
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1498
|
+
res.end(JSON.stringify({ error: "No active SSE sessions found." }));
|
|
1499
|
+
return;
|
|
1500
|
+
}
|
|
1501
|
+
if (transports.size > 1) {
|
|
1502
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1503
|
+
res.end(
|
|
1504
|
+
JSON.stringify({
|
|
1505
|
+
error: "Multiple active SSE sessions. Please specify sessionId in query params (e.g. /messages?sessionId=...)."
|
|
1506
|
+
})
|
|
1507
|
+
);
|
|
1508
|
+
return;
|
|
1509
|
+
}
|
|
1510
|
+
transport = transports.values().next().value;
|
|
1511
|
+
}
|
|
1512
|
+
if (!transport) {
|
|
1513
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
1514
|
+
res.end(JSON.stringify({ error: "Session not available" }));
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
await transport.handlePostMessage(req, res);
|
|
1518
|
+
return;
|
|
1519
|
+
}
|
|
1520
|
+
if (req.method === "GET" && url.pathname === "/health") {
|
|
1521
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
1522
|
+
res.end(JSON.stringify({ status: "ok", server: "wordnook-mcp" }));
|
|
1523
|
+
return;
|
|
1524
|
+
}
|
|
1525
|
+
res.writeHead(404).end("Not Found");
|
|
1526
|
+
};
|
|
1527
|
+
}
|
|
1528
|
+
async function startHttpServer(port2 = 8001, options = {}) {
|
|
1529
|
+
const instance = await createWordNookMcpServer(options);
|
|
1530
|
+
const transports = /* @__PURE__ */ new Map();
|
|
1531
|
+
const handler = createHttpHandler(instance, transports, port2);
|
|
1532
|
+
const server = http.createServer(handler);
|
|
1533
|
+
return new Promise((resolve, reject) => {
|
|
1534
|
+
server.listen(port2, "0.0.0.0", () => {
|
|
1535
|
+
console.error(`WordNook MCP SSE Server running at http://localhost:${port2}/sse`);
|
|
1536
|
+
console.error(`For Open WebUI in Docker, use: http://host.docker.internal:${port2}/sse`);
|
|
1537
|
+
resolve(server);
|
|
1538
|
+
});
|
|
1539
|
+
server.on("error", reject);
|
|
1540
|
+
});
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
// src/mcp/cli.ts
|
|
1544
|
+
var args = process.argv.slice(2);
|
|
1545
|
+
var dataDir;
|
|
1546
|
+
var port;
|
|
1547
|
+
var activePack;
|
|
1548
|
+
for (let i = 0; i < args.length; i++) {
|
|
1549
|
+
const arg = args[i];
|
|
1550
|
+
if (arg === "--help" || arg === "-h") {
|
|
1551
|
+
const useColor = !process.env.NO_COLOR && (process.stdout.isTTY ?? false);
|
|
1552
|
+
const cBlue = useColor ? "\x1B[38;5;75m" : "";
|
|
1553
|
+
const cBold = useColor ? "\x1B[1m" : "";
|
|
1554
|
+
const cItalic = useColor ? "\x1B[3m" : "";
|
|
1555
|
+
const cDim = useColor ? "\x1B[2m" : "";
|
|
1556
|
+
const cReset = useColor ? "\x1B[0m" : "";
|
|
1557
|
+
const heroArt = [
|
|
1558
|
+
` ${cDim}__...--~~~~~-._ _.-~~~~~--...__${cReset}`,
|
|
1559
|
+
` ${cDim}// \`V\` \\\\${cReset}`,
|
|
1560
|
+
` ${cDim}// | \\\\${cReset}`,
|
|
1561
|
+
` ${cDim}//__...--~~~~~-._ | _.-~~~~~--...__\\\\${cReset}`,
|
|
1562
|
+
` ${cDim}//__.....---~~~~~._\\ | /_.~~~~~---.....__\\\\${cReset}`,
|
|
1563
|
+
` ${cDim}====================\\\\|//====================${cReset}`,
|
|
1564
|
+
"",
|
|
1565
|
+
` ${cBold}__ __ _ ${cReset} ${cBlue}${cBold} _ _ _ ${cReset}`,
|
|
1566
|
+
` ${cBold}\\ \\ / / | |${cReset} ${cBlue}${cBold}| \\ | | | | ${cReset}`,
|
|
1567
|
+
` ${cBold}\\ \\ /\\ / /__ _ __ __| |${cReset} ${cBlue}${cBold}| \\| | ___ ___ | | __${cReset}`,
|
|
1568
|
+
` ${cBold}\\ \\/ \\/ / _ \\| '__/ _\` |${cReset} ${cBlue}${cBold}| . \` |/ _ \\ / _ \\| |/ /${cReset}`,
|
|
1569
|
+
` ${cBold}\\ /\\ / (_) | | | (_| |${cReset} ${cBlue}${cBold}| |\\ | (_) | (_) | < ${cReset}`,
|
|
1570
|
+
` ${cBold}\\/ \\/ \\___/|_| \\__,_|${cReset} ${cBlue}${cBold}|_| \\_|\\___/ \\___/|_|\\_\\${cReset}`,
|
|
1571
|
+
"",
|
|
1572
|
+
` ${cItalic}${cDim}\u2014 The quiet nook for words, definitions, and wonder. \u2014${cReset}`
|
|
1573
|
+
].join("\n");
|
|
1574
|
+
console.log(`
|
|
1575
|
+
${heroArt}
|
|
1576
|
+
|
|
1577
|
+
${cBold}WordNook MCP Server (Model Context Protocol)${cReset}
|
|
1578
|
+
|
|
1579
|
+
Usage:
|
|
1580
|
+
wordnook-mcp [options]
|
|
1581
|
+
|
|
1582
|
+
Options:
|
|
1583
|
+
--port, -p <number> Run in HTTP/SSE mode on specified port (e.g. for Open WebUI)
|
|
1584
|
+
--pack <packId> Set default active pack on startup (e.g. "en-kaikki" or "en-core")
|
|
1585
|
+
--data-dir <path> Path to directory containing public/data/*.json.gz
|
|
1586
|
+
--version, -v Show version
|
|
1587
|
+
--help, -h Show this help message
|
|
1588
|
+
|
|
1589
|
+
Transports:
|
|
1590
|
+
- Default: stdio (for Claude Desktop, Cursor, Antigravity, mcphost, Zed, Cline)
|
|
1591
|
+
- --port 8001: Streamable HTTP / SSE (for Open WebUI: http://localhost:8001/sse)
|
|
1592
|
+
|
|
1593
|
+
Tools Exposed:
|
|
1594
|
+
- lookup_word Full definitions, phonetics, etymology, and lemmatization
|
|
1595
|
+
- search_words Autocomplete prefix & fuzzy typo tolerance
|
|
1596
|
+
- find_synonyms Thesaurus synonyms & antonyms (Wordset + Moby)
|
|
1597
|
+
- lemmatize_word Morphological lemma derivation (-ing, -ed, -s, etc.)
|
|
1598
|
+
- get_word_of_the_day Offline deterministic Word of the Day
|
|
1599
|
+
- get_random_word Serendipitous curated vocabulary discovery
|
|
1600
|
+
- list_packs Inventory of installed & available reference packs
|
|
1601
|
+
- set_active_pack Dynamically switch active reference pack (e.g. en-kaikki)
|
|
1602
|
+
`);
|
|
1603
|
+
process.exit(0);
|
|
1604
|
+
} else if (arg === "--version" || arg === "-v") {
|
|
1605
|
+
console.error("wordnook-mcp v1.0.21");
|
|
1606
|
+
process.exit(0);
|
|
1607
|
+
} else if ((arg === "--port" || arg === "-p") && args[i + 1]) {
|
|
1608
|
+
port = parseInt(args[i + 1], 10);
|
|
1609
|
+
i++;
|
|
1610
|
+
} else if (arg === "--pack" && args[i + 1]) {
|
|
1611
|
+
activePack = args[i + 1];
|
|
1612
|
+
i++;
|
|
1613
|
+
} else if (arg === "--data-dir" && args[i + 1]) {
|
|
1614
|
+
dataDir = args[i + 1];
|
|
1615
|
+
i++;
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
function handleServerError(transport, err) {
|
|
1619
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1620
|
+
console.error(`
|
|
1621
|
+
\u274C Failed to start WordNook MCP ${transport} server:`);
|
|
1622
|
+
console.error(message + "\n");
|
|
1623
|
+
process.exit(1);
|
|
1624
|
+
}
|
|
1625
|
+
if (port) {
|
|
1626
|
+
startHttpServer(port, { dataDir, activePack }).catch((err) => handleServerError("HTTP/SSE", err));
|
|
1627
|
+
} else {
|
|
1628
|
+
startStdioServer({ dataDir, activePack }).catch((err) => handleServerError("stdio", err));
|
|
1629
|
+
}
|