lingual-mcp 0.1.1 → 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,28 +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
- import { createRequire } from "module";
3
9
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
10
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
11
  import {
6
12
  CallToolRequestSchema,
7
- ListToolsRequestSchema,
13
+ GetPromptRequestSchema,
8
14
  ListPromptsRequestSchema,
9
- GetPromptRequestSchema
15
+ ListToolsRequestSchema
10
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";
11
23
  import {
12
- translateCore,
13
- executeModeRunner,
14
- compileModeSystemPrompt,
15
- loadUserLingualConfig,
16
- getPresetLoadout,
17
- sanitizePromptForTranslation,
18
- ensureCodeTokensPreserved,
19
- detectScriptLanguage
24
+ getPresetLoadout
20
25
  } from "pi-lingual/core";
21
- var require2 = createRequire(import.meta.url);
22
- var manifest = require2("../package.json");
23
- var PKG_VERSION = typeof manifest.version === "string" ? manifest.version : "0.0.0";
24
26
  var REASONING_LEVELS = ["off", "minimal", "low", "medium", "high"];
25
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();
26
50
  function isLoopbackUrl(urlStr) {
27
51
  try {
28
52
  const parsed = new URL(urlStr);
@@ -78,444 +102,380 @@ function modeIds(disk, extra = []) {
78
102
  const custom = (disk.modes || []).filter((mode) => mode.enabled !== false).map((mode) => mode.id);
79
103
  return Array.from(/* @__PURE__ */ new Set([...extra, ...PRESET_IDS, ...custom]));
80
104
  }
81
- function createLingualMcpServer(options = {}) {
82
- const readDisk = () => options.diskConfig ?? loadUserLingualConfig();
83
- const server = new Server(
105
+
106
+ // src/prompts.ts
107
+ import { compileModeSystemPrompt } from "pi-lingual/core";
108
+ function listLingualPrompts() {
109
+ return [
84
110
  {
85
- name: "lingual-mcp",
86
- 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
+ ]
87
118
  },
88
119
  {
89
- capabilities: {
90
- tools: {},
91
- prompts: {}
92
- }
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
+ ]
93
127
  }
94
- );
95
- server.setRequestHandler(ListToolsRequestSchema, async () => {
96
- const disk = readDisk();
97
- const transformIds = modeIds(disk);
98
- const templateIds = modeIds(disk, ["companion"]);
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");
99
142
  return {
100
- tools: [
101
- {
102
- name: "lingual_transform_spec",
103
- 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.",
104
- inputSchema: {
105
- type: "object",
106
- properties: {
107
- text: {
108
- type: "string",
109
- description: "The raw thought, feature requirement, issue draft, or commit message in any language."
110
- },
111
- loadout: {
112
- type: "string",
113
- enum: transformIds,
114
- 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'.",
115
- default: "spec"
116
- },
117
- sourceLang: {
118
- type: "string",
119
- description: "Source language code (e.g. 'zh', 'ja', 'en', 'es'). Auto-detected if omitted."
120
- },
121
- targetLang: {
122
- type: "string",
123
- description: "Target language code (e.g. 'en', 'ja', 'zh'). Default: 'en'.",
124
- default: "en"
125
- },
126
- reasoning: {
127
- type: "string",
128
- enum: REASONING_LEVELS,
129
- description: "Thinking effort for this call. Overrides the mode's pinned level (spec pins 'low', the rest pin 'off')."
130
- },
131
- context: {
132
- type: "string",
133
- description: "Extra context for context-aware modes, such as a staged git diff for 'commit' or the previous agent turn."
134
- },
135
- includeVocab: {
136
- type: "boolean",
137
- description: "Set false to drop the vocabulary slot from the prompt and the response. Default: true.",
138
- default: true
139
- }
140
- },
141
- 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
142
227
  }
143
228
  },
144
- {
145
- name: "lingual_bilingual_companion",
146
- 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.",
147
- inputSchema: {
148
- type: "object",
149
- properties: {
150
- text: {
151
- type: "string",
152
- description: "The natural language text or expression to unpack into technical dual-registers."
153
- },
154
- sourceLang: {
155
- type: "string",
156
- description: "Source language code (e.g. 'zh', 'ja'). Auto-detected if omitted."
157
- },
158
- targetLang: {
159
- type: "string",
160
- description: "Target language code (e.g. 'en', 'ja'). Default: 'en'.",
161
- default: "en"
162
- },
163
- reasoning: {
164
- type: "string",
165
- enum: REASONING_LEVELS,
166
- description: "Thinking effort for this call. Defaults to the companion mode's level ('off')."
167
- },
168
- includeVocab: {
169
- type: "boolean",
170
- description: "Set false to drop the vocabulary slot from the prompt and the response. Default: true.",
171
- default: true
172
- }
173
- },
174
- 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
175
260
  }
176
261
  },
177
- {
178
- name: "lingual_prompt_template",
179
- 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.",
180
- inputSchema: {
181
- type: "object",
182
- properties: {
183
- loadout: {
184
- type: "string",
185
- enum: templateIds,
186
- description: "Target mode or loadout id: any preset, 'companion', or a custom mode id from lingual.json.",
187
- default: "spec"
188
- },
189
- sourceLang: {
190
- type: "string",
191
- description: "Source language code (e.g. 'zh', 'ja', 'en'). Default: 'zh'.",
192
- default: "zh"
193
- },
194
- targetLang: {
195
- type: "string",
196
- description: "Target language code (e.g. 'en', 'ja'). Default: 'en'.",
197
- default: "en"
198
- },
199
- includeVocab: {
200
- type: "boolean",
201
- description: "Set false to drop the vocabulary slot from the compiled prompt. Default: true.",
202
- default: true
203
- }
204
- },
205
- required: ["loadout"]
206
- }
207
- }
208
- ]
209
- };
210
- });
211
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
212
- const { name, arguments: args } = request.params;
213
- const disk = readDisk();
214
- const llm = resolveMcpLlmConfig(disk);
215
- if (name === "lingual_transform_spec") {
216
- const text = String(args?.text || "");
217
- const loadoutId = String(args?.loadout || "spec");
218
- const targetLang = String(args?.targetLang || "en");
219
- const sourceLang = args?.sourceLang ? String(args.sourceLang) : detectScriptLanguage(text) || disk.sourceLang || "zh";
220
- const explainLang = disk.explainLang || sourceLang;
221
- const reasoning = normalizeReasoningArg(args?.reasoning);
222
- const includeVocab = args?.includeVocab !== false;
223
- const context = typeof args?.context === "string" && args.context.trim() ? args.context.trim() : void 0;
224
- const mode = resolveMode(loadoutId, sourceLang, explainLang, disk.modes);
225
- if (!mode) {
226
- return {
227
- isError: true,
228
- content: [
229
- {
230
- type: "text",
231
- text: `Unknown loadout or mode: ${loadoutId}. Known ids: ${modeIds(disk).join(", ")}`
232
- }
233
- ]
234
- };
262
+ required: ["text"]
235
263
  }
236
- const runMode = applyModeOverrides(mode, { reasoning, includeVocab });
237
- const sanitized = sanitizePromptForTranslation(text);
238
- const inputToTransform = sanitized.distilledText || text;
239
- if (!llm.configured) {
240
- return {
241
- content: [
242
- {
243
- type: "text",
244
- text: JSON.stringify(
245
- {
246
- status: "unconfigured_zero_key_fallback",
247
- 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.",
248
- mode: runMode.id,
249
- reasoning: runMode.reasoning ?? "off",
250
- distilledInput: inputToTransform,
251
- compiledSystemPrompt: compileModeSystemPrompt(runMode, {
252
- sourceLang,
253
- targetLang,
254
- explainLang,
255
- globalKillList: disk.globalKillList,
256
- extraContext: context
257
- })
258
- },
259
- null,
260
- 2
261
- )
262
- }
263
- ]
264
- };
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"]
265
294
  }
266
- try {
267
- const candidates = await executeModeRunner(inputToTransform, runMode, {
268
- endpoint: llm.endpoint,
269
- apiKey: llm.apiKey,
270
- 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, {
271
324
  sourceLang,
272
325
  targetLang,
273
326
  explainLang,
274
327
  globalKillList: disk.globalKillList,
275
- extraContext: context,
276
- reasoning
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
277
350
  });
278
- if (!candidates || candidates.length === 0) {
279
- return {
280
- content: [
281
- {
282
- type: "text",
283
- text: JSON.stringify(
284
- {
285
- status: "fallback",
286
- message: "LLM endpoint did not return transformed candidates; returning original input.",
287
- mode: runMode.id,
288
- transformed: text
289
- },
290
- null,
291
- 2
292
- )
293
- }
294
- ]
295
- };
296
- }
297
- const primary = candidates[0];
298
- const finalTransformed = sanitized.rawPayload ? ensureCodeTokensPreserved(sanitized.rawPayload, primary.content) : primary.content;
299
- return {
300
- content: [
301
- {
302
- type: "text",
303
- text: JSON.stringify(
304
- {
305
- status: "success",
306
- mode: runMode.id,
307
- loadout: loadoutId,
308
- reasoning: runMode.reasoning ?? "off",
309
- transformed: finalTransformed,
310
- explanation: primary.explanation,
311
- vocab: primary.vocab,
312
- sourceText: text
313
- },
314
- null,
315
- 2
316
- )
317
- }
318
- ]
319
- };
320
- } catch (err) {
321
- return {
322
- isError: true,
323
- content: [{ type: "text", text: `Transformation failed: ${err instanceof Error ? err.message : String(err)}` }]
324
- };
325
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)}`);
326
366
  }
327
- if (name === "lingual_bilingual_companion") {
328
- const text = String(args?.text || "");
329
- const targetLang = String(args?.targetLang || "en");
330
- const sourceLang = args?.sourceLang ? String(args.sourceLang) : detectScriptLanguage(text) || disk.sourceLang || "zh";
331
- const explainLang = disk.explainLang || sourceLang;
332
- const reasoning = normalizeReasoningArg(args?.reasoning);
333
- const includeVocab = args?.includeVocab !== false;
334
- const companion = resolveMode("companion", sourceLang, explainLang, disk.modes);
335
- const runMode = companion ? applyModeOverrides(companion, { reasoning, includeVocab }) : null;
336
- if (!llm.configured) {
337
- return {
338
- content: [
339
- {
340
- type: "text",
341
- text: JSON.stringify(
342
- {
343
- status: "unconfigured_zero_key_fallback",
344
- 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.",
345
- compiledSystemPrompt: compileModeSystemPrompt(runMode ?? {}, {
346
- sourceLang,
347
- targetLang,
348
- explainLang,
349
- globalKillList: disk.globalKillList
350
- }),
351
- sourceText: text
352
- },
353
- null,
354
- 2
355
- )
356
- }
357
- ]
358
- };
359
- }
360
- try {
361
- const result = await translateCore(text, {
362
- endpoint: llm.endpoint,
363
- apiKey: llm.apiKey,
364
- 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 ?? {}, {
365
382
  sourceLang,
366
383
  targetLang,
367
384
  explainLang,
368
- slots: runMode?.slots,
369
- killList: runMode?.killList,
370
- globalKillList: disk.globalKillList,
371
- reasoning: reasoning ?? runMode?.reasoning
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
372
408
  });
373
- if (!result) {
374
- return {
375
- content: [
376
- {
377
- type: "text",
378
- text: JSON.stringify(
379
- {
380
- status: "empty",
381
- message: "No translation generated (input might be pure code or bypassed by shield).",
382
- sourceText: text
383
- },
384
- null,
385
- 2
386
- )
387
- }
388
- ]
389
- };
390
- }
391
- return {
392
- content: [
393
- {
394
- type: "text",
395
- text: JSON.stringify(
396
- {
397
- status: "success",
398
- spoken: result.spoken,
399
- nativeSpoken: result.nativeSpoken,
400
- written: result.written,
401
- nativeWritten: result.nativeWritten,
402
- vocab: result.vocab,
403
- sourceText: result.original
404
- },
405
- null,
406
- 2
407
- )
408
- }
409
- ]
410
- };
411
- } catch (err) {
412
- return {
413
- isError: true,
414
- content: [{ type: "text", text: `Companion mapping failed: ${err instanceof Error ? err.message : String(err)}` }]
415
- };
416
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)}`);
417
421
  }
418
- if (name === "lingual_prompt_template") {
419
- const loadoutId = String(args?.loadout || "spec");
420
- const sourceLang = String(args?.sourceLang || "zh");
421
- const targetLang = String(args?.targetLang || "en");
422
- const explainLang = disk.explainLang || sourceLang;
423
- const includeVocab = args?.includeVocab !== false;
424
- const mode = resolveMode(loadoutId, sourceLang, explainLang, disk.modes);
425
- if (!mode) {
426
- return {
427
- isError: true,
428
- content: [
429
- {
430
- type: "text",
431
- text: `Unknown loadout or mode: ${loadoutId}. Known ids: ${modeIds(disk, ["companion"]).join(", ")}`
432
- }
433
- ]
434
- };
435
- }
436
- return {
437
- content: [
438
- {
439
- type: "text",
440
- text: compileModeSystemPrompt(applyModeOverrides(mode, { includeVocab }), {
441
- sourceLang,
442
- targetLang,
443
- explainLang,
444
- globalKillList: disk.globalKillList
445
- })
446
- }
447
- ]
448
- };
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(", ")}`);
449
432
  }
450
433
  return {
451
- isError: true,
452
- content: [{ type: "text", text: `Unknown tool name: ${name}` }]
453
- };
454
- });
455
- server.setRequestHandler(ListPromptsRequestSchema, async () => {
456
- return {
457
- prompts: [
458
- {
459
- name: "spec_prompt",
460
- description: "Structure raw developer instructions into a rigorous technical specification.",
461
- arguments: [
462
- { name: "raw_idea", description: "The raw thought or instruction to structure.", required: true },
463
- { name: "source_lang", description: "Optional source language code (default: auto/zh).", required: false },
464
- { name: "target_lang", description: "Optional target language code (default: en).", required: false }
465
- ]
466
- },
434
+ content: [
467
435
  {
468
- name: "conventional_commit",
469
- description: "Dehydrate plain explanation into a Conventional Commit (first line <= 72 chars).",
470
- arguments: [
471
- { name: "changes_summary", description: "Description of what was changed and why.", required: true },
472
- { name: "source_lang", description: "Optional source language code (default: auto/zh).", required: false },
473
- { name: "target_lang", description: "Optional target language code (default: en).", required: false }
474
- ]
436
+ type: "text",
437
+ text: compileModeSystemPrompt2(applyModeOverrides(mode, { includeVocab }), {
438
+ sourceLang,
439
+ targetLang,
440
+ explainLang,
441
+ globalKillList: disk.globalKillList
442
+ })
475
443
  }
476
444
  ]
477
445
  };
478
- });
479
- server.setRequestHandler(GetPromptRequestSchema, async (request) => {
480
- const { name, arguments: args } = request.params;
481
- const disk = readDisk();
482
- const sourceLang = args?.source_lang || disk.sourceLang || "zh";
483
- const targetLang = args?.target_lang || "en";
484
- const explainLang = disk.explainLang || sourceLang;
485
- const compile = (modeId) => {
486
- const mode = resolveMode(modeId, sourceLang, explainLang, disk.modes);
487
- return mode ? compileModeSystemPrompt(mode, { sourceLang, targetLang, explainLang, globalKillList: disk.globalKillList }) : null;
488
- };
489
- if (name === "spec_prompt") {
490
- const idea = args?.raw_idea || "";
491
- const sys = compile("spec");
492
- if (!sys) throw new Error("Spec mode is unavailable");
493
- return {
494
- description: "Transform idea into an engineering specification",
495
- messages: [
496
- { role: "user", content: { type: "text", text: `${sys}
497
-
498
- Task to structure:
499
- ${idea}` } }
500
- ]
501
- };
502
- }
503
- if (name === "conventional_commit") {
504
- const summary = args?.changes_summary || "";
505
- const sys = compile("commit");
506
- if (!sys) throw new Error("Commit mode is unavailable");
507
- return {
508
- description: "Transform change summary into Conventional Commit",
509
- messages: [
510
- { role: "user", content: { type: "text", text: `${sys}
446
+ }
447
+ return errorResult(`Unknown tool name: ${name}`);
448
+ }
511
449
 
512
- Changes to commit:
513
- ${summary}` } }
514
- ]
515
- };
516
- }
517
- throw new Error(`Prompt not found: ${name}`);
518
- });
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
+ );
519
479
  return server;
520
480
  }
521
481
  async function runLingualMcpServer() {
@@ -524,8 +484,12 @@ async function runLingualMcpServer() {
524
484
  await server.connect(transport);
525
485
  }
526
486
  export {
487
+ PKG_VERSION,
488
+ PRESET_IDS,
489
+ REASONING_LEVELS,
527
490
  applyModeOverrides,
528
491
  createLingualMcpServer,
492
+ modeIds,
529
493
  normalizeReasoningArg,
530
494
  resolveMcpLlmConfig,
531
495
  resolveMode,