lingual-mcp 0.1.0 → 0.1.2

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/dist/index.js CHANGED
@@ -1,24 +1,52 @@
1
+ // node_modules/tsup/assets/esm_shims.js
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ var getFilename = () => fileURLToPath(import.meta.url);
5
+ var getDirname = () => path.dirname(getFilename());
6
+ var __dirname = /* @__PURE__ */ getDirname();
7
+
1
8
  // src/index.ts
2
9
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
10
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
11
  import {
5
12
  CallToolRequestSchema,
6
- ListToolsRequestSchema,
13
+ GetPromptRequestSchema,
7
14
  ListPromptsRequestSchema,
8
- GetPromptRequestSchema
15
+ ListToolsRequestSchema
9
16
  } from "@modelcontextprotocol/sdk/types.js";
17
+ import { loadUserLingualConfig } from "pi-lingual/core";
18
+
19
+ // src/config.ts
20
+ import * as fs from "fs";
21
+ import * as path2 from "path";
22
+ import { fileURLToPath as fileURLToPath2 } from "url";
10
23
  import {
11
- translatePrompt,
12
- executeModeRunner,
13
- compileModeSystemPrompt,
14
- loadUserLingualConfig,
15
- getPresetLoadout,
16
- buildSystemPrompt,
17
- sanitizePromptForTranslation,
18
- ensureCodeTokensPreserved,
19
- detectScriptLanguage
24
+ getPresetLoadout
20
25
  } from "pi-lingual/core";
21
- var PKG_VERSION = "0.1.0";
26
+ var REASONING_LEVELS = ["off", "minimal", "low", "medium", "high"];
27
+ var PRESET_IDS = ["spec", "commit", "oss", "yap", "direct"];
28
+ function resolveManifestVersion() {
29
+ const candidates = [];
30
+ if (typeof __dirname === "string") {
31
+ candidates.push(path2.resolve(__dirname, "../package.json"));
32
+ }
33
+ if (typeof import.meta?.url === "string" && import.meta.url) {
34
+ candidates.push(path2.resolve(path2.dirname(fileURLToPath2(import.meta.url)), "../package.json"));
35
+ }
36
+ candidates.push(path2.resolve(process.cwd(), "package.json"));
37
+ for (const candidate of candidates) {
38
+ try {
39
+ if (!fs.existsSync(candidate)) continue;
40
+ const manifest = JSON.parse(fs.readFileSync(candidate, "utf-8"));
41
+ if (typeof manifest.version === "string" && manifest.version.trim()) {
42
+ return manifest.version.trim();
43
+ }
44
+ } catch {
45
+ }
46
+ }
47
+ return "0.1.1";
48
+ }
49
+ var PKG_VERSION = resolveManifestVersion();
22
50
  function isLoopbackUrl(urlStr) {
23
51
  try {
24
52
  const parsed = new URL(urlStr);
@@ -47,352 +75,407 @@ function resolveMcpLlmConfig(diskConfig, env = process.env) {
47
75
  model: rawModel || "gpt-4o-mini"
48
76
  };
49
77
  }
50
- function createLingualMcpServer() {
51
- const server = new Server(
78
+ function normalizeReasoningArg(raw) {
79
+ const value = typeof raw === "string" ? raw.trim().toLowerCase() : "";
80
+ return REASONING_LEVELS.includes(value) ? value : void 0;
81
+ }
82
+ function resolveMode(id, sourceLang, explainLang, custom) {
83
+ const wanted = (id || "").trim().toLowerCase();
84
+ if (!wanted) return null;
85
+ const userMode = (custom || []).find((mode) => mode.id.toLowerCase() === wanted && mode.enabled !== false);
86
+ if (userMode) return userMode;
87
+ return getPresetLoadout(wanted, sourceLang, explainLang);
88
+ }
89
+ function stripVocabSlots(slots) {
90
+ return slots ? slots.filter((slot) => slot.role !== "vocab") : slots;
91
+ }
92
+ function applyModeOverrides(mode, options) {
93
+ const next = { ...mode };
94
+ if (options.reasoning) next.reasoning = options.reasoning;
95
+ if (options.includeVocab === false) {
96
+ next.vocab = false;
97
+ next.slots = stripVocabSlots(next.slots);
98
+ }
99
+ return next;
100
+ }
101
+ function modeIds(disk, extra = []) {
102
+ const custom = (disk.modes || []).filter((mode) => mode.enabled !== false).map((mode) => mode.id);
103
+ return Array.from(/* @__PURE__ */ new Set([...extra, ...PRESET_IDS, ...custom]));
104
+ }
105
+
106
+ // src/prompts.ts
107
+ import { compileModeSystemPrompt } from "pi-lingual/core";
108
+ function listLingualPrompts() {
109
+ return [
52
110
  {
53
- name: "lingual-mcp",
54
- version: PKG_VERSION
111
+ name: "spec_prompt",
112
+ description: "Structure raw developer instructions into a rigorous technical specification.",
113
+ arguments: [
114
+ { name: "raw_idea", description: "The raw thought or instruction to structure.", required: true },
115
+ { name: "source_lang", description: "Optional source language code (default: auto/zh).", required: false },
116
+ { name: "target_lang", description: "Optional target language code (default: en).", required: false }
117
+ ]
55
118
  },
56
119
  {
57
- capabilities: {
58
- tools: {},
59
- prompts: {}
60
- }
120
+ name: "conventional_commit",
121
+ description: "Dehydrate plain explanation into a Conventional Commit (first line <= 72 chars).",
122
+ arguments: [
123
+ { name: "changes_summary", description: "Description of what was changed and why.", required: true },
124
+ { name: "source_lang", description: "Optional source language code (default: auto/zh).", required: false },
125
+ { name: "target_lang", description: "Optional target language code (default: en).", required: false }
126
+ ]
61
127
  }
62
- );
63
- server.setRequestHandler(ListToolsRequestSchema, async () => {
128
+ ];
129
+ }
130
+ function getLingualPrompt(name, args, disk) {
131
+ const sourceLang = args?.source_lang || disk.sourceLang || "zh";
132
+ const targetLang = args?.target_lang || "en";
133
+ const explainLang = disk.explainLang || sourceLang;
134
+ const compile = (modeId) => {
135
+ const mode = resolveMode(modeId, sourceLang, explainLang, disk.modes);
136
+ return mode ? compileModeSystemPrompt(mode, { sourceLang, targetLang, explainLang, globalKillList: disk.globalKillList }) : null;
137
+ };
138
+ if (name === "spec_prompt") {
139
+ const idea = args?.raw_idea || "";
140
+ const sys = compile("spec");
141
+ if (!sys) throw new Error("Spec mode is unavailable");
64
142
  return {
65
- tools: [
66
- {
67
- name: "lingual_transform_spec",
68
- description: "Transform messy native-language thoughts or instructions into crisp, structured engineering specifications, conventional commits, or OSS maintainer peer comms while keeping code blocks & stack traces 100% untouched.",
69
- inputSchema: {
70
- type: "object",
71
- properties: {
72
- text: {
73
- type: "string",
74
- description: "The raw thought, feature requirement, issue draft, or commit message in any language."
75
- },
76
- loadout: {
77
- type: "string",
78
- enum: ["spec", "commit", "oss", "yap", "direct"],
79
- description: "Preset loadout: 'spec' (structured engineering specification), 'commit' (conventional commit <=72 chars), 'oss' (maintainer peer issue/PR feedback), 'yap' (high-density tech post for X/HN), 'direct' (rewrite into clean technical English, keeping code blocks and stack traces intact). Default: 'spec'.",
80
- default: "spec"
81
- },
82
- sourceLang: {
83
- type: "string",
84
- description: "Source language code (e.g. 'zh', 'ja', 'en', 'es'). Auto-detected if omitted."
85
- },
86
- targetLang: {
87
- type: "string",
88
- description: "Target language code (e.g. 'en', 'ja', 'zh'). Default: 'en'.",
89
- default: "en"
90
- }
91
- },
92
- required: ["text"]
143
+ description: "Transform idea into an engineering specification",
144
+ messages: [{ role: "user", content: { type: "text", text: `${sys}
145
+
146
+ Task to structure:
147
+ ${idea}` } }]
148
+ };
149
+ }
150
+ if (name === "conventional_commit") {
151
+ const summary = args?.changes_summary || "";
152
+ const sys = compile("commit");
153
+ if (!sys) throw new Error("Commit mode is unavailable");
154
+ return {
155
+ description: "Transform change summary into Conventional Commit",
156
+ messages: [{ role: "user", content: { type: "text", text: `${sys}
157
+
158
+ Changes to commit:
159
+ ${summary}` } }]
160
+ };
161
+ }
162
+ throw new Error(`Prompt not found: ${name}`);
163
+ }
164
+
165
+ // src/tools.ts
166
+ import {
167
+ compileModeSystemPrompt as compileModeSystemPrompt2,
168
+ detectScriptLanguage,
169
+ ensureCodeTokensPreserved,
170
+ executeModeRunner,
171
+ sanitizePromptForTranslation,
172
+ translateCore
173
+ } from "pi-lingual/core";
174
+ function jsonResult(payload) {
175
+ return {
176
+ content: [{ type: "text", text: JSON.stringify(payload, null, 2) }]
177
+ };
178
+ }
179
+ function errorResult(message) {
180
+ return {
181
+ isError: true,
182
+ content: [{ type: "text", text: message }]
183
+ };
184
+ }
185
+ function listLingualTools(disk) {
186
+ const transformIds = modeIds(disk);
187
+ const templateIds = modeIds(disk, ["companion"]);
188
+ return [
189
+ {
190
+ name: "lingual_transform_spec",
191
+ description: "Transform messy native-language thoughts or instructions into crisp, structured engineering specifications, conventional commits, or OSS maintainer peer comms while keeping code blocks & stack traces 100% untouched. Accepts any preset id or a mode id declared in ~/.pi/agent/lingual.json.",
192
+ inputSchema: {
193
+ type: "object",
194
+ properties: {
195
+ text: {
196
+ type: "string",
197
+ description: "The raw thought, feature requirement, issue draft, or commit message in any language."
198
+ },
199
+ loadout: {
200
+ type: "string",
201
+ enum: transformIds,
202
+ description: "Preset loadout: 'spec' (structured engineering specification), 'commit' (conventional commit <=72 chars), 'oss' (maintainer peer issue/PR feedback), 'yap' (high-density tech post for X/HN), 'direct' (clean technical English, code blocks and stack traces intact), or any custom mode id from lingual.json. Default: 'spec'.",
203
+ default: "spec"
204
+ },
205
+ sourceLang: {
206
+ type: "string",
207
+ description: "Source language code (e.g. 'zh', 'ja', 'en', 'es'). Auto-detected if omitted."
208
+ },
209
+ targetLang: {
210
+ type: "string",
211
+ description: "Target language code (e.g. 'en', 'ja', 'zh'). Default: 'en'.",
212
+ default: "en"
213
+ },
214
+ reasoning: {
215
+ type: "string",
216
+ enum: REASONING_LEVELS,
217
+ description: "Thinking effort for this call. Overrides the mode's pinned level (spec pins 'low', the rest pin 'off')."
218
+ },
219
+ context: {
220
+ type: "string",
221
+ description: "Extra context for context-aware modes, such as a staged git diff for 'commit' or the previous agent turn."
222
+ },
223
+ includeVocab: {
224
+ type: "boolean",
225
+ description: "Set false to drop the vocabulary slot from the prompt and the response. Default: true.",
226
+ default: true
93
227
  }
94
228
  },
95
- {
96
- name: "lingual_bilingual_companion",
97
- description: "Generate dual-register phrasing (Spoken for Slack/standups vs. Written for RFCs/PRs), native nuance meanings, and key vocabulary highlights for any technical expression or thought.",
98
- inputSchema: {
99
- type: "object",
100
- properties: {
101
- text: {
102
- type: "string",
103
- description: "The natural language text or expression to unpack into technical dual-registers."
104
- },
105
- sourceLang: {
106
- type: "string",
107
- description: "Source language code (e.g. 'zh', 'ja'). Auto-detected if omitted."
108
- },
109
- targetLang: {
110
- type: "string",
111
- description: "Target language code (e.g. 'en', 'ja'). Default: 'en'.",
112
- default: "en"
113
- }
114
- },
115
- required: ["text"]
229
+ required: ["text"]
230
+ }
231
+ },
232
+ {
233
+ name: "lingual_bilingual_companion",
234
+ description: "Generate dual-register phrasing (Spoken for Slack/standups vs. Written for RFCs/PRs), native nuance meanings, and key vocabulary highlights for any technical expression or thought.",
235
+ inputSchema: {
236
+ type: "object",
237
+ properties: {
238
+ text: {
239
+ type: "string",
240
+ description: "The natural language text or expression to unpack into technical dual-registers."
241
+ },
242
+ sourceLang: {
243
+ type: "string",
244
+ description: "Source language code (e.g. 'zh', 'ja'). Auto-detected if omitted."
245
+ },
246
+ targetLang: {
247
+ type: "string",
248
+ description: "Target language code (e.g. 'en', 'ja'). Default: 'en'.",
249
+ default: "en"
250
+ },
251
+ reasoning: {
252
+ type: "string",
253
+ enum: REASONING_LEVELS,
254
+ description: "Thinking effort for this call. Defaults to the companion mode's level ('off')."
255
+ },
256
+ includeVocab: {
257
+ type: "boolean",
258
+ description: "Set false to drop the vocabulary slot from the prompt and the response. Default: true.",
259
+ default: true
116
260
  }
117
261
  },
118
- {
119
- name: "lingual_prompt_template",
120
- description: "Zero-key mode: extract the exact compiled system prompt and few-shot rules for any Lingual mode so the host agent can execute it directly without external API credentials.",
121
- inputSchema: {
122
- type: "object",
123
- properties: {
124
- loadout: {
125
- type: "string",
126
- enum: ["spec", "commit", "oss", "yap", "direct", "companion"],
127
- description: "Target mode or loadout.",
128
- default: "spec"
129
- },
130
- sourceLang: {
131
- type: "string",
132
- description: "Source language code (e.g. 'zh', 'ja', 'en'). Default: 'zh'.",
133
- default: "zh"
134
- },
135
- targetLang: {
136
- type: "string",
137
- description: "Target language code (e.g. 'en', 'ja'). Default: 'en'.",
138
- default: "en"
139
- }
140
- },
141
- required: ["loadout"]
142
- }
143
- }
144
- ]
145
- };
146
- });
147
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
148
- const { name, arguments: args } = request.params;
149
- const diskConfig = loadUserLingualConfig();
150
- const llm = resolveMcpLlmConfig(diskConfig);
151
- if (name === "lingual_transform_spec") {
152
- const text = String(args?.text || "");
153
- const loadoutId = String(args?.loadout || "spec");
154
- const targetLang = String(args?.targetLang || "en");
155
- const sourceLang = args?.sourceLang ? String(args.sourceLang) : detectScriptLanguage(text) || diskConfig.sourceLang || "zh";
156
- const preset = getPresetLoadout(loadoutId, sourceLang);
157
- if (!preset) {
158
- return {
159
- isError: true,
160
- content: [{ type: "text", text: `Unknown loadout preset: ${loadoutId}` }]
161
- };
262
+ required: ["text"]
162
263
  }
163
- const sanitized = sanitizePromptForTranslation(text);
164
- const inputToTransform = sanitized.distilledText || text;
165
- if (!llm.configured) {
166
- return {
167
- content: [
168
- {
169
- type: "text",
170
- text: JSON.stringify(
171
- {
172
- status: "unconfigured_zero_key_fallback",
173
- message: "No external LLM credentials configured (set LINGUAL_ENDPOINT / OPENAI_BASE_URL and LINGUAL_API_KEY / OPENAI_API_KEY, or configure ~/.pi/agent/lingual.json). Use the compiledSystemPrompt below directly in your host agent.",
174
- loadout: loadoutId,
175
- distilledInput: inputToTransform,
176
- compiledSystemPrompt: compileModeSystemPrompt(preset, { sourceLang, targetLang })
177
- },
178
- null,
179
- 2
180
- )
181
- }
182
- ]
183
- };
264
+ },
265
+ {
266
+ name: "lingual_prompt_template",
267
+ description: "Zero-key mode: extract the exact compiled system prompt and few-shot rules for any Lingual mode so the host agent can execute it directly without external API credentials. Custom modes from lingual.json are accepted.",
268
+ inputSchema: {
269
+ type: "object",
270
+ properties: {
271
+ loadout: {
272
+ type: "string",
273
+ enum: templateIds,
274
+ description: "Target mode or loadout id: any preset, 'companion', or a custom mode id from lingual.json.",
275
+ default: "spec"
276
+ },
277
+ sourceLang: {
278
+ type: "string",
279
+ description: "Source language code (e.g. 'zh', 'ja', 'en'). Default: 'zh'.",
280
+ default: "zh"
281
+ },
282
+ targetLang: {
283
+ type: "string",
284
+ description: "Target language code (e.g. 'en', 'ja'). Default: 'en'.",
285
+ default: "en"
286
+ },
287
+ includeVocab: {
288
+ type: "boolean",
289
+ description: "Set false to drop the vocabulary slot from the compiled prompt. Default: true.",
290
+ default: true
291
+ }
292
+ },
293
+ required: ["loadout"]
184
294
  }
185
- try {
186
- const candidates = await executeModeRunner(inputToTransform, preset, {
187
- endpoint: llm.endpoint,
188
- apiKey: llm.apiKey,
189
- model: llm.model,
295
+ }
296
+ ];
297
+ }
298
+ async function handleLingualToolCall(name, args, disk) {
299
+ const llm = resolveMcpLlmConfig(disk);
300
+ if (name === "lingual_transform_spec") {
301
+ const text = String(args?.text || "");
302
+ const loadoutId = String(args?.loadout || "spec");
303
+ const targetLang = String(args?.targetLang || "en");
304
+ const sourceLang = args?.sourceLang ? String(args.sourceLang) : detectScriptLanguage(text) || disk.sourceLang || "zh";
305
+ const explainLang = disk.explainLang || sourceLang;
306
+ const reasoning = normalizeReasoningArg(args?.reasoning);
307
+ const includeVocab = args?.includeVocab !== false;
308
+ const context = typeof args?.context === "string" && args.context.trim() ? args.context.trim() : void 0;
309
+ const mode = resolveMode(loadoutId, sourceLang, explainLang, disk.modes);
310
+ if (!mode) {
311
+ return errorResult(`Unknown loadout or mode: ${loadoutId}. Known ids: ${modeIds(disk).join(", ")}`);
312
+ }
313
+ const runMode = applyModeOverrides(mode, { reasoning, includeVocab });
314
+ const sanitized = sanitizePromptForTranslation(text);
315
+ const inputToTransform = sanitized.distilledText || text;
316
+ if (!llm.configured) {
317
+ return jsonResult({
318
+ status: "unconfigured_zero_key_fallback",
319
+ message: "No external LLM credentials configured (set LINGUAL_ENDPOINT / OPENAI_BASE_URL and LINGUAL_API_KEY / OPENAI_API_KEY, or configure ~/.pi/agent/lingual.json). Use the compiledSystemPrompt below directly in your host agent.",
320
+ mode: runMode.id,
321
+ reasoning: runMode.reasoning ?? "off",
322
+ distilledInput: inputToTransform,
323
+ compiledSystemPrompt: compileModeSystemPrompt2(runMode, {
190
324
  sourceLang,
191
- targetLang
325
+ targetLang,
326
+ explainLang,
327
+ globalKillList: disk.globalKillList,
328
+ extraContext: context
329
+ })
330
+ });
331
+ }
332
+ try {
333
+ const candidates = await executeModeRunner(inputToTransform, runMode, {
334
+ endpoint: llm.endpoint,
335
+ apiKey: llm.apiKey,
336
+ model: llm.model,
337
+ sourceLang,
338
+ targetLang,
339
+ explainLang,
340
+ globalKillList: disk.globalKillList,
341
+ extraContext: context,
342
+ reasoning
343
+ });
344
+ if (!candidates || candidates.length === 0) {
345
+ return jsonResult({
346
+ status: "fallback",
347
+ message: "LLM endpoint did not return transformed candidates; returning original input.",
348
+ mode: runMode.id,
349
+ transformed: text
192
350
  });
193
- if (!candidates || candidates.length === 0) {
194
- return {
195
- content: [
196
- {
197
- type: "text",
198
- text: JSON.stringify(
199
- {
200
- status: "fallback",
201
- message: "LLM endpoint did not return transformed candidates; returning original input.",
202
- transformed: text
203
- },
204
- null,
205
- 2
206
- )
207
- }
208
- ]
209
- };
210
- }
211
- const primary = candidates[0];
212
- const finalTransformed = sanitized.rawPayload ? ensureCodeTokensPreserved(sanitized.rawPayload, primary.content) : primary.content;
213
- return {
214
- content: [
215
- {
216
- type: "text",
217
- text: JSON.stringify(
218
- {
219
- status: "success",
220
- loadout: loadoutId,
221
- transformed: finalTransformed,
222
- explanation: primary.explanation,
223
- vocab: primary.vocab,
224
- sourceText: text
225
- },
226
- null,
227
- 2
228
- )
229
- }
230
- ]
231
- };
232
- } catch (err) {
233
- return {
234
- isError: true,
235
- content: [{ type: "text", text: `Transformation failed: ${err?.message || String(err)}` }]
236
- };
237
351
  }
352
+ const primary = candidates[0];
353
+ const finalTransformed = sanitized.rawPayload ? ensureCodeTokensPreserved(sanitized.rawPayload, primary.content) : primary.content;
354
+ return jsonResult({
355
+ status: "success",
356
+ mode: runMode.id,
357
+ loadout: loadoutId,
358
+ reasoning: runMode.reasoning ?? "off",
359
+ transformed: finalTransformed,
360
+ explanation: primary.explanation,
361
+ vocab: primary.vocab,
362
+ sourceText: text
363
+ });
364
+ } catch (err) {
365
+ return errorResult(`Transformation failed: ${err instanceof Error ? err.message : String(err)}`);
238
366
  }
239
- if (name === "lingual_bilingual_companion") {
240
- const text = String(args?.text || "");
241
- const targetLang = String(args?.targetLang || "en");
242
- const sourceLang = args?.sourceLang ? String(args.sourceLang) : detectScriptLanguage(text) || diskConfig.sourceLang || "zh";
243
- if (!llm.configured) {
244
- return {
245
- content: [
246
- {
247
- type: "text",
248
- text: JSON.stringify(
249
- {
250
- status: "unconfigured_zero_key_fallback",
251
- message: "No external LLM credentials configured (set LINGUAL_ENDPOINT / OPENAI_BASE_URL and LINGUAL_API_KEY / OPENAI_API_KEY). Use compiledSystemPrompt in your host agent.",
252
- compiledSystemPrompt: buildSystemPrompt(sourceLang, targetLang),
253
- sourceText: text
254
- },
255
- null,
256
- 2
257
- )
258
- }
259
- ]
260
- };
261
- }
262
- try {
263
- const result = await translatePrompt(text, {
264
- endpoint: llm.endpoint,
265
- apiKey: llm.apiKey,
266
- model: llm.model,
367
+ }
368
+ if (name === "lingual_bilingual_companion") {
369
+ const text = String(args?.text || "");
370
+ const targetLang = String(args?.targetLang || "en");
371
+ const sourceLang = args?.sourceLang ? String(args.sourceLang) : detectScriptLanguage(text) || disk.sourceLang || "zh";
372
+ const explainLang = disk.explainLang || sourceLang;
373
+ const reasoning = normalizeReasoningArg(args?.reasoning);
374
+ const includeVocab = args?.includeVocab !== false;
375
+ const companion = resolveMode("companion", sourceLang, explainLang, disk.modes);
376
+ const runMode = companion ? applyModeOverrides(companion, { reasoning, includeVocab }) : null;
377
+ if (!llm.configured) {
378
+ return jsonResult({
379
+ status: "unconfigured_zero_key_fallback",
380
+ message: "No external LLM credentials configured (set LINGUAL_ENDPOINT / OPENAI_BASE_URL and LINGUAL_API_KEY / OPENAI_API_KEY). Use compiledSystemPrompt in your host agent.",
381
+ compiledSystemPrompt: compileModeSystemPrompt2(runMode ?? {}, {
267
382
  sourceLang,
268
- targetLang
383
+ targetLang,
384
+ explainLang,
385
+ globalKillList: disk.globalKillList
386
+ }),
387
+ sourceText: text
388
+ });
389
+ }
390
+ try {
391
+ const result = await translateCore(text, {
392
+ endpoint: llm.endpoint,
393
+ apiKey: llm.apiKey,
394
+ model: llm.model,
395
+ sourceLang,
396
+ targetLang,
397
+ explainLang,
398
+ slots: runMode?.slots,
399
+ killList: runMode?.killList,
400
+ globalKillList: disk.globalKillList,
401
+ reasoning: reasoning ?? runMode?.reasoning
402
+ });
403
+ if (!result) {
404
+ return jsonResult({
405
+ status: "empty",
406
+ message: "No translation generated (input might be pure code or bypassed by shield).",
407
+ sourceText: text
269
408
  });
270
- if (!result) {
271
- return {
272
- content: [
273
- {
274
- type: "text",
275
- text: JSON.stringify(
276
- {
277
- status: "empty",
278
- message: "No translation generated (input might be pure code or bypassed by shield).",
279
- sourceText: text
280
- },
281
- null,
282
- 2
283
- )
284
- }
285
- ]
286
- };
287
- }
288
- return {
289
- content: [
290
- {
291
- type: "text",
292
- text: JSON.stringify(
293
- {
294
- status: "success",
295
- spoken: result.spoken,
296
- nativeSpoken: result.nativeSpoken,
297
- written: result.written,
298
- nativeWritten: result.nativeWritten,
299
- vocab: result.vocab,
300
- sourceText: result.original
301
- },
302
- null,
303
- 2
304
- )
305
- }
306
- ]
307
- };
308
- } catch (err) {
309
- return {
310
- isError: true,
311
- content: [{ type: "text", text: `Companion mapping failed: ${err?.message || String(err)}` }]
312
- };
313
409
  }
410
+ return jsonResult({
411
+ status: "success",
412
+ spoken: result.spoken,
413
+ nativeSpoken: result.nativeSpoken,
414
+ written: result.written,
415
+ nativeWritten: result.nativeWritten,
416
+ vocab: result.vocab,
417
+ sourceText: result.original
418
+ });
419
+ } catch (err) {
420
+ return errorResult(`Companion mapping failed: ${err instanceof Error ? err.message : String(err)}`);
314
421
  }
315
- if (name === "lingual_prompt_template") {
316
- const loadoutId = String(args?.loadout || "spec");
317
- const sourceLang = String(args?.sourceLang || "zh");
318
- const targetLang = String(args?.targetLang || "en");
319
- if (loadoutId === "companion") {
320
- return {
321
- content: [{ type: "text", text: buildSystemPrompt(sourceLang, targetLang) }]
322
- };
323
- }
324
- const preset = getPresetLoadout(loadoutId, sourceLang);
325
- if (!preset) {
326
- return {
327
- isError: true,
328
- content: [{ type: "text", text: `Unknown loadout preset: ${loadoutId}` }]
329
- };
330
- }
331
- return {
332
- content: [{ type: "text", text: compileModeSystemPrompt(preset, { sourceLang, targetLang }) }]
333
- };
422
+ }
423
+ if (name === "lingual_prompt_template") {
424
+ const loadoutId = String(args?.loadout || "spec");
425
+ const sourceLang = String(args?.sourceLang || "zh");
426
+ const targetLang = String(args?.targetLang || "en");
427
+ const explainLang = disk.explainLang || sourceLang;
428
+ const includeVocab = args?.includeVocab !== false;
429
+ const mode = resolveMode(loadoutId, sourceLang, explainLang, disk.modes);
430
+ if (!mode) {
431
+ return errorResult(`Unknown loadout or mode: ${loadoutId}. Known ids: ${modeIds(disk, ["companion"]).join(", ")}`);
334
432
  }
335
433
  return {
336
- isError: true,
337
- content: [{ type: "text", text: `Unknown tool name: ${name}` }]
338
- };
339
- });
340
- server.setRequestHandler(ListPromptsRequestSchema, async () => {
341
- return {
342
- prompts: [
434
+ content: [
343
435
  {
344
- name: "spec_prompt",
345
- description: "Structure raw developer instructions into a rigorous technical specification.",
346
- arguments: [
347
- { name: "raw_idea", description: "The raw thought or instruction to structure.", required: true },
348
- { name: "source_lang", description: "Optional source language code (default: auto/zh).", required: false },
349
- { name: "target_lang", description: "Optional target language code (default: en).", required: false }
350
- ]
351
- },
352
- {
353
- name: "conventional_commit",
354
- description: "Dehydrate plain explanation into a Conventional Commit (first line <= 72 chars).",
355
- arguments: [
356
- { name: "changes_summary", description: "Description of what was changed and why.", required: true },
357
- { name: "source_lang", description: "Optional source language code (default: auto/zh).", required: false },
358
- { name: "target_lang", description: "Optional target language code (default: en).", required: false }
359
- ]
436
+ type: "text",
437
+ text: compileModeSystemPrompt2(applyModeOverrides(mode, { includeVocab }), {
438
+ sourceLang,
439
+ targetLang,
440
+ explainLang,
441
+ globalKillList: disk.globalKillList
442
+ })
360
443
  }
361
444
  ]
362
445
  };
363
- });
364
- server.setRequestHandler(GetPromptRequestSchema, async (request) => {
365
- const { name, arguments: args } = request.params;
366
- const sourceLang = args?.source_lang || "zh";
367
- const targetLang = args?.target_lang || "en";
368
- if (name === "spec_prompt") {
369
- const idea = args?.raw_idea || "";
370
- const sys = compileModeSystemPrompt(getPresetLoadout("spec", sourceLang), { sourceLang, targetLang });
371
- return {
372
- description: "Transform idea into an engineering specification",
373
- messages: [
374
- { role: "user", content: { type: "text", text: `${sys}
375
-
376
- Task to structure:
377
- ${idea}` } }
378
- ]
379
- };
380
- }
381
- if (name === "conventional_commit") {
382
- const summary = args?.changes_summary || "";
383
- const sys = compileModeSystemPrompt(getPresetLoadout("commit", sourceLang), { sourceLang, targetLang });
384
- return {
385
- description: "Transform change summary into Conventional Commit",
386
- messages: [
387
- { role: "user", content: { type: "text", text: `${sys}
446
+ }
447
+ return errorResult(`Unknown tool name: ${name}`);
448
+ }
388
449
 
389
- Changes to commit:
390
- ${summary}` } }
391
- ]
392
- };
393
- }
394
- throw new Error(`Prompt not found: ${name}`);
395
- });
450
+ // src/index.ts
451
+ function createLingualMcpServer(options = {}) {
452
+ const readDisk = () => options.diskConfig ?? loadUserLingualConfig();
453
+ const server = new Server(
454
+ { name: "lingual-mcp", version: PKG_VERSION },
455
+ { capabilities: { tools: {}, prompts: {} } }
456
+ );
457
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
458
+ tools: listLingualTools(readDisk())
459
+ }));
460
+ server.setRequestHandler(
461
+ CallToolRequestSchema,
462
+ async (request) => handleLingualToolCall(
463
+ request.params.name,
464
+ request.params.arguments,
465
+ readDisk()
466
+ )
467
+ );
468
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({
469
+ prompts: listLingualPrompts()
470
+ }));
471
+ server.setRequestHandler(
472
+ GetPromptRequestSchema,
473
+ async (request) => getLingualPrompt(
474
+ request.params.name,
475
+ request.params.arguments,
476
+ readDisk()
477
+ )
478
+ );
396
479
  return server;
397
480
  }
398
481
  async function runLingualMcpServer() {
@@ -401,7 +484,15 @@ async function runLingualMcpServer() {
401
484
  await server.connect(transport);
402
485
  }
403
486
  export {
487
+ PKG_VERSION,
488
+ PRESET_IDS,
489
+ REASONING_LEVELS,
490
+ applyModeOverrides,
404
491
  createLingualMcpServer,
492
+ modeIds,
493
+ normalizeReasoningArg,
405
494
  resolveMcpLlmConfig,
406
- runLingualMcpServer
495
+ resolveMode,
496
+ runLingualMcpServer,
497
+ stripVocabSlots
407
498
  };