@verbaly/mcp 0.74.0 → 0.76.0

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.
@@ -0,0 +1,619 @@
1
+ import { createRequire } from "node:module";
2
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
3
+ import { check, collectOrigins, counted, doctor, effectiveDrafts, extractProject, formatCheckResult, formatCheckWarnings, formatDoctorEntry, formatDoctorHealth, formatFinding, formatStatusResult, formatTranslateFailures, init, loadCatalogs, loadConfig, loadState, mergeTranslations, readState, recordTranslations, resolveProvider, shippedCatalogs, status, syncProject, translateCatalogs, wrapProject, writeDrafts } from "@verbaly/compiler";
4
+ import { relative } from "node:path";
5
+ import { z } from "zod";
6
+ //#region src/server.ts
7
+ const { version } = createRequire(import.meta.url)("../package.json");
8
+ const reply = (body, data) => ({
9
+ content: [{
10
+ type: "text",
11
+ text: body
12
+ }],
13
+ structuredContent: data
14
+ });
15
+ const rootInput = z.string().optional().describe("Project root holding verbaly.config (defaults to the server working directory)");
16
+ const perLocale = z.array(z.object({
17
+ locale: z.string(),
18
+ keys: z.array(z.string())
19
+ }));
20
+ const perLocaleEntries = z.array(z.object({
21
+ locale: z.string(),
22
+ key: z.string()
23
+ }));
24
+ const byLocale = (record) => Object.entries(record).map(([locale, keys]) => ({
25
+ locale,
26
+ keys
27
+ }));
28
+ const sourceSite = z.object({
29
+ file: z.string(),
30
+ line: z.number().optional(),
31
+ message: z.string()
32
+ });
33
+ function relativeTo(root) {
34
+ return (file) => relative(root, file).replaceAll("\\", "/");
35
+ }
36
+ function lockOf(findings, rel) {
37
+ for (const finding of findings) {
38
+ if (finding.kind !== "lock") continue;
39
+ const from = finding.from && { from: rel(finding.from) };
40
+ return { lock: {
41
+ file: rel(finding.file),
42
+ ...from,
43
+ ...finding.merged && { merged: true }
44
+ } };
45
+ }
46
+ return {};
47
+ }
48
+ function relativeCheck(root, result) {
49
+ const rel = relativeTo(root);
50
+ return {
51
+ ...result,
52
+ unknown: result.unknown.map((entry) => ({
53
+ ...entry,
54
+ files: entry.files.map(rel)
55
+ })),
56
+ extra: result.extra.map((entry) => ({
57
+ ...entry,
58
+ files: entry.files.map(rel)
59
+ })),
60
+ collisions: result.collisions.map((entry) => ({
61
+ ...entry,
62
+ sites: entry.sites.map((at) => ({
63
+ ...at,
64
+ file: rel(at.file)
65
+ }))
66
+ })),
67
+ divergent: result.divergent.map((entry) => ({
68
+ ...entry,
69
+ code: {
70
+ ...entry.code,
71
+ file: rel(entry.code.file)
72
+ }
73
+ }))
74
+ };
75
+ }
76
+ function createVerbalyMcp(options = {}) {
77
+ const server = new McpServer({
78
+ name: "verbaly",
79
+ version
80
+ });
81
+ const config = (root) => loadConfig(root ?? options.root ?? process.cwd());
82
+ const guarded = (run) => async (args) => {
83
+ try {
84
+ return await run(args);
85
+ } catch (error) {
86
+ return {
87
+ content: [{
88
+ type: "text",
89
+ text: error instanceof Error ? error.message : String(error)
90
+ }],
91
+ isError: true
92
+ };
93
+ }
94
+ };
95
+ server.registerResource("verbaly-config", "verbaly://config", {
96
+ title: "Project shape",
97
+ description: "The resolved Verbaly config: source locale, every locale, the catalog directory and where the language lives in the url. Read this before reasoning about anything else in the project.",
98
+ mimeType: "application/json"
99
+ }, async (uri) => {
100
+ const cfg = await config();
101
+ const shape = {
102
+ root: cfg.root,
103
+ sourceLocale: cfg.sourceLocale,
104
+ locales: cfg.locales,
105
+ localesDeclared: cfg.localesDeclared,
106
+ dir: cfg.dir,
107
+ routing: cfg.routing,
108
+ include: cfg.include
109
+ };
110
+ return { contents: [{
111
+ uri: uri.href,
112
+ mimeType: "application/json",
113
+ text: JSON.stringify(shape, null, 2)
114
+ }] };
115
+ });
116
+ server.registerResource("verbaly-catalog", new ResourceTemplate("verbaly://catalog/{locale}", { list: async () => {
117
+ return { resources: (await config()).locales.map((locale) => ({
118
+ name: `${locale} catalog`,
119
+ uri: `verbaly://catalog/${locale}`,
120
+ mimeType: "application/json"
121
+ })) };
122
+ } }), {
123
+ title: "Locale catalog",
124
+ description: "Every message of one locale, keyed the way the runtime sees them: a nested catalog arrives flattened, a text the code owns reads as the code has it, and an empty value means untranslated. This is the only way to read what a message actually says.",
125
+ mimeType: "application/json"
126
+ }, async (uri, { locale }) => {
127
+ const cfg = await config();
128
+ const name = String(locale);
129
+ if (!cfg.locales.includes(name)) {
130
+ const have = cfg.locales.join(", ");
131
+ throw new Error(`[verbaly] unknown locale "${name}": the project has ${have}`);
132
+ }
133
+ const registry = await extractProject(cfg);
134
+ const catalog = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false })[name] ?? {};
135
+ return { contents: [{
136
+ uri: uri.href,
137
+ mimeType: "application/json",
138
+ text: JSON.stringify(catalog, null, 2)
139
+ }] };
140
+ });
141
+ server.registerTool("verbaly_init", {
142
+ title: "Set up Verbaly in a project",
143
+ description: "Create the config file and the locale catalogs, and detect the bundler or meta-framework so the answer names the package to add and the line to wire (what `verbaly init` does). Writes files, and a file already there is kept rather than overwritten. Run this when doctor says there is no config.",
144
+ inputSchema: {
145
+ root: rootInput,
146
+ dir: z.string().optional().describe("Directory for the catalogs (default: locales)"),
147
+ sourceLocale: z.string().optional().describe("The language you write in (default: en)"),
148
+ locales: z.array(z.string()).optional().describe("Every locale, source included")
149
+ },
150
+ outputSchema: {
151
+ created: z.array(z.string()).describe("Files written, relative to the project root"),
152
+ skipped: z.array(z.string()).describe("Files already there, left untouched"),
153
+ host: z.string().optional().describe("Bundler or meta-framework detected from the dependencies"),
154
+ configFile: z.string(),
155
+ next: z.array(z.string()).describe("What a human still has to do, in order"),
156
+ renamed: z.array(z.object({
157
+ from: z.string(),
158
+ to: z.string()
159
+ })).describe("Locales written with the hyphen a locale tag takes (pt_BR became pt-BR)"),
160
+ refused: z.array(z.string()).describe("Locales left out: not a locale tag, and no sure way to fix one"),
161
+ found: z.string().optional().describe("Catalogs the project already had, which the new config points at")
162
+ }
163
+ }, guarded(async ({ root, dir, sourceLocale, locales }) => {
164
+ const result = await init({
165
+ root: root ?? options.root,
166
+ dir,
167
+ sourceLocale,
168
+ locales
169
+ });
170
+ const lines = [];
171
+ if (result.created.length) lines.push(`created: ${result.created.join(", ")}`);
172
+ if (result.skipped.length) lines.push(`kept (already there): ${result.skipped.join(", ")}`);
173
+ for (const { from, to } of result.renamed) lines.push(`wrote ${to} for ${from}`);
174
+ for (const locale of result.refused) lines.push(`left out "${locale}": it is not a locale tag, use one like es or pt-BR`);
175
+ if (result.found) lines.push(`catalogs: ${result.found}, kept where they already are`);
176
+ if (result.host) lines.push(`detected: ${result.host}`);
177
+ lines.push(...result.next.map((step, i) => `${i + 1}. ${step}`));
178
+ return reply(lines.join("\n"), { ...result });
179
+ }));
180
+ server.registerTool("verbaly_doctor", {
181
+ title: "Diagnose the setup",
182
+ description: "Diagnose a Verbaly project end to end (what `verbaly doctor` does): the config file, the catalog files and their JSON, the bundler plugin for the detected framework, the generated types, files the parser could not read, t imported from a package that never exports it, orphan keys, and every failure `verbaly check` would report. Run this first when something does not work. Read-only.",
183
+ inputSchema: { root: rootInput },
184
+ outputSchema: {
185
+ ok: z.boolean().describe("False when an entry is an error, which is when the CLI exits 1"),
186
+ entries: z.array(z.object({
187
+ level: z.enum([
188
+ "ok",
189
+ "warn",
190
+ "error"
191
+ ]),
192
+ check: z.string(),
193
+ message: z.string(),
194
+ fix: z.string().optional().describe("What to run or change, when there is one")
195
+ }))
196
+ },
197
+ annotations: { readOnlyHint: true }
198
+ }, guarded(async ({ root }) => {
199
+ const cfg = await config(root);
200
+ const result = await doctor(cfg);
201
+ const head = `${counted(result.entries.length, "check")}, ${formatDoctorHealth(result)}`;
202
+ return reply([head, ...result.entries.map(formatDoctorEntry)].join("\n"), { ...result });
203
+ }));
204
+ server.registerTool("verbaly_wrap", {
205
+ title: "Wrap hardcoded JSX text",
206
+ description: "Find hardcoded user-visible text in JSX/TSX files and wrap it in a t tagged template so the compiler can extract it (what `verbaly wrap` does). This is how an existing codebase is onboarded. Reports only unless write is set. Text it cannot wrap safely (a sentence split across markup, an expression rendering JSX) is listed as needing a human and never rewritten. A file that does not bind t is never written either, because the rewrite would not compile: those come back in blocked, with whether the file is a client component, so you can add the binding and run again.",
207
+ inputSchema: {
208
+ root: rootInput,
209
+ write: z.boolean().optional().describe("Apply the rewrites instead of only reporting")
210
+ },
211
+ outputSchema: {
212
+ files: z.number().describe("JSX/TSX files scanned"),
213
+ write: z.boolean(),
214
+ changed: z.array(z.string()).describe("Files the rewrite touched, or would touch"),
215
+ wrapped: z.array(z.object({
216
+ file: z.string(),
217
+ line: z.number(),
218
+ text: z.string(),
219
+ kind: z.enum(["text", "attribute"]),
220
+ attribute: z.string().optional()
221
+ })),
222
+ skipped: z.array(z.object({
223
+ file: z.string(),
224
+ line: z.number(),
225
+ text: z.string(),
226
+ reason: z.string()
227
+ })),
228
+ blocked: z.array(z.object({
229
+ file: z.string(),
230
+ texts: z.number(),
231
+ client: z.boolean()
232
+ }))
233
+ }
234
+ }, guarded(async ({ root, write }) => {
235
+ const cfg = await config(root);
236
+ const result = await wrapProject(cfg, { write });
237
+ const blocked = new Set(result.blocked.map((entry) => entry.file));
238
+ const done = result.changed.filter((file) => !blocked.has(file));
239
+ const texts = result.wrapped.filter((entry) => !blocked.has(entry.file));
240
+ const lines = [`${write ? "wrapped" : "would wrap"} ${write ? `${counted(texts.length, "text")} in ${counted(done.length, "file")}` : `${counted(result.wrapped.length, "text")} in ${counted(result.changed.length, "file")}`} of ${counted(result.files, "file")} scanned`];
241
+ for (const entry of write ? texts : result.wrapped) {
242
+ const attr = entry.kind === "attribute" ? `${entry.attribute} -> ` : "";
243
+ lines.push(` ${entry.file}:${entry.line} ${attr}"${entry.text}"`);
244
+ }
245
+ if (result.skipped.length > 0) {
246
+ lines.push(" needs a human:");
247
+ for (const entry of result.skipped) lines.push(` ${entry.file}:${entry.line} "${entry.text}" (${entry.reason})`);
248
+ }
249
+ if (result.blocked.length > 0) {
250
+ lines.push(` nothing written in ${counted(result.blocked.length, "file")} with no t in scope:`);
251
+ for (const entry of result.blocked) {
252
+ const how = entry.client ? "\"use client\", so const t = useT()" : "no \"use client\"";
253
+ lines.push(` ${entry.file} ${counted(entry.texts, "text")}, ${how}`);
254
+ }
255
+ lines.push(" next: bind t there, run verbaly_wrap with write again, then verbaly_extract");
256
+ } else if (write && done.length > 0) lines.push(" next: run verbaly_extract");
257
+ return reply(lines.join("\n"), {
258
+ ...result,
259
+ write: write === true
260
+ });
261
+ }));
262
+ server.registerTool("verbaly_extract", {
263
+ title: "Extract messages",
264
+ description: "Scan the source files, add new messages to the locale catalogs and refresh the generated types (what `verbaly extract` does). Writes catalog files unless dryRun is set. prune drops keys no longer referenced in the code, translations included.",
265
+ inputSchema: {
266
+ root: rootInput,
267
+ prune: z.boolean().optional().describe("Drop keys no longer referenced (deletes their translations)"),
268
+ dryRun: z.boolean().optional().describe("Report what would change, write nothing")
269
+ },
270
+ outputSchema: {
271
+ messages: z.number().describe("Messages the source catalog holds after this run"),
272
+ inCode: z.number().describe("How many of those messages the code writes as text: 0 when the project keeps its text in the catalog and reads it with t(key)"),
273
+ locales: z.array(z.string()),
274
+ dryRun: z.boolean(),
275
+ added: perLocale,
276
+ pruned: perLocale,
277
+ unparsed: z.array(z.object({
278
+ file: z.string(),
279
+ message: z.string()
280
+ })).describe("Source files the parser could not read: their messages are not extracted, and prune drops nothing until they parse"),
281
+ collisions: z.array(z.object({
282
+ key: z.string(),
283
+ sites: z.array(sourceSite)
284
+ })).describe("Keys written with more than one text: every place shows the text of the first site, so give each text its own key"),
285
+ renamed: z.array(z.object({
286
+ file: z.string(),
287
+ line: z.number().optional(),
288
+ name: z.string()
289
+ })).describe("Tagged templates on t under another name (const tr = useT()): never extracted, so they stay in the source language until the binding is named t"),
290
+ replaced: z.array(z.object({
291
+ key: z.string(),
292
+ before: z.string(),
293
+ code: sourceSite
294
+ })).describe("Source texts the code wrote over: before is what the catalog said, code is the text that ships. An edit made in the code reads like this too"),
295
+ positional: z.array(z.object({
296
+ params: z.array(z.string()),
297
+ code: sourceSite
298
+ })).describe("Messages that hand a translator a nameless value like {_0}: put the value in a named variable first"),
299
+ escaped: z.array(z.object({
300
+ slice: z.string(),
301
+ code: sourceSite
302
+ })).describe("Plural or format blocks inside a tagged template, which render as literal text"),
303
+ stateProblem: z.string().optional().describe("The state file could not be read or written: the catalogs were written, drafts and outdated tracking were not"),
304
+ lock: z.object({
305
+ file: z.string(),
306
+ from: z.string().optional(),
307
+ merged: z.boolean().optional()
308
+ }).optional().describe("This run created verbaly.lock, moved an older state file (from) into it, or rewrote it whole after a merge conflict (merged): it belongs in git with the catalogs, so tell the user to commit it")
309
+ }
310
+ }, guarded(async ({ root, prune, dryRun }) => {
311
+ const cfg = await config(root);
312
+ const result = await syncProject(cfg, {
313
+ prune,
314
+ dryRun
315
+ });
316
+ const rel = relativeTo(cfg.root);
317
+ const at = (code) => ({
318
+ ...code,
319
+ file: rel(code.file)
320
+ });
321
+ const data = {
322
+ messages: result.messages,
323
+ inCode: result.inCode,
324
+ locales: cfg.locales,
325
+ dryRun: dryRun === true,
326
+ added: byLocale(result.added),
327
+ pruned: byLocale(result.pruned),
328
+ unparsed: [],
329
+ collisions: [],
330
+ renamed: [],
331
+ replaced: [],
332
+ positional: [],
333
+ escaped: [],
334
+ ...result.stateProblem && { stateProblem: result.stateProblem },
335
+ ...lockOf(result.findings, rel)
336
+ };
337
+ for (const finding of result.findings) if (finding.kind === "unparsed") data.unparsed.push({
338
+ file: rel(finding.file),
339
+ message: finding.message
340
+ });
341
+ else if (finding.kind === "collision") data.collisions.push({
342
+ key: finding.key,
343
+ sites: finding.sites.map(at)
344
+ });
345
+ else if (finding.kind === "renamed") data.renamed.push({
346
+ ...finding,
347
+ file: rel(finding.file)
348
+ });
349
+ else if (finding.kind === "replaced") data.replaced.push({
350
+ key: finding.key,
351
+ before: finding.before,
352
+ code: at(finding.site)
353
+ });
354
+ else if (finding.kind === "positional") data.positional.push({
355
+ params: finding.params,
356
+ code: at(finding.site)
357
+ });
358
+ else if (finding.kind === "escaped") data.escaped.push({
359
+ slice: finding.slice,
360
+ code: at(finding.site)
361
+ });
362
+ const lines = [`${counted(data.messages, "message")} · locales: ${cfg.locales.join(", ")}${dryRun ? " (dry run, nothing written)" : ""}`];
363
+ if (result.pruneBlocked) lines.push("prune skipped: an unparsed file may read any key, so it waits until every file parses");
364
+ for (const { locale, keys } of data.pruned) lines.push(dryRun ? `${locale}: would prune ${keys.length}: ${keys.join(", ")}` : `${locale}: ${keys.length} pruned`);
365
+ for (const { locale, keys } of data.added) lines.push(`${locale}: ${dryRun ? `would add ${keys.length}` : `+${keys.length} added`}`);
366
+ for (const finding of result.findings) lines.push(formatFinding(finding, cfg.root));
367
+ if (result.stateProblem) lines.push(`${result.stateProblem}, so drafts and outdated translations were not updated`);
368
+ return reply(lines.join("\n"), data);
369
+ }));
370
+ server.registerTool("verbaly_status", {
371
+ title: "Translation coverage",
372
+ description: "Translation coverage of the Verbaly project: total messages, translated count per locale, machine translations awaiting review (drafts) and translations written for an older source text (outdated). Read-only.",
373
+ inputSchema: { root: rootInput },
374
+ outputSchema: {
375
+ messages: z.number().describe("Messages the project has, source catalog plus code"),
376
+ source: z.string().describe("Source locale"),
377
+ locales: z.array(z.object({
378
+ locale: z.string(),
379
+ translated: z.number(),
380
+ total: z.number(),
381
+ drafts: z.number().describe("Machine translations awaiting human review"),
382
+ broken: z.number().describe("Present but not rendering what the source renders"),
383
+ outdated: z.number().describe("Translated from an older source text: update them, or a human keeps them")
384
+ })),
385
+ stateProblem: z.string().optional().describe("The state file could not be read, so drafts and outdated are counted as zero")
386
+ },
387
+ annotations: { readOnlyHint: true }
388
+ }, guarded(async ({ root }) => {
389
+ const cfg = await config(root);
390
+ const registry = await extractProject(cfg);
391
+ const { state, problem } = readState(cfg);
392
+ const result = status(cfg, loadCatalogs(cfg), registry, state.drafts, state.fingerprints);
393
+ const body = formatStatusResult(result);
394
+ return reply(problem ? `${body}\n${problem}, so drafts and outdated are not counted` : body, {
395
+ ...result,
396
+ ...problem && { stateProblem: problem }
397
+ });
398
+ }));
399
+ server.registerTool("verbaly_missing", {
400
+ title: "Missing and broken translations",
401
+ description: "List missing translations, unknown keys, keys written with two texts (collisions: every place shows the first text) and translations that exist but cannot render what the source renders (a dropped {param}, a lost rich tag, a flattened plural block), the same gate `verbaly check` runs in CI. Warnings never fail the gate and are listed too: an incomplete plural set for the locale, keys a translation carries that the source catalog does not (extra), texts the code and the source catalog disagree on (divergent, the text in the code ships) and translations written for an older source text (outdated). Optionally also lists machine translations awaiting review. Read-only.",
402
+ inputSchema: {
403
+ root: rootInput,
404
+ drafts: z.boolean().optional().describe("Also list machine translations awaiting human review")
405
+ },
406
+ outputSchema: {
407
+ ok: z.boolean().describe("Whether `verbaly check` would pass (warnings never fail it)"),
408
+ missing: z.array(z.object({
409
+ locale: z.string(),
410
+ key: z.string(),
411
+ source: z.string().optional()
412
+ })),
413
+ unknown: z.array(z.object({
414
+ key: z.string(),
415
+ files: z.array(z.string())
416
+ })),
417
+ broken: z.array(z.object({
418
+ locale: z.string(),
419
+ key: z.string(),
420
+ severity: z.enum(["error", "warning"]),
421
+ issue: z.string()
422
+ })),
423
+ extra: z.array(z.object({
424
+ locale: z.string(),
425
+ key: z.string(),
426
+ files: z.array(z.string())
427
+ })).describe("Keys only a translation has; files are where the code reads one, which the source language then shows as the key itself. Never fails the gate"),
428
+ collisions: z.array(z.object({
429
+ key: z.string(),
430
+ sites: z.array(sourceSite)
431
+ })).describe("One key, several texts: every place shows the first site, so it fails the gate. Give each text its own key"),
432
+ divergent: z.array(z.object({
433
+ key: z.string(),
434
+ catalog: z.string(),
435
+ code: sourceSite
436
+ })).describe("The source catalog says one text and the code another: the code's text ships. Never fails the gate"),
437
+ outdated: perLocaleEntries.describe("Translations written for an older source text: rewrite them, or a human keeps them with verbaly review --approve. Never fails the gate"),
438
+ unreviewed: perLocale,
439
+ stateProblem: z.string().optional().describe("The state file could not be read, so outdated translations are not listed")
440
+ },
441
+ annotations: { readOnlyHint: true }
442
+ }, guarded(async ({ root, drafts }) => {
443
+ const cfg = await config(root);
444
+ const registry = await extractProject(cfg);
445
+ const catalogs = loadCatalogs(cfg);
446
+ const { state, problem } = drafts ? {
447
+ state: loadState(cfg),
448
+ problem: void 0
449
+ } : readState(cfg);
450
+ const result = check(cfg, catalogs, registry, state.fingerprints);
451
+ const unreviewed = drafts ? byLocale(effectiveDrafts(state.drafts, catalogs)) : [];
452
+ const lines = [];
453
+ if (!result.ok) lines.push(formatCheckResult(result, cfg.root));
454
+ const warnings = formatCheckWarnings(result, cfg.root);
455
+ if (warnings) lines.push(`warnings (the gate still passes):\n${warnings}`);
456
+ for (const { locale, keys } of unreviewed) if (keys.length) lines.push(`[${locale}] ${keys.length} unreviewed: ${keys.join(", ")}`);
457
+ if (problem) lines.push(`${problem}, so outdated translations are not listed`);
458
+ return reply(lines.length === 0 ? "all translations complete" : lines.join("\n"), {
459
+ ...relativeCheck(cfg.root, result),
460
+ unreviewed,
461
+ ...problem && { stateProblem: problem }
462
+ });
463
+ }));
464
+ server.registerTool("verbaly_translate", {
465
+ title: "Machine-translate missing entries",
466
+ description: "Fill missing translations with the configured provider (default: Claude, needs @anthropic-ai/sdk and ANTHROPIC_API_KEY). New translations are saved as drafts awaiting human review (`verbaly review`), which no tool here can approve. A batch the provider never answers is reported in failed and leaves everything else written, so a retry only asks for what is left. dryRun lists what would be translated without calling the provider.",
467
+ inputSchema: {
468
+ root: rootInput,
469
+ locales: z.array(z.string()).optional().describe("Target locales (default: all)"),
470
+ dryRun: z.boolean().optional().describe("List missing entries per locale, call no provider")
471
+ },
472
+ outputSchema: {
473
+ dryRun: z.boolean(),
474
+ translated: perLocale.describe("Saved as drafts, a human still has to approve them"),
475
+ kept: perLocale.describe("Written on disk by someone else while the provider worked, so left as they were"),
476
+ invalid: perLocale.describe("Rejected: params or tags were not preserved"),
477
+ failed: z.array(z.object({
478
+ locale: z.string(),
479
+ keys: z.array(z.string()),
480
+ error: z.string()
481
+ })).describe("Batches the provider never answered, safe to retry"),
482
+ pending: perLocale.describe("dryRun only: what would be translated")
483
+ }
484
+ }, guarded(async ({ root, locales, dryRun }) => {
485
+ const cfg = await config(root);
486
+ if (!dryRun) loadState(cfg);
487
+ const registry = await extractProject(cfg);
488
+ const catalogs = shippedCatalogs(cfg, loadCatalogs(cfg), registry, { newKeys: false });
489
+ const provider = await resolveProvider(cfg);
490
+ const result = await translateCatalogs(cfg, catalogs, provider, {
491
+ locales,
492
+ batchSize: cfg.translate.batchSize,
493
+ concurrency: cfg.translate.concurrency,
494
+ retries: cfg.translate.retries,
495
+ dryRun,
496
+ origins: dryRun ? void 0 : await collectOrigins(cfg, registry)
497
+ });
498
+ if (dryRun) {
499
+ const pending = byLocale(result.pending);
500
+ const lines = pending.map(({ locale, keys }) => `${locale}: ${keys.length} missing: ${keys.join(", ")}`);
501
+ const data = {
502
+ dryRun: true,
503
+ translated: [],
504
+ kept: [],
505
+ invalid: [],
506
+ failed: [],
507
+ pending
508
+ };
509
+ return reply(lines.length === 0 ? "nothing to translate" : lines.join("\n"), data);
510
+ }
511
+ const written = {};
512
+ const kept = {};
513
+ const writes = [];
514
+ for (const [locale, keys] of Object.entries(result.translated)) {
515
+ const catalog = catalogs[locale] ?? {};
516
+ const landed = mergeTranslations(cfg, locale, catalog, keys);
517
+ writes.push({
518
+ locale,
519
+ draft: true,
520
+ entries: landed.map((key) => ({
521
+ key,
522
+ text: catalog[key]
523
+ }))
524
+ });
525
+ if (landed.length > 0) written[locale] = landed;
526
+ const left = keys.filter((key) => !landed.includes(key));
527
+ if (left.length > 0) kept[locale] = left;
528
+ }
529
+ if (writes.length > 0) recordTranslations(cfg, catalogs[cfg.sourceLocale] ?? {}, writes);
530
+ const data = {
531
+ dryRun: false,
532
+ translated: byLocale(written),
533
+ kept: byLocale(kept),
534
+ invalid: byLocale(result.invalid),
535
+ failed: result.failed,
536
+ pending: []
537
+ };
538
+ const lines = [];
539
+ for (const { locale, keys } of data.translated) lines.push(`${locale}: +${keys.length} translated (draft)`);
540
+ for (const { locale, keys } of data.kept) lines.push(`${locale}: ${keys.length} kept as written while this ran: ${keys.join(", ")}`);
541
+ for (const { locale, keys } of data.invalid) lines.push(`${locale}: ${keys.length} rejected (params/tags not preserved): ${keys.join(", ")}`);
542
+ lines.push(...formatTranslateFailures(result.failed));
543
+ if (lines.length === 0) return reply("nothing to translate", data);
544
+ if (data.translated.length > 0) lines.push("drafts await human review: verbaly review (--approve accepts them)");
545
+ return reply(lines.join("\n"), data);
546
+ }));
547
+ server.registerTool("verbaly_write_drafts", {
548
+ title: "Save translations an agent wrote",
549
+ description: "Save translations you wrote yourself, so neither a catalog nor the state file is ever edited by hand. Each one is checked the way `verbaly translate` checks a provider (params, rich tags and plural cases must survive), written only for keys the source catalog has, and marked as a draft awaiting human review. Existing translations are kept unless overwrite is set, which is how an outdated one gets rewritten. Approving is not a tool here: a human runs `verbaly review --approve`.",
550
+ inputSchema: {
551
+ root: rootInput,
552
+ locale: z.string().describe("Target locale, one of the project's non-source locales"),
553
+ entries: z.array(z.object({
554
+ key: z.string(),
555
+ text: z.string()
556
+ })).describe("The translations, by catalog key"),
557
+ overwrite: z.boolean().optional().describe("Replace translations that already exist, for example outdated ones")
558
+ },
559
+ outputSchema: {
560
+ written: z.array(z.string()).describe("Saved as drafts, a human still has to approve them"),
561
+ kept: z.array(z.string()).describe("Already translated, left as they were (overwrite replaces them)"),
562
+ invalid: z.array(z.string()).describe("Rejected: empty, or the params, tags or plural cases were not preserved"),
563
+ unknown: z.array(z.string()).describe("Not in the source catalog, so nothing was written")
564
+ }
565
+ }, guarded(async ({ root, locale, entries, overwrite }) => {
566
+ const cfg = await config(root);
567
+ const registry = await extractProject(cfg);
568
+ const result = writeDrafts(cfg, locale, entries, {
569
+ overwrite,
570
+ registry
571
+ });
572
+ const lines = [];
573
+ if (result.written.length > 0) lines.push(`${locale}: +${result.written.length} saved as drafts, awaiting human review`);
574
+ if (result.kept.length > 0) lines.push(`${locale}: ${result.kept.length} already translated, kept: ${result.kept.join(", ")}`);
575
+ if (result.invalid.length > 0) lines.push(`${locale}: ${result.invalid.length} rejected (params/tags not preserved): ${result.invalid.join(", ")}`);
576
+ if (result.unknown.length > 0) lines.push(`${locale}: ${counted(result.unknown.length, "unknown key")} not in the source catalog: ${result.unknown.join(", ")}`);
577
+ return reply(lines.length > 0 ? lines.join("\n") : "nothing to save", { ...result });
578
+ }));
579
+ server.registerTool("verbaly_drafts", {
580
+ title: "Machine translations awaiting review",
581
+ description: "Every machine translation still waiting for a human, each with the source text and what the provider wrote, so a person can read both and decide. Read-only. Approving is deliberately not a tool here and never will be: a machine translation is unreviewed by definition, so accepting one is `verbaly review --approve`, run by a human.",
582
+ inputSchema: {
583
+ root: rootInput,
584
+ locales: z.array(z.string()).optional().describe("Target locales (default: all)")
585
+ },
586
+ outputSchema: {
587
+ total: z.number(),
588
+ entries: z.array(z.object({
589
+ locale: z.string(),
590
+ key: z.string(),
591
+ source: z.string().describe("What the message says in the source locale"),
592
+ translated: z.string().describe("What the provider wrote, still unreviewed")
593
+ }))
594
+ },
595
+ annotations: { readOnlyHint: true }
596
+ }, guarded(async ({ root, locales }) => {
597
+ const cfg = await config(root);
598
+ const catalogs = loadCatalogs(cfg);
599
+ const source = shippedCatalogs(cfg, catalogs, await extractProject(cfg))[cfg.sourceLocale] ?? {};
600
+ const pending = effectiveDrafts(loadState(cfg).drafts, catalogs);
601
+ const wanted = locales ?? cfg.locales;
602
+ const entries = Object.entries(pending).filter(([locale]) => wanted.includes(locale)).flatMap(([locale, keys]) => keys.map((key) => ({
603
+ locale,
604
+ key,
605
+ source: source[key] ?? "",
606
+ translated: catalogs[locale]?.[key] ?? ""
607
+ })));
608
+ const body = entries.length ? entries.map((e) => `[${e.locale}] ${e.key}
609
+ source: ${e.source}
610
+ draft: ${e.translated}`).join("\n") : "nothing awaiting review";
611
+ return reply(body, {
612
+ total: entries.length,
613
+ entries
614
+ });
615
+ }));
616
+ return server;
617
+ }
618
+ //#endregion
619
+ export { createVerbalyMcp as t };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@verbaly/mcp",
3
- "version": "0.74.0",
3
+ "version": "0.76.0",
4
4
  "description": "MCP server for Verbaly: diagnosis, onboarding, extraction, coverage and machine translation as tools for coding agents.",
5
5
  "keywords": [
6
6
  "i18n",
@@ -44,7 +44,7 @@
44
44
  },
45
45
  "dependencies": {
46
46
  "@modelcontextprotocol/sdk": "^1.32.1",
47
- "@verbaly/compiler": "^0.74.0",
47
+ "@verbaly/compiler": "^0.76.0",
48
48
  "zod": "^4.6.7"
49
49
  },
50
50
  "devDependencies": {