@cocaxcode/logbook-mcp 0.5.0 → 0.5.1

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.
@@ -1,1022 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/server.ts
4
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
-
6
- // src/tools/topics.ts
7
- import { z } from "zod";
8
-
9
- // src/storage/index.ts
10
- import { createRequire } from "module";
11
- var require2 = createRequire(import.meta.url);
12
- var instance = null;
13
- var VALID_MODES = ["sqlite", "obsidian"];
14
- function getStorageMode() {
15
- const mode = process.env.LOGBOOK_STORAGE?.toLowerCase();
16
- if (!mode) return "sqlite";
17
- if (mode === "obsidian") return "obsidian";
18
- if (mode === "sqlite") return "sqlite";
19
- throw new Error(
20
- `LOGBOOK_STORAGE invalido: "${mode}". Valores validos: ${VALID_MODES.join(", ")}`
21
- );
22
- }
23
- function getStorage() {
24
- if (instance) return instance;
25
- const mode = getStorageMode();
26
- if (mode === "obsidian") {
27
- const dir = process.env.LOGBOOK_DIR;
28
- if (!dir) {
29
- throw new Error(
30
- "LOGBOOK_DIR es requerido cuando LOGBOOK_STORAGE=obsidian. Debe apuntar a la carpeta del vault de Obsidian."
31
- );
32
- }
33
- const mod = require2("./obsidian/index.js");
34
- instance = new mod.ObsidianStorage(dir);
35
- } else {
36
- const mod = require2("./sqlite/index.js");
37
- instance = new mod.SqliteStorage();
38
- }
39
- return instance;
40
- }
41
-
42
- // src/tools/topics.ts
43
- function registerTopicsTool(server) {
44
- server.tool(
45
- "logbook_topics",
46
- "Lista o crea temas para organizar notas y TODOs. Temas predefinidos: feature, fix, chore, idea, decision, blocker.",
47
- {
48
- action: z.enum(["list", "add"]).default("list").describe("Accion: list (ver temas) o add (crear tema custom)"),
49
- name: z.string().min(1).max(50).regex(/^[a-z0-9-]+$/, "Solo letras minusculas, numeros y guiones").optional().describe("Nombre del nuevo tema (solo para action=add, lowercase, sin espacios)"),
50
- description: z.string().max(200).optional().describe("Descripcion del nuevo tema (solo para action=add)")
51
- },
52
- async ({ action, name, description }) => {
53
- try {
54
- const storage = getStorage();
55
- if (action === "add") {
56
- if (!name) {
57
- return {
58
- isError: true,
59
- content: [{ type: "text", text: 'El parametro "name" es obligatorio para action=add' }]
60
- };
61
- }
62
- const topics2 = storage.getTopics();
63
- if (topics2.some((t) => t.name === name)) {
64
- return {
65
- isError: true,
66
- content: [{ type: "text", text: `El topic "${name}" ya existe` }]
67
- };
68
- }
69
- const topic = storage.insertTopic(name, description);
70
- return {
71
- content: [{ type: "text", text: JSON.stringify(topic) }]
72
- };
73
- }
74
- const topics = storage.getTopics();
75
- return {
76
- content: [{ type: "text", text: JSON.stringify(topics) }]
77
- };
78
- } catch (err) {
79
- return {
80
- isError: true,
81
- content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }]
82
- };
83
- }
84
- }
85
- );
86
- }
87
-
88
- // src/tools/note.ts
89
- import { z as z2 } from "zod";
90
- function registerNoteTool(server) {
91
- server.tool(
92
- "logbook_note",
93
- "A\xF1ade una nota al logbook. Topics: feature, fix, chore, idea, decision, blocker. Si no se pasa topic, queda sin categorizar.",
94
- {
95
- content: z2.string().min(1).max(5e3).describe("Contenido de la nota"),
96
- topic: z2.string().optional().describe("Topic: feature, fix, chore, idea, decision, blocker (o custom)")
97
- },
98
- async ({ content, topic }) => {
99
- try {
100
- const storage = getStorage();
101
- storage.autoRegisterRepo();
102
- const note = storage.insertNote(content, topic);
103
- return {
104
- content: [{ type: "text", text: JSON.stringify(note) }]
105
- };
106
- } catch (err) {
107
- return {
108
- isError: true,
109
- content: [{ type: "text", text: `Error creando nota: ${err instanceof Error ? err.message : String(err)}` }]
110
- };
111
- }
112
- }
113
- );
114
- }
115
-
116
- // src/tools/todo-add.ts
117
- import { z as z3 } from "zod";
118
- var priorityEnum = z3.enum(["low", "normal", "high", "urgent"]);
119
- function registerTodoAddTool(server) {
120
- server.tool(
121
- "logbook_todo_add",
122
- "Crea uno o varios TODOs. Para uno solo usa content. Para varios usa items (array). El topic se puede pasar o dejar que la AI lo infiera.",
123
- {
124
- content: z3.string().min(1).max(2e3).optional().describe("Contenido del TODO (para crear uno solo)"),
125
- topic: z3.string().optional().describe("Topic para el TODO individual"),
126
- priority: priorityEnum.optional().default("normal").describe("Prioridad del TODO individual"),
127
- remind_at: z3.string().optional().describe("Fecha recordatorio unica (YYYY-MM-DD)"),
128
- remind_pattern: z3.string().optional().describe("Patron recurrente: daily, weekdays, weekly:2 (martes), weekly:1,3 (lun+mie), monthly:1 (dia 1), monthly:1,15"),
129
- items: z3.array(
130
- z3.object({
131
- content: z3.string().min(1).max(2e3).describe("Contenido del TODO"),
132
- topic: z3.string().optional().describe("Topic"),
133
- priority: priorityEnum.optional().default("normal").describe("Prioridad"),
134
- remind_at: z3.string().optional().describe("Fecha recordatorio (YYYY-MM-DD)"),
135
- remind_pattern: z3.string().optional().describe("Patron recurrente")
136
- })
137
- ).max(50).optional().describe("Array de TODOs para crear varios a la vez (max 50)")
138
- },
139
- async ({ content, topic, priority, remind_at, remind_pattern, items }) => {
140
- try {
141
- if (!content && (!items || items.length === 0)) {
142
- return {
143
- isError: true,
144
- content: [{
145
- type: "text",
146
- text: 'Debes pasar "content" (para uno) o "items" (para varios)'
147
- }]
148
- };
149
- }
150
- const storage = getStorage();
151
- storage.autoRegisterRepo();
152
- const todoItems = items ? items : [{ content, topic, priority: priority ?? "normal", remind_at, remind_pattern }];
153
- const results = [];
154
- for (const item of todoItems) {
155
- const hasReminder = item.remind_at || item.remind_pattern;
156
- const effectiveTopic = hasReminder && !item.topic ? "reminder" : item.topic;
157
- const todo = storage.insertTodo(item.content, {
158
- topic: effectiveTopic,
159
- priority: item.priority ?? "normal",
160
- remind_at: item.remind_at,
161
- remind_pattern: item.remind_pattern
162
- });
163
- results.push(todo);
164
- }
165
- return {
166
- content: [{
167
- type: "text",
168
- text: JSON.stringify(
169
- results.length === 1 ? results[0] : { created: results.length, todos: results }
170
- )
171
- }]
172
- };
173
- } catch (err) {
174
- return {
175
- isError: true,
176
- content: [{ type: "text", text: `Error creando TODO: ${err instanceof Error ? err.message : String(err)}` }]
177
- };
178
- }
179
- }
180
- );
181
- }
182
-
183
- // src/tools/todo-list.ts
184
- import { z as z4 } from "zod";
185
-
186
- // src/git/detect-repo.ts
187
- import { execFileSync } from "child_process";
188
- import { basename } from "path";
189
-
190
- // src/db/queries.ts
191
- var NOTE_WITH_META_SQL = `
192
- SELECT n.*, r.name as repo_name, t.name as topic_name
193
- FROM notes n
194
- LEFT JOIN repos r ON n.repo_id = r.id
195
- LEFT JOIN topics t ON n.topic_id = t.id
196
- `;
197
- function getNotes(db2, filters = {}) {
198
- const conditions = [];
199
- const params = [];
200
- if (filters.repoId !== void 0) {
201
- conditions.push("n.repo_id = ?");
202
- params.push(filters.repoId);
203
- }
204
- if (filters.topicId !== void 0) {
205
- conditions.push("n.topic_id = ?");
206
- params.push(filters.topicId);
207
- }
208
- if (filters.from) {
209
- conditions.push("n.created_at >= ?");
210
- params.push(filters.from);
211
- }
212
- if (filters.to) {
213
- conditions.push("n.created_at < ?");
214
- params.push(filters.to);
215
- }
216
- const where = conditions.length ? ` WHERE ${conditions.join(" AND ")}` : "";
217
- const limit = filters.limit ?? 100;
218
- return db2.prepare(
219
- `${NOTE_WITH_META_SQL}${where} ORDER BY n.created_at DESC LIMIT ?`
220
- ).all(...params, limit);
221
- }
222
- var TODO_WITH_META_SQL = `
223
- SELECT t.*, r.name as repo_name, tp.name as topic_name, 'manual' as source
224
- FROM todos t
225
- LEFT JOIN repos r ON t.repo_id = r.id
226
- LEFT JOIN topics tp ON t.topic_id = tp.id
227
- `;
228
- function getTodos(db2, filters = {}) {
229
- const conditions = [];
230
- const params = [];
231
- if (filters.status && filters.status !== "all") {
232
- conditions.push("t.status = ?");
233
- params.push(filters.status);
234
- }
235
- if (filters.repoId !== void 0) {
236
- conditions.push("t.repo_id = ?");
237
- params.push(filters.repoId);
238
- }
239
- if (filters.topicId !== void 0) {
240
- conditions.push("t.topic_id = ?");
241
- params.push(filters.topicId);
242
- }
243
- if (filters.priority) {
244
- conditions.push("t.priority = ?");
245
- params.push(filters.priority);
246
- }
247
- if (filters.from) {
248
- conditions.push("t.created_at >= ?");
249
- params.push(filters.from);
250
- }
251
- if (filters.to) {
252
- conditions.push("t.created_at < ?");
253
- params.push(filters.to);
254
- }
255
- const where = conditions.length ? ` WHERE ${conditions.join(" AND ")}` : "";
256
- const limit = filters.limit ?? 100;
257
- return db2.prepare(
258
- `${TODO_WITH_META_SQL}${where} ORDER BY t.created_at DESC LIMIT ?`
259
- ).all(...params, limit);
260
- }
261
-
262
- // src/git/detect-repo.ts
263
- function detectRepoPath() {
264
- try {
265
- const result = execFileSync("git", ["rev-parse", "--show-toplevel"], {
266
- encoding: "utf-8",
267
- timeout: 5e3,
268
- stdio: ["pipe", "pipe", "pipe"]
269
- });
270
- return result.trim().replace(/\\/g, "/");
271
- } catch {
272
- return null;
273
- }
274
- }
275
-
276
- // src/tools/todo-list.ts
277
- function registerTodoListTool(server) {
278
- server.tool(
279
- "logbook_todo_list",
280
- "Lista TODOs agrupados por topic. Incluye manuales y del codigo (TODO/FIXME/HACK/BUG). Sincroniza automaticamente: code TODOs que desaparecen del codigo se marcan como resueltos.",
281
- {
282
- status: z4.enum(["pending", "done", "all"]).optional().default("pending").describe("Filtrar por estado (default: pending)"),
283
- topic: z4.string().optional().describe("Filtrar por topic"),
284
- priority: z4.enum(["low", "normal", "high", "urgent"]).optional().describe("Filtrar por prioridad"),
285
- source: z4.enum(["all", "manual", "code"]).optional().default("all").describe("Filtrar por origen: manual (DB), code (git grep), all"),
286
- scope: z4.enum(["project", "global"]).optional().default("project").describe("Scope: project (auto-detecta) o global (todos los proyectos)"),
287
- from: z4.string().optional().describe("Desde fecha (YYYY-MM-DD)"),
288
- to: z4.string().optional().describe("Hasta fecha (YYYY-MM-DD)"),
289
- limit: z4.number().optional().default(100).describe("Maximo resultados manuales")
290
- },
291
- async ({ status, topic, priority, source, scope, from, to, limit }) => {
292
- try {
293
- const storage = getStorage();
294
- if (scope === "project") storage.autoRegisterRepo();
295
- const manualTodos = source === "code" ? [] : storage.getTodos({
296
- status,
297
- topicId: topic,
298
- priority,
299
- from,
300
- to,
301
- limit
302
- });
303
- let codeTodos = [];
304
- let syncResult = null;
305
- if (source !== "manual" && status !== "done") {
306
- const repoPath = scope === "project" ? detectRepoPath() : null;
307
- if (repoPath) {
308
- codeTodos = storage.getCodeTodos(repoPath);
309
- syncResult = storage.syncCodeTodos(repoPath, codeTodos);
310
- if (topic) {
311
- codeTodos = codeTodos.filter((ct) => ct.topic_name === topic);
312
- }
313
- }
314
- }
315
- const groupMap = /* @__PURE__ */ new Map();
316
- for (const todo of manualTodos) {
317
- const key = todo.topic ?? "sin-topic";
318
- if (!groupMap.has(key)) groupMap.set(key, []);
319
- groupMap.get(key).push(todo);
320
- }
321
- for (const ct of codeTodos) {
322
- const key = ct.topic_name;
323
- if (!groupMap.has(key)) groupMap.set(key, []);
324
- groupMap.get(key).push(ct);
325
- }
326
- const groups = Array.from(groupMap.entries()).sort(([a], [b]) => a.localeCompare(b)).map(([topicName, items]) => ({ topic: topicName, items }));
327
- return {
328
- content: [{
329
- type: "text",
330
- text: JSON.stringify({
331
- groups,
332
- summary: {
333
- manual: manualTodos.length,
334
- code: codeTodos.length,
335
- total: manualTodos.length + codeTodos.length,
336
- ...syncResult && (syncResult.added > 0 || syncResult.resolved > 0) ? { sync: syncResult } : {}
337
- }
338
- })
339
- }]
340
- };
341
- } catch (err) {
342
- return {
343
- isError: true,
344
- content: [{ type: "text", text: `Error listando TODOs: ${err instanceof Error ? err.message : String(err)}` }]
345
- };
346
- }
347
- }
348
- );
349
- }
350
-
351
- // src/tools/todo-done.ts
352
- import { z as z5 } from "zod";
353
- function registerTodoDoneTool(server) {
354
- server.tool(
355
- "logbook_todo_done",
356
- "Marca TODOs como hechos o los devuelve a pendiente (undo). Los recordatorios recurrentes se marcan como hechos por hoy y vuelven automaticamente el proximo dia que toque.",
357
- {
358
- ids: z5.union([z5.number(), z5.string(), z5.array(z5.union([z5.number(), z5.string()]))]).describe("ID o array de IDs de TODOs a marcar"),
359
- undo: z5.boolean().optional().default(false).describe("Si true, devuelve a pendiente en vez de marcar como hecho")
360
- },
361
- async ({ ids, undo }) => {
362
- try {
363
- const storage = getStorage();
364
- storage.autoRegisterRepo();
365
- const idArray = (Array.isArray(ids) ? ids : [ids]).map(String);
366
- const allTodos = storage.getTodos({ status: "all" });
367
- const todoMap = new Map(allTodos.map((t) => [t.id, t]));
368
- const regularIds = [];
369
- const recurringIds = [];
370
- for (const id of idArray) {
371
- const todo = todoMap.get(id);
372
- if (todo?.remind_pattern && !undo) {
373
- recurringIds.push(id);
374
- } else {
375
- regularIds.push(id);
376
- }
377
- }
378
- const results = [];
379
- if (regularIds.length > 0) {
380
- const status = undo ? "pending" : "done";
381
- const updated = storage.updateTodoStatus(regularIds, status);
382
- results.push(...updated);
383
- }
384
- for (const id of recurringIds) {
385
- storage.ackRecurringReminder(id);
386
- const todo = todoMap.get(id);
387
- if (todo) results.push(todo);
388
- }
389
- return {
390
- content: [{
391
- type: "text",
392
- text: JSON.stringify({
393
- action: undo ? "undo" : "done",
394
- updated: results.length,
395
- recurring_acked: recurringIds.length,
396
- todos: results
397
- })
398
- }]
399
- };
400
- } catch (err) {
401
- return {
402
- isError: true,
403
- content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }]
404
- };
405
- }
406
- }
407
- );
408
- }
409
-
410
- // src/tools/todo-edit.ts
411
- import { z as z6 } from "zod";
412
- function registerTodoEditTool(server) {
413
- server.tool(
414
- "logbook_todo_edit",
415
- "Edita un TODO existente: contenido, topic o prioridad.",
416
- {
417
- id: z6.union([z6.number(), z6.string()]).describe("ID del TODO a editar"),
418
- content: z6.string().optional().describe("Nuevo contenido"),
419
- topic: z6.string().optional().describe("Nuevo topic"),
420
- priority: z6.enum(["low", "normal", "high", "urgent"]).optional().describe("Nueva prioridad")
421
- },
422
- async ({ id, content, topic, priority }) => {
423
- try {
424
- const storage = getStorage();
425
- storage.autoRegisterRepo();
426
- const updated = storage.updateTodo(String(id), { content, topic, priority });
427
- if (!updated) {
428
- return {
429
- isError: true,
430
- content: [{ type: "text", text: `TODO #${id} no encontrado o sin cambios` }]
431
- };
432
- }
433
- return {
434
- content: [{ type: "text", text: JSON.stringify(updated) }]
435
- };
436
- } catch (err) {
437
- return {
438
- isError: true,
439
- content: [{ type: "text", text: `Error editando TODO: ${err instanceof Error ? err.message : String(err)}` }]
440
- };
441
- }
442
- }
443
- );
444
- }
445
-
446
- // src/tools/todo-rm.ts
447
- import { z as z7 } from "zod";
448
- function registerTodoRmTool(server) {
449
- server.tool(
450
- "logbook_todo_rm",
451
- "Elimina TODOs por ID. Acepta uno o varios IDs.",
452
- {
453
- ids: z7.union([z7.number(), z7.string(), z7.array(z7.union([z7.number(), z7.string()]))]).describe("ID o array de IDs de TODOs a eliminar")
454
- },
455
- async ({ ids }) => {
456
- try {
457
- const storage = getStorage();
458
- storage.autoRegisterRepo();
459
- const idArray = (Array.isArray(ids) ? ids : [ids]).map(String);
460
- const deleted = storage.deleteTodos(idArray);
461
- return {
462
- content: [{
463
- type: "text",
464
- text: JSON.stringify({
465
- deleted: deleted.length,
466
- ids: deleted
467
- })
468
- }]
469
- };
470
- } catch (err) {
471
- return {
472
- isError: true,
473
- content: [{ type: "text", text: `Error eliminando TODOs: ${err instanceof Error ? err.message : String(err)}` }]
474
- };
475
- }
476
- }
477
- );
478
- }
479
-
480
- // src/tools/log.ts
481
- import { z as z8 } from "zod";
482
- function registerLogTool(server) {
483
- server.tool(
484
- "logbook_log",
485
- "Muestra actividad: notas y TODOs completados para un periodo. Por defecto muestra el dia de hoy del proyecto actual.",
486
- {
487
- period: z8.enum(["today", "yesterday", "week", "month"]).optional().describe("Periodo predefinido (default: today)"),
488
- from: z8.string().optional().describe("Desde fecha (YYYY-MM-DD). Sobreescribe period."),
489
- to: z8.string().optional().describe("Hasta fecha (YYYY-MM-DD). Sobreescribe period."),
490
- type: z8.enum(["all", "notes", "todos"]).optional().default("all").describe("Filtrar por tipo: all, notes, todos"),
491
- topic: z8.string().optional().describe("Filtrar por topic"),
492
- scope: z8.enum(["project", "global"]).optional().default("project").describe("Scope: project (auto-detecta) o global")
493
- },
494
- async ({ period, from, to, type, topic, scope }) => {
495
- try {
496
- const storage = getStorage();
497
- const repo = scope === "project" ? storage.autoRegisterRepo() : null;
498
- const entries = storage.getLog({
499
- period,
500
- from,
501
- to,
502
- type,
503
- topic,
504
- scope
505
- });
506
- return {
507
- content: [{
508
- type: "text",
509
- text: JSON.stringify({
510
- period: from ? `${from} \u2014 ${to || from}` : period ?? "today",
511
- scope: scope ?? "project",
512
- project: repo?.name ?? null,
513
- entries,
514
- summary: {
515
- total: entries.length
516
- }
517
- })
518
- }]
519
- };
520
- } catch (err) {
521
- return {
522
- isError: true,
523
- content: [{ type: "text", text: `Error: ${err instanceof Error ? err.message : String(err)}` }]
524
- };
525
- }
526
- }
527
- );
528
- }
529
-
530
- // src/tools/search.ts
531
- import { z as z9 } from "zod";
532
- function registerSearchTool(server) {
533
- server.tool(
534
- "logbook_search",
535
- "Busqueda full-text en notas y TODOs. Usa FTS5 para busqueda rapida.",
536
- {
537
- query: z9.string().min(1).max(500).describe("Texto a buscar"),
538
- type: z9.enum(["all", "notes", "todos"]).optional().default("all").describe("Buscar en: all, notes, todos"),
539
- topic: z9.string().optional().describe("Filtrar por topic"),
540
- scope: z9.enum(["project", "global"]).optional().default("project").describe("Scope: project o global"),
541
- limit: z9.number().optional().default(20).describe("Maximo resultados (default: 20)")
542
- },
543
- async ({ query, type, topic, scope, limit }) => {
544
- try {
545
- const storage = getStorage();
546
- if (scope === "project") storage.autoRegisterRepo();
547
- const results = storage.search(query, { type, topic, scope, limit });
548
- return {
549
- content: [{
550
- type: "text",
551
- text: JSON.stringify({
552
- query,
553
- results,
554
- total: results.length
555
- })
556
- }]
557
- };
558
- } catch (err) {
559
- return {
560
- isError: true,
561
- content: [{ type: "text", text: `Error buscando: ${err instanceof Error ? err.message : String(err)}` }]
562
- };
563
- }
564
- }
565
- );
566
- }
567
-
568
- // src/tools/standup.ts
569
- import { z as z10 } from "zod";
570
- function registerStandupTool(server) {
571
- server.tool(
572
- "logbook_standup",
573
- "Registra un standup diario con lo que se hizo ayer, lo de hoy y blockers. Ideal para Daily Notes en Obsidian.",
574
- {
575
- yesterday: z10.string().min(1).max(2e3).describe("Lo que se hizo ayer"),
576
- today: z10.string().min(1).max(2e3).describe("Lo que se va a hacer hoy"),
577
- blockers: z10.string().max(2e3).optional().default("").describe("Blockers actuales (opcional)"),
578
- topic: z10.string().optional().describe("Topic (opcional)")
579
- },
580
- async ({ yesterday, today, blockers, topic }) => {
581
- try {
582
- const storage = getStorage();
583
- storage.autoRegisterRepo();
584
- const standup = storage.insertStandup(yesterday, today, blockers, topic);
585
- return {
586
- content: [{ type: "text", text: JSON.stringify(standup) }]
587
- };
588
- } catch (err) {
589
- return {
590
- isError: true,
591
- content: [{ type: "text", text: `Error creando standup: ${err instanceof Error ? err.message : String(err)}` }]
592
- };
593
- }
594
- }
595
- );
596
- }
597
-
598
- // src/tools/decision.ts
599
- import { z as z11 } from "zod";
600
- function registerDecisionTool(server) {
601
- server.tool(
602
- "logbook_decision",
603
- "Registra una decision arquitectonica o tecnica (ADR). Incluye contexto, opciones, decision y consecuencias.",
604
- {
605
- title: z11.string().min(1).max(200).describe("Titulo de la decision"),
606
- context: z11.string().min(1).max(3e3).describe("Contexto: por que se necesita esta decision"),
607
- options: z11.array(z11.string().min(1).max(500)).min(1).max(10).describe("Opciones consideradas"),
608
- decision: z11.string().min(1).max(2e3).describe("Decision tomada"),
609
- consequences: z11.string().min(1).max(2e3).describe("Consecuencias de la decision"),
610
- topic: z11.string().optional().describe("Topic (default: decision)")
611
- },
612
- async ({ title, context, options, decision, consequences, topic }) => {
613
- try {
614
- const storage = getStorage();
615
- storage.autoRegisterRepo();
616
- const entry = storage.insertDecision(title, context, options, decision, consequences, topic);
617
- return {
618
- content: [{ type: "text", text: JSON.stringify(entry) }]
619
- };
620
- } catch (err) {
621
- return {
622
- isError: true,
623
- content: [{ type: "text", text: `Error creando decision: ${err instanceof Error ? err.message : String(err)}` }]
624
- };
625
- }
626
- }
627
- );
628
- }
629
-
630
- // src/tools/debug.ts
631
- import { z as z12 } from "zod";
632
- function registerDebugTool(server) {
633
- server.tool(
634
- "logbook_debug",
635
- "Registra una sesion de debug: error, causa, fix y archivo adjunto opcional. En Obsidian se muestra como callout [!bug].",
636
- {
637
- title: z12.string().min(1).max(200).describe("Titulo del bug/error"),
638
- error: z12.string().min(1).max(3e3).describe("Descripcion del error"),
639
- cause: z12.string().min(1).max(3e3).describe("Causa raiz identificada"),
640
- fix: z12.string().min(1).max(3e3).describe("Solucion aplicada"),
641
- file: z12.string().optional().describe("Ruta a archivo adjunto (screenshot, log). Se copia al vault."),
642
- topic: z12.string().optional().describe("Topic (default: fix)")
643
- },
644
- async ({ title, error, cause, fix, file, topic }) => {
645
- try {
646
- const storage = getStorage();
647
- storage.autoRegisterRepo();
648
- const entry = storage.insertDebug(title, error, cause, fix, file, topic);
649
- return {
650
- content: [{ type: "text", text: JSON.stringify(entry) }]
651
- };
652
- } catch (err) {
653
- return {
654
- isError: true,
655
- content: [{ type: "text", text: `Error creando debug entry: ${err instanceof Error ? err.message : String(err)}` }]
656
- };
657
- }
658
- }
659
- );
660
- }
661
-
662
- // src/tools/tags.ts
663
- import { z as z13 } from "zod";
664
- function registerTagsTool(server) {
665
- server.tool(
666
- "logbook_tags",
667
- "Lista todos los tags usados en el logbook con su conteo. Opcionalmente filtra por un tag especifico.",
668
- {
669
- filter: z13.string().optional().describe("Filtrar por tag especifico (opcional)")
670
- },
671
- async ({ filter }) => {
672
- try {
673
- const storage = getStorage();
674
- storage.autoRegisterRepo();
675
- const tags = storage.getTags(filter);
676
- return {
677
- content: [{ type: "text", text: JSON.stringify({ tags, total: tags.length }) }]
678
- };
679
- } catch (err) {
680
- return {
681
- isError: true,
682
- content: [{ type: "text", text: `Error listando tags: ${err instanceof Error ? err.message : String(err)}` }]
683
- };
684
- }
685
- }
686
- );
687
- }
688
-
689
- // src/tools/timeline.ts
690
- import { z as z14 } from "zod";
691
- function registerTimelineTool(server) {
692
- server.tool(
693
- "logbook_timeline",
694
- "Timeline de actividad cruzando proyectos y workspaces. Muestra un resumen cronologico de toda la actividad.",
695
- {
696
- period: z14.enum(["today", "yesterday", "week", "month"]).optional().default("week").describe("Periodo (default: week)"),
697
- from: z14.string().optional().describe("Desde fecha (YYYY-MM-DD). Sobreescribe period."),
698
- to: z14.string().optional().describe("Hasta fecha (YYYY-MM-DD). Sobreescribe period."),
699
- workspace: z14.string().optional().describe("Filtrar por workspace (opcional)")
700
- },
701
- async ({ period, from, to, workspace }) => {
702
- try {
703
- const storage = getStorage();
704
- storage.autoRegisterRepo();
705
- const entries = storage.getTimeline({ period, from, to, workspace });
706
- return {
707
- content: [{
708
- type: "text",
709
- text: JSON.stringify({
710
- period: from ? `${from} \u2014 ${to || from}` : period,
711
- entries,
712
- total: entries.length
713
- })
714
- }]
715
- };
716
- } catch (err) {
717
- return {
718
- isError: true,
719
- content: [{ type: "text", text: `Error generando timeline: ${err instanceof Error ? err.message : String(err)}` }]
720
- };
721
- }
722
- }
723
- );
724
- }
725
-
726
- // src/db/connection.ts
727
- import Database from "better-sqlite3";
728
- import { existsSync, mkdirSync } from "fs";
729
- import { homedir } from "os";
730
- import { dirname, join } from "path";
731
-
732
- // src/db/schema.ts
733
- var SCHEMA_SQL = `
734
- CREATE TABLE IF NOT EXISTS repos (
735
- id INTEGER PRIMARY KEY AUTOINCREMENT,
736
- name TEXT NOT NULL UNIQUE,
737
- path TEXT NOT NULL UNIQUE,
738
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
739
- );
740
-
741
- CREATE TABLE IF NOT EXISTS topics (
742
- id INTEGER PRIMARY KEY AUTOINCREMENT,
743
- name TEXT NOT NULL UNIQUE,
744
- description TEXT,
745
- commit_prefix TEXT,
746
- is_custom INTEGER NOT NULL DEFAULT 0,
747
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
748
- );
749
-
750
- CREATE TABLE IF NOT EXISTS notes (
751
- id INTEGER PRIMARY KEY AUTOINCREMENT,
752
- repo_id INTEGER REFERENCES repos(id) ON DELETE SET NULL,
753
- topic_id INTEGER REFERENCES topics(id) ON DELETE SET NULL,
754
- content TEXT NOT NULL,
755
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
756
- );
757
-
758
- CREATE TABLE IF NOT EXISTS todos (
759
- id INTEGER PRIMARY KEY AUTOINCREMENT,
760
- repo_id INTEGER REFERENCES repos(id) ON DELETE SET NULL,
761
- topic_id INTEGER REFERENCES topics(id) ON DELETE SET NULL,
762
- content TEXT NOT NULL,
763
- status TEXT NOT NULL DEFAULT 'pending',
764
- priority TEXT NOT NULL DEFAULT 'normal',
765
- remind_at TEXT,
766
- remind_pattern TEXT,
767
- remind_last_done TEXT,
768
- completed_at TEXT,
769
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
770
- );
771
-
772
- CREATE INDEX IF NOT EXISTS idx_notes_repo ON notes(repo_id);
773
- CREATE INDEX IF NOT EXISTS idx_notes_topic ON notes(topic_id);
774
- CREATE INDEX IF NOT EXISTS idx_notes_date ON notes(created_at);
775
- CREATE INDEX IF NOT EXISTS idx_todos_repo ON todos(repo_id);
776
- CREATE INDEX IF NOT EXISTS idx_todos_topic ON todos(topic_id);
777
- CREATE INDEX IF NOT EXISTS idx_todos_status ON todos(status);
778
- CREATE INDEX IF NOT EXISTS idx_todos_date ON todos(created_at);
779
- CREATE TABLE IF NOT EXISTS code_todo_snapshots (
780
- id INTEGER PRIMARY KEY AUTOINCREMENT,
781
- repo_id INTEGER NOT NULL REFERENCES repos(id) ON DELETE CASCADE,
782
- file TEXT NOT NULL,
783
- line INTEGER NOT NULL,
784
- tag TEXT NOT NULL,
785
- content TEXT NOT NULL,
786
- topic_name TEXT NOT NULL,
787
- first_seen_at TEXT NOT NULL DEFAULT (datetime('now')),
788
- resolved_at TEXT,
789
- UNIQUE(repo_id, file, content)
790
- );
791
-
792
- CREATE INDEX IF NOT EXISTS idx_code_snapshots_repo ON code_todo_snapshots(repo_id);
793
- CREATE INDEX IF NOT EXISTS idx_code_snapshots_resolved ON code_todo_snapshots(resolved_at);
794
-
795
- CREATE VIRTUAL TABLE IF NOT EXISTS notes_fts USING fts5(
796
- content,
797
- content='notes',
798
- content_rowid='id'
799
- );
800
-
801
- CREATE VIRTUAL TABLE IF NOT EXISTS todos_fts USING fts5(
802
- content,
803
- content='todos',
804
- content_rowid='id'
805
- );
806
-
807
- CREATE TRIGGER IF NOT EXISTS notes_ai AFTER INSERT ON notes BEGIN
808
- INSERT INTO notes_fts(rowid, content) VALUES (new.id, new.content);
809
- END;
810
- CREATE TRIGGER IF NOT EXISTS notes_ad AFTER DELETE ON notes BEGIN
811
- INSERT INTO notes_fts(notes_fts, rowid, content) VALUES ('delete', old.id, old.content);
812
- END;
813
- CREATE TRIGGER IF NOT EXISTS notes_au AFTER UPDATE ON notes BEGIN
814
- INSERT INTO notes_fts(notes_fts, rowid, content) VALUES ('delete', old.id, old.content);
815
- INSERT INTO notes_fts(rowid, content) VALUES (new.id, new.content);
816
- END;
817
-
818
- CREATE TRIGGER IF NOT EXISTS todos_ai AFTER INSERT ON todos BEGIN
819
- INSERT INTO todos_fts(rowid, content) VALUES (new.id, new.content);
820
- END;
821
- CREATE TRIGGER IF NOT EXISTS todos_ad AFTER DELETE ON todos BEGIN
822
- INSERT INTO todos_fts(todos_fts, rowid, content) VALUES ('delete', old.id, old.content);
823
- END;
824
- CREATE TRIGGER IF NOT EXISTS todos_au AFTER UPDATE ON todos BEGIN
825
- INSERT INTO todos_fts(todos_fts, rowid, content) VALUES ('delete', old.id, old.content);
826
- INSERT INTO todos_fts(rowid, content) VALUES (new.id, new.content);
827
- END;
828
- `;
829
- var MIGRATIONS_SQL = `
830
- -- Add reminder columns to existing todos tables (safe to run multiple times)
831
- ALTER TABLE todos ADD COLUMN remind_at TEXT;
832
- ALTER TABLE todos ADD COLUMN remind_pattern TEXT;
833
- ALTER TABLE todos ADD COLUMN remind_last_done TEXT;
834
- `;
835
- var POST_MIGRATION_SQL = `
836
- CREATE INDEX IF NOT EXISTS idx_todos_remind ON todos(remind_at);
837
- `;
838
- var SEED_TOPICS_SQL = `
839
- INSERT OR IGNORE INTO topics (name, description, commit_prefix, is_custom) VALUES
840
- ('feature', 'Funcionalidad nueva', 'feat', 0),
841
- ('fix', 'Correcci\xF3n de errores', 'fix', 0),
842
- ('chore', 'Mantenimiento general', 'refactor,docs,ci,build,chore,test,perf', 0),
843
- ('idea', 'Ideas y propuestas futuras', NULL, 0),
844
- ('decision', 'Decisiones tomadas', NULL, 0),
845
- ('blocker', 'Bloqueos activos', NULL, 0),
846
- ('reminder', 'Recordatorios con fecha', NULL, 0);
847
- `;
848
-
849
- // src/db/connection.ts
850
- var DB_DIR = join(homedir(), ".logbook");
851
- var DB_PATH = join(DB_DIR, "logbook.db");
852
- var db = null;
853
- function getDb(dbPath) {
854
- if (db) return db;
855
- const path = dbPath ?? DB_PATH;
856
- const dir = dirname(path);
857
- if (!existsSync(dir)) {
858
- mkdirSync(dir, { recursive: true });
859
- }
860
- db = new Database(path);
861
- db.pragma("journal_mode = WAL");
862
- db.pragma("foreign_keys = ON");
863
- db.exec(SCHEMA_SQL);
864
- for (const stmt of MIGRATIONS_SQL.split(";").map((s) => s.trim()).filter(Boolean)) {
865
- try {
866
- db.exec(stmt);
867
- } catch (e) {
868
- const msg = e instanceof Error ? e.message : String(e);
869
- if (!msg.includes("duplicate column")) {
870
- console.error(`Migration warning: ${msg}`);
871
- }
872
- }
873
- }
874
- db.exec(POST_MIGRATION_SQL);
875
- db.exec(SEED_TOPICS_SQL);
876
- return db;
877
- }
878
-
879
- // src/tools/migrate.ts
880
- function registerMigrateTool(server) {
881
- server.tool(
882
- "logbook_migrate",
883
- "Convierte datos existentes de SQLite a archivos markdown para Obsidian. Requiere LOGBOOK_STORAGE=obsidian y que exista la base de datos SQLite.",
884
- {},
885
- async () => {
886
- try {
887
- if (getStorageMode() !== "obsidian") {
888
- return {
889
- isError: true,
890
- content: [{
891
- type: "text",
892
- text: "logbook_migrate requiere LOGBOOK_STORAGE=obsidian. Configura las variables de entorno antes de migrar."
893
- }]
894
- };
895
- }
896
- let db2;
897
- try {
898
- db2 = getDb();
899
- } catch {
900
- return {
901
- isError: true,
902
- content: [{
903
- type: "text",
904
- text: "No se encontro la base de datos SQLite en ~/.logbook/logbook.db"
905
- }]
906
- };
907
- }
908
- const notes = getNotes(db2, { limit: 1e4 });
909
- const todos = getTodos(db2, { limit: 1e4 });
910
- const storage = getStorage();
911
- storage.autoRegisterRepo();
912
- let migratedNotes = 0;
913
- let migratedTodos = 0;
914
- for (const note of notes) {
915
- try {
916
- storage.insertNote(note.content, note.topic_name || void 0);
917
- migratedNotes++;
918
- } catch {
919
- }
920
- }
921
- for (const todo of todos) {
922
- try {
923
- const entry = storage.insertTodo(todo.content, {
924
- topic: todo.topic_name || void 0,
925
- priority: todo.priority,
926
- remind_at: todo.remind_at || void 0,
927
- remind_pattern: todo.remind_pattern || void 0
928
- });
929
- if (todo.status === "done") {
930
- storage.updateTodoStatus([entry.id], "done");
931
- }
932
- migratedTodos++;
933
- } catch {
934
- }
935
- }
936
- return {
937
- content: [{
938
- type: "text",
939
- text: JSON.stringify({
940
- migrated: {
941
- notes: migratedNotes,
942
- todos: migratedTodos,
943
- total: migratedNotes + migratedTodos
944
- },
945
- source: "sqlite (~/.logbook/logbook.db)",
946
- destination: process.env.LOGBOOK_DIR
947
- })
948
- }]
949
- };
950
- } catch (err) {
951
- return {
952
- isError: true,
953
- content: [{ type: "text", text: `Error migrando: ${err instanceof Error ? err.message : String(err)}` }]
954
- };
955
- }
956
- }
957
- );
958
- }
959
-
960
- // src/resources/reminders.ts
961
- function registerRemindersResource(server) {
962
- server.resource(
963
- "reminders",
964
- "logbook://reminders",
965
- {
966
- description: "Recordatorios pendientes para hoy y atrasados, agrupados por proyecto. Vacio si no hay ninguno.",
967
- mimeType: "application/json"
968
- },
969
- async (uri) => {
970
- try {
971
- const storage = getStorage();
972
- storage.autoRegisterRepo();
973
- const result = storage.getDueReminders();
974
- if (!result) {
975
- return { contents: [] };
976
- }
977
- for (const group of result.recurring) {
978
- for (const reminder of group.reminders) {
979
- storage.ackRecurringReminder(reminder.id);
980
- }
981
- }
982
- return {
983
- contents: [{
984
- uri: uri.href,
985
- text: JSON.stringify(result)
986
- }]
987
- };
988
- } catch {
989
- return { contents: [] };
990
- }
991
- }
992
- );
993
- }
994
-
995
- // src/server.ts
996
- var VERSION = true ? "0.5.0" : "0.0.0";
997
- function createServer() {
998
- const server = new McpServer({
999
- name: "logbook-mcp",
1000
- version: VERSION
1001
- });
1002
- registerTopicsTool(server);
1003
- registerNoteTool(server);
1004
- registerTodoAddTool(server);
1005
- registerTodoListTool(server);
1006
- registerTodoDoneTool(server);
1007
- registerTodoEditTool(server);
1008
- registerTodoRmTool(server);
1009
- registerLogTool(server);
1010
- registerSearchTool(server);
1011
- registerStandupTool(server);
1012
- registerDecisionTool(server);
1013
- registerDebugTool(server);
1014
- registerTagsTool(server);
1015
- registerTimelineTool(server);
1016
- registerMigrateTool(server);
1017
- registerRemindersResource(server);
1018
- return server;
1019
- }
1020
- export {
1021
- createServer
1022
- };