-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
1592 lines (1520 loc) · 74.3 KB
/
Copy pathindex.js
File metadata and controls
1592 lines (1520 loc) · 74.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import next from 'next';
import cors from 'cors';
import path from 'path';
import fs from 'fs';
import { promises as fsp } from 'fs';
import { fileURLToPath } from 'url';
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import {
ListToolsRequestSchema,
CallToolRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
import { loadEnvFromDotenv } from './src/env.js';
loadEnvFromDotenv();
// Configuration
const BASE_PATH = process.env.BASE_PATH || '/mcp'; // MCP endpoint path
const HOST = process.env.HOST || process.env.MCP_HOST || 'localhost';
const PORT = process.env.PORT ? Number(process.env.PORT) : (process.env.MCP_PORT ? Number(process.env.MCP_PORT) : 3000);
import { buildAuthRouter, apiKeyQueryMiddleware } from './src/auth.js';
import {
listProjects as dbListProjects,
initProject as dbInitProject,
deleteProject as dbDeleteProject,
renameProject as dbRenameProject,
readDoc as dbReadDoc,
writeDoc as dbWriteDoc,
listTasks as dbListTasks,
addTasks as dbAddTasks,
replaceTasks as dbReplaceTasks,
setTasksState as dbSetTasksState,
listUserTaskIds as dbListUserTaskIds,
initScratchpad as dbInitScratchpad,
getScratchpad as dbGetScratchpad,
updateScratchpadTasks as dbUpdateScratchpadTasks,
appendScratchpadCommonMemory as dbAppendScratchpadCommonMemory,
getSubagentRun as dbGetSubagentRun,
listProjectFiles as dbListProjectFiles,
listProjectsForUserWithShares as dbListProjectsWithShares,
resolveProjectAccess as dbResolveProjectAccess,
getDataDir,
} from './src/db.js';
import { onInitProject as vcOnInitProject, commitProject as vcCommitProject, listProjectLogs as vcListLogs, revertProject as vcRevertProject } from './src/version.js';
import { runScratchpadSubagent, getProviderMeta, buildSelectedPagesMarkdown } from './src/ext_ai/ext_ai.js';
import { buildProjectsRouter } from './src/share.js';
import { buildProjectFilesRouter } from './src/project.js';
import { loadFilePayload } from './src/ext_ai/fileUtils.js';
const pdfParse = await import('pdf-parse').then(m => m.default || m);
// Utility: sanitize and validate project name (letters, digits, space, dot, underscore, hyphen)
function validateProjectName(name) {
if (typeof name !== 'string') return false;
const trimmed = name.trim();
if (trimmed.length === 0) return false;
// Allow common characters and spaces; disallow control characters and symbols
return /^[A-Za-z0-9._\- ]{1,100}$/.test(trimmed);
}
// DB-backed project and file operations (per-user)
function userOps(userId, userName) {
return {
async listProjects() {
const rows = await dbListProjectsWithShares(userId);
return rows;
},
async initProject(name, { agent = defaultAgentMd(name), progress = [] } = {}) {
if (!validateProjectName(name)) throw new Error('Invalid project name');
const agentJson = JSON.stringify({ content: agent });
// Progress now stored in structured tasks table; keep placeholder in project row
const progressJson = JSON.stringify({ content: '' });
const res = await dbInitProject(userId, name, { agentJson, progressJson });
// If structured tasks provided on init, try to insert them
const tasks = Array.isArray(progress) ? progress : [];
if (tasks.length) {
const valid = validateAndNormalizeTasks(tasks);
if (valid.invalid.length) {
res.invalid = valid.invalid;
}
if (valid.tasks.length) {
const addRes = await dbAddTasks(userId, res.id, valid.tasks);
res.added = addRes.added;
res.exists = addRes.exists;
} else {
res.added = [];
res.exists = [];
}
}
try {
const hash = await vcOnInitProject(userId, res.id);
res.hash = hash;
} catch (err) {
console.error(`Failed to initialize versioning for project "${name}":`, err);
}
return res;
},
async removeProject(projectId) {
await dbDeleteProject(userId, String(projectId || ''));
},
async renameProject(projectId, newName) {
if (!validateProjectName(newName)) throw new Error('Invalid project name');
return dbRenameProject(userId, String(projectId || ''), newName);
},
async readDoc(projectId, which) {
const acc = await dbResolveProjectAccess(userId, String(projectId || ''));
if (!acc) throw new Error('project not found');
return dbReadDoc(acc.owner_id, acc.project_id, which);
},
async writeDoc(projectId, which, content) {
const acc = await dbResolveProjectAccess(userId, String(projectId || ''));
if (!acc) throw new Error('project not found');
if (acc.permission === 'ro') { const e = new Error('read_only_project'); e.code = 'read_only_project'; throw e; }
await dbWriteDoc(acc.owner_id, acc.project_id, which, content);
return { modifiedBy: (acc.permission !== 'owner') ? (userName || userId) : null, ownerId: acc.owner_id };
},
};
}
// -------- Progress helpers --------
function coerceJsonArray(input) {
if (Array.isArray(input)) return input;
if (typeof input === 'string') {
const s = input.trim();
if (s.startsWith('[')) {
try {
const parsed = JSON.parse(s);
if (Array.isArray(parsed)) return parsed;
} catch {}
}
}
return null;
}
function coerceProgressContent(content) {
// Accept either raw markdown string or a JSON array of strings
const arr = coerceJsonArray(content);
if (arr) {
const lines = arr
.filter(v => typeof v === 'string' && v.trim().length > 0)
.map(v => formatProgressLine('pending', v.trim()));
return lines.join('\n') + (lines.length ? '\n' : '');
}
return String(content ?? '');
}
function parseProgressLine(line) {
// Returns { isItem, state, text }
const m = line.match(/^\s*-\s*\[(.|\s)\]\s*(.*)$/);
if (m) {
const raw = m[1].toLowerCase();
const text = m[2] ?? '';
let state = 'pending';
if (raw === 'x') state = 'completed';
else if (raw === '~' || raw === '-') state = 'in_progress';
else state = 'pending';
return { isItem: true, state, text };
}
// Fallback: dash bullet without checkbox
const m2 = line.match(/^\s*-\s+(.*)$/);
if (m2) {
return { isItem: true, state: 'pending', text: m2[1] };
}
return { isItem: false };
}
function formatProgressLine(state, text) {
let marker = '[ ]';
if (state === 'completed') marker = '[x]';
else if (state === 'in_progress') marker = '[~]';
return `- ${marker} ${text}`;
}
function normalizeStateFilter(val) {
const v = String(val || '').toLowerCase().trim();
if (['todo', 'to-do', 'pending', 'not_started', 'not-started', 'open'].includes(v)) return 'pending';
if (['in_progress', 'in-progress', 'doing', 'wip'].includes(v)) return 'in_progress';
if (['done', 'completed', 'complete', 'closed'].includes(v)) return 'completed';
if (['archived', 'archive'].includes(v)) return 'archived';
return null;
}
function validateTaskId(id) {
return typeof id === 'string' && /^[a-z0-9]{8}$/.test(id);
}
function normalizeStatus(s) {
const v = String(s || '').toLowerCase().trim();
if (v === 'pending' || v === 'in_progress' || v === 'completed' || v === 'archived') return v;
if (['todo', 'to-do', 'open', 'not-started', 'not_started'].includes(v)) return 'pending';
if (['doing', 'wip', 'in-progress'].includes(v)) return 'in_progress';
if (['done', 'complete', 'closed'].includes(v)) return 'completed';
if (['archive', 'archived'].includes(v)) return 'archived';
return 'pending';
}
// Accept tasks as array, single object, or JSON string of either; returns { tasks, invalid }
function validateAndNormalizeTasks(input) {
let list = input;
if (typeof input === 'string') {
const s = input.trim();
try {
const parsed = JSON.parse(s);
list = Array.isArray(parsed) ? parsed : (parsed && typeof parsed === 'object' ? [parsed] : []);
} catch {
list = [];
}
}
// If a single object was provided directly, wrap it into an array
if (!Array.isArray(list)) {
if (list && typeof list === 'object') list = [list];
else list = [];
}
const tasks = [];
const invalid = [];
for (const t of list) {
if (!t || typeof t !== 'object') { invalid.push({ item: t, reason: 'not_an_object' }); continue; }
const task_id = String(t.task_id || '').trim();
const task_info = String(t.task_info || '').trim();
const parent_id = t.parent_id == null ? null : String(t.parent_id).trim();
const extra_note = t.extra_note == null ? null : String(t.extra_note);
const status = normalizeStatus(t.status || 'pending');
if (!validateTaskId(task_id)) { invalid.push({ item: t, reason: 'invalid_task_id_format', hint: 'Use exactly 8 lowercase a-z0-9, e.g., abcd1234' }); continue; }
if (!task_info) { invalid.push({ item: t, reason: 'missing_task_info' }); continue; }
if (parent_id && !validateTaskId(parent_id)) { invalid.push({ item: t, reason: 'invalid_parent_id_format', hint: 'Use exactly 8 lowercase a-z0-9' }); continue; }
tasks.push({ task_id, task_info, parent_id, status, extra_note });
}
return { tasks, invalid };
}
function filterProgressContent(md, only) {
const list = Array.isArray(only) ? only : (only == null ? [] : [only]);
const wanted = new Set(list.map(normalizeStateFilter).filter(Boolean));
if (!wanted.size) return String(md ?? '');
const out = [];
const lines = String(md || '').split(/\r?\n/);
for (const line of lines) {
const p = parseProgressLine(line);
if (!p.isItem) continue;
if (wanted.has(p.state)) out.push(formatProgressLine(p.state, p.text));
}
return out.join('\n') + (out.length ? '\n' : '');
}
// ---------- Unified Diff Patch (git-style) helper ----------
// Minimal unified diff applier for single-file patches.
// Supports headers (diff --git, index, ---/+++), and @@ hunks with ' ', '+', '-' lines.
// Strictly validates that each hunk's header counts match the number of lines provided:
// - oldCount === (#context ' ' + #deletes '-')
// - newCount === (#context ' ' + #adds '+')
// Also enforces the "-- " rule for deleting markdown bullets that literally begin with "- ":
// deletion lines must start with "-- " to include the literal dash in the deleted content.
function applyUnifiedDiff(oldText, diffText) {
const oldLines = String(oldText ?? '').split(/\n/);
const diffLines = String(diffText ?? '').split(/\n/);
const noCR = (s) => String(s ?? '').replace(/\r$/, '');
// Collect hunks
const hunks = [];
let i = 0;
while (i < diffLines.length) {
const line = diffLines[i];
// Skip file headers and metadata
if (/^(diff --git |index |--- |\+\+\+ )/.test(line)) {
i++;
continue;
}
const m = line.match(/^@@\s+-(\d+)(?:,(\d+))?\s+\+(\d+)(?:,(\d+))?\s+@@.*$/);
if (m) {
const oldStart = parseInt(m[1], 10);
const oldCount = m[2] ? parseInt(m[2], 10) : 1;
const newStart = parseInt(m[3], 10);
const newCount = m[4] ? parseInt(m[4], 10) : 1;
i++;
const hunkLines = [];
while (i < diffLines.length && !/^@@/.test(diffLines[i])) {
const hl = diffLines[i];
if (/^(diff --git |index |--- |\+\+\+ )/.test(hl)) break;
// Ignore end-of-file marker lines
if (/^\\ No newline at end of file/.test(hl)) { i++; continue; }
// Only accept proper hunk lines starting with ' ', '+', or '-'.
// Ignore other metadata and blank lines.
if (/^[ \+\-]/.test(hl)) {
hunkLines.push(hl);
}
i++;
}
// Validate hunk counts strictly before applying
let ctxCount = 0, addCount = 0, delCount = 0;
for (const hl of hunkLines) {
if (!hl || typeof hl !== 'string') continue;
const p = hl[0];
if (p === ' ') ctxCount++;
else if (p === '+') addCount++;
else if (p === '-') delCount++;
}
const oldSpan = ctxCount + delCount;
const newSpan = ctxCount + addCount;
if (oldSpan !== oldCount || newSpan !== newCount) {
throw new Error(
`Patch hunk header/count mismatch at @@ -${oldStart},${oldCount} +${newStart},${newCount} @@: ` +
`have context=${ctxCount}, deletes=${delCount}, adds=${addCount}`
);
}
hunks.push({ oldStart, oldCount, newStart, newCount, lines: hunkLines });
continue;
}
// Otherwise ignore
i++;
}
if (!hunks.length) {
throw new Error('No hunks found in unified diff');
}
// Apply hunks in order
const out = [];
let origIndex = 0; // 0-based index into oldLines
// Helper: find where to apply hunk based on its context (' ' and '-') lines
function findHunkAnchor(startAt, hunk) {
const expected = [];
for (const hl of hunk.lines) {
const p = hl[0];
if (p === ' ' || p === '-') expected.push(noCR(hl.slice(1)));
}
if (!expected.length) return Math.max(0, hunk.oldStart - 1); // no anchor; fall back to header
// Search from current position forward
for (let pos = Math.max(0, startAt); pos + expected.length <= oldLines.length; pos++) {
let ok = true;
for (let k = 0; k < expected.length; k++) {
if (noCR(oldLines[pos + k]) !== expected[k]) { ok = false; break; }
}
if (ok) return pos;
}
// As a fallback, search entire file
for (let pos = 0; pos + expected.length <= oldLines.length; pos++) {
let ok = true;
for (let k = 0; k < expected.length; k++) {
if (noCR(oldLines[pos + k]) !== expected[k]) { ok = false; break; }
}
if (ok) return pos;
}
// If not found, return header-based index so we still error with a clear message
return Math.max(0, hunk.oldStart - 1);
}
for (const h of hunks) {
const anchor = findHunkAnchor(origIndex, h);
while (origIndex < anchor) {
out.push(noCR(oldLines[origIndex]));
origIndex++;
}
// Apply hunk at anchor
for (const hl of h.lines) {
const prefix = hl[0];
const text = hl.slice(1);
if (prefix === ' ') {
const got = noCR(oldLines[origIndex]);
if (got !== noCR(text)) {
throw new Error(`Patch context mismatch: expected "${text}" got "${got}"`);
}
out.push(got);
origIndex++;
} else if (prefix === '-') {
const got = noCR(oldLines[origIndex]);
const want = noCR(text);
if (got !== want) {
// Enforce the special rule for markdown bullets that begin with "- ".
// If the target line literally starts with "- " but the diff line omitted the
// extra dash (i.e., diff line started with "- " instead of "-- "), instruct the caller.
if (got.startsWith('- ') && (' ' + got.slice(2) === want || got.slice(1) === want)) {
throw new Error(
`Patch delete mismatch: deleting a markdown bullet must use "-- " (delete marker + literal dash). ` +
`Provided line "${text}" does not include the literal dash; expected "-${text}"`
);
}
throw new Error(`Patch delete mismatch: expected "${text}" got "${got}"`);
} else {
origIndex++;
}
} else if (prefix === '+') {
out.push(noCR(text));
} else {
throw new Error('Invalid hunk line in patch');
}
}
}
while (origIndex < oldLines.length) {
out.push(noCR(oldLines[origIndex]));
origIndex++;
}
return out.join('\n');
}
function normalizeTaskText(s) {
return String(s || '').trim().toLowerCase();
}
function extractExistingTasks(mdContent) {
const set = new Set();
const lines = String(mdContent || '').split(/\r?\n/);
for (const line of lines) {
const p = parseProgressLine(line);
if (p.isItem && p.text) set.add(normalizeTaskText(p.text));
}
return set;
}
function defaultAgentMd(projectName) {
return `# AGENTS.md\n\n- Project: ${projectName}\n- Purpose: Instructions for agents (style, best practices, personality)\n\nGuidance:\n- Keep responses concise, clear, and actionable.\n- Prefer safe defaults; avoid destructive actions.\n- Explain rationale briefly when ambiguity exists.\n`;
}
function defaultProgressMd() {
return `# progress.md\n\n- [ ] Initial setup\n- [ ] Define tasks\n- [ ] Implement features\n- [ ] Review and refine\n`;
}
// ---------- Agent MD Examples (from example_agent_md.json) ----------
const EXAMPLES_JSON_PATH = path.resolve(__dirname, 'example_agent_md.json');
async function loadAgentExamplesJson() {
try {
const raw = await fs.promises.readFile(EXAMPLES_JSON_PATH, 'utf8');
const parsed = JSON.parse(raw);
const theArt = parsed.the_art_of_writing_agents_md || parsed["the_art_of_writing_agents_md"] || '';
const examples = Array.isArray(parsed.examples) ? parsed.examples : [];
return { theArt, examples, rawParsed: parsed };
} catch (err) {
return { theArt: '', examples: [], rawParsed: null };
}
}
function normalizeIncludeList(include) {
if (include == null) return [];
if (Array.isArray(include)) return include.map(String).map(s => s.trim()).filter(Boolean);
// Accept JSON list passed as string (e.g., "[\"a\",\"b\"]")
if (typeof include === 'string') {
const s = include.trim();
if (s.startsWith('[')) {
try {
const parsed = JSON.parse(s);
if (Array.isArray(parsed)) {
return parsed.map(String).map(v => v.trim()).filter(Boolean);
}
} catch {}
}
return [s].filter(Boolean);
}
return [];
}
function filterExamplesByInclude(examples, includeList) {
if (!includeList.length) return [];
const needles = includeList.map(s => s.toLowerCase());
return examples.filter(ex => {
const u = String(ex.usecase || '').toLowerCase();
const t = String(ex.title || '').toLowerCase();
return needles.some(n => u.includes(n) || t.includes(n));
});
}
// Render tasks to nested Markdown for readability
function renderTasksMarkdown(rows) {
const marker = (st) => {
if (st === 'completed') return '[x]';
if (st === 'in_progress') return '[~]';
if (st === 'archived') return '[A]';
return '[ ]';
};
// Build node map
const nodes = new Map();
for (const r of rows) {
nodes.set(r.task_id, { task: r, children: [] });
}
const roots = [];
for (const r of rows) {
const node = nodes.get(r.task_id);
const pid = r.parent_id || null;
if (pid && nodes.has(pid)) nodes.get(pid).children.push(node); else roots.push(node);
}
const lines = [];
function walk(node, depth) {
const t = node.task;
const indent = ' '.repeat(depth);
lines.push(`${indent}- ${marker(t.status)} ${t.task_info} (${t.task_id})`);
for (const ch of node.children) walk(ch, depth + 1);
}
for (const n of roots) walk(n, 0);
return lines.join('\n');
}
// Build a fresh MCP server instance for each request (stateless mode)
function buildMcpServer(userId, userName) {
const ops = userOps(userId, userName);
const server = new Server(
{ name: 'mcp-http-agent-md', version: '0.1.0' },
{ capabilities: { tools: {} } }
);
// Describe available tools
server.setRequestHandler(ListToolsRequestSchema, async () => {
const agentsReminder = 'Reminder: Proactively update AGENTS.md to capture new project knowledge and evolving user preferences. Call get_agents_md_best_practices_and_examples to learn more.';
const { examples } = await loadAgentExamplesJson();
const available = examples.map(ex => `${ex.usecase || ''}${ex.title ? ` - ${ex.title}` : ''}`.trim()).filter(Boolean);
const examplesToolDesc = [
'Best practices and examples for AGENTS.md from example_agent_md.json.',
available.length ? `Available examples: ${available.join('; ')}` : 'No examples found.',
"Use 'include' to control examples: include='all' returns all examples; include can also be a string or a JSON/array of filters matching usecase/title.",
"Default returns only 'the_art_of_writing_agents_md' (best-practices)."
].join(' ') + ' ' + agentsReminder;
const meta = getProviderMeta();
const hasTools = Array.isArray(meta.tools) && meta.tools.length > 0;
const capLabels = {
grounding: 'grounding (search)',
crawling: 'crawling (web fetch)',
code_execution: 'code_execution (run code)',
};
const shown = hasTools ? meta.tools.filter(t => capLabels[t]).map(t => capLabels[t]) : [];
const toolsSentence = hasTools
? `Available subagent tools: ${shown.join(', ')}. Provide 'tool' as "all" or a subset of the above.`
: `This subagent is configured with no tools; the 'tool' argument is ignored.`;
// For provider 'mcp', surface MCP server tool short descriptions from subagent_config.json
let mcpToolsHint = '';
if (String(meta.key) === 'mcp') {
try {
const cfgPath = path.join(process.cwd(), 'subagent_config.json');
const raw = fs.readFileSync(cfgPath, 'utf-8');
const json = JSON.parse(raw);
const servers = json?.mcpServers || {};
const parts = [];
for (const [name, cfg] of Object.entries(servers)) {
const desc = String(cfg?.short_descriptions || '').trim();
if (desc) {
parts.push(`${name} (${desc})`);
} else {
// Warn in console so users can improve discoverability next time
try { console.warn(`[mcp] short_descriptions missing for server '${name}' in subagent_config.json. Consider adding a concise hint (e.g., \"${name}(one‑line purpose)\").`); } catch {}
parts.push(String(name));
}
}
if (parts.length) mcpToolsHint = ` MCP tools (listed as tool_name (short description)): ${parts.join(', ')}. Provide 'tool' as "all" or a subset of the above.`;
} catch {}
}
const readProjectFileTool = {
name: 'read_project_file',
description: 'Read a specific chunk of an uploaded project document. Provide file_id from list_file plus either (a) byte offset start and length (defaults: start=0, length=10000), or (b) pages (e.g., "1-3,5") for PDFs with processed status true. Do NOT supply start/length together with pages. Returns UTF-8 text (PDFs are parsed to text).',
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
file_id: { type: 'string' },
start: { type: 'number', minimum: 0, description: 'Optional byte offset to begin reading. Defaults to 0.' },
length: { type: 'number', minimum: 1, description: 'Optional byte length to read. Defaults to 10000. Max 100000.' },
pages: { type: 'string', description: 'Optional page selection for PDFs (e.g., "1-3,5"). Only allowed when PDF with processed=true.' }
},
required: ['project_id','file_id']
}
};
const result = { tools: [
{
name: 'list_projects',
description: 'List accessible projects with id, name, owner_id, and permission.',
inputSchema: { type: 'object', properties: {} }
},
{
name: 'list_file',
description: 'List uploaded documents for a project. Returns each file\'s original filename, description, file_id, and PDF processing info (processed, total_pages). When page numbers are available (processed=true), the automatically generated descriptions and outlines include page markers using the format [p. N] or [pp. A–B]; otherwise page numbers are omitted.',
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' }
},
required: ['project_id']
}
},
{
name: 'scratchpad_subagent',
description: `Start a subagent (provider: ${meta.key}) to work on a scratchpad task. Required: project_id, scratchpad_id, task_id, prompt. Optional: sys_prompt, tool (array or "all"), file_path (absolute path) or file_id (from list_file) to attach a document. ${toolsSentence}${mcpToolsHint} Optional 'pages' (e.g., "1-3,5,9"): only allowed when the PDF is processed=true in list_file (OCRed or native-pdf-capable provider). When provided, the server assembles either a Markdown excerpt (from OCR pages) or a new PDF (subset of pages) and attaches it. If processed=false, the call fails with pages_not_supported_unprocessed_pdf. The server auto-appends the scratchpad's common_memory to the prompt when present. The subagent appends its answer to the task's scratchpad and logs any sources/code it used into comments. Note that the subagent's context is isolated: it can ONLY see common_memory without other project context; update common_memory if needed.`,
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
scratchpad_id: { type: 'string' },
task_id: { type: 'string' },
prompt: { type: 'string' },
sys_prompt: { type: 'string' , description: 'Default: You are a general problem-solving agent with access to tool_list. Keep answers concise and accurate.'},
tool: { oneOf: [ { type: 'string' }, { type: 'array', items: { type: 'string' } } ] },
file_path: { type: 'string', description: 'Absolute path to a local file to attach (bypasses file_id lookup).' },
file_id: { type: 'string', description: 'Project file_id (see list_file). Server resolves to disk path securely.' },
pages: { type: 'string', description: 'Optional page selection for PDFs (e.g., "1-3,5,9"). Only allowed when list_file marks the PDF as processed=true.' }
},
required: ['project_id','scratchpad_id','task_id','prompt']
}
},
{
name: 'generate_task_ids',
description: 'Generate N random 8-character task IDs (lowercase a-z0-9) not used by this user across any project.',
inputSchema: {
type: 'object',
properties: {
count: { type: 'number', minimum: 1, maximum: 200, default: 5 }
}
}
},
{
name: 'progress_add',
description: 'Add one or more structured project-level tasks. Provide an array of task objects. Each requires 8-char task_id (lowercase a-z0-9), task_info; optional parent_id (root task_id), status (pending|in_progress|completed|archived), extra_note. Optionally include a commit message via comment.' + agentsReminder,
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
item: {
type: 'array', items: {
type: 'object',
properties: {
task_id: { type: 'string', minLength: 8, maxLength: 8 },
task_info: { type: 'string' },
parent_id: { type: 'string', minLength: 8, maxLength: 8, description: 'Root task_id this task belongs under; enables arbitrary-depth nesting.' },
status: { type: 'string', enum: ['pending','in_progress','completed','archived'] },
extra_note: { type: 'string' }
},
required: ['task_id','task_info']
}
},
comment: { type: 'string' }
},
required: ['project_id', 'item']
}
},
{
name: 'progress_set_new_state',
description: 'Update project-level tasks by task_id (8-char) or by matching task_info substring. Provide an array of match terms (ids or substrings). Can set state (pending|in_progress|completed|archived) and/or update fields task_info, parent_id, extra_note. Archiving or completing cascades to all children recursively. Lock rules: when a task or any ancestor is completed/archived, no edits are allowed except unlocking the task itself to pending/in_progress, and only if no ancestor is locked. Optionally include a commit message via comment.' + agentsReminder,
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
match: { type: 'array', items: { type: 'string' } },
state: { type: 'string', enum: ['pending', 'in_progress', 'completed', 'archived'] },
task_info: { type: 'string' },
parent_id: { type: 'string', minLength: 8, maxLength: 8 },
extra_note: { type: 'string' },
comment: { type: 'string' }
},
required: ['project_id', 'match']
}
},
{
name: 'init_project',
description: 'Create or initialize a project with optional agent content and structured tasks. Task IDs must be exactly 8 lowercase a-z0-9 (e.g., abcd1234). Use parent_id to reference the root task for nesting. ' + agentsReminder,
inputSchema: {
type: 'object',
properties: {
name: { type: 'string' },
agent: { type: 'string' },
progress: { type: 'array', items: {
type: 'object',
properties: {
task_id: { type: 'string', minLength: 8, maxLength: 8 },
task_info: { type: 'string' },
parent_id: { type: 'string', minLength: 8, maxLength: 8, description: 'Root task_id for this task; enables nested subtasks' },
status: { type: 'string', enum: ['pending','in_progress','completed'] },
extra_note: { type: 'string' }
},
required: ['task_id','task_info']
} }
},
required: ['name']
}
},
{
name: 'delete_project',
description: 'Delete a project by id (owner only).',
inputSchema: {
type: 'object',
properties: { project_id: { type: 'string' } },
required: ['project_id']
}
},
{
name: 'rename_project',
description: 'Rename a project by id. Optionally include a commit message via comment. ' + agentsReminder,
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
newName: { type: 'string' },
comment: { type: 'string' }
},
required: ['project_id', 'newName']
}
},
{
name: 'read_agent',
description: 'Read AGENTS.md for a project. Optional: prepend line numbers with N|. ' + agentsReminder,
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
lineNumbers: { type: 'boolean', description: 'If true, prepend line numbers as N|line' }
},
required: ['project_id']
}
},
{
name: 'write_agent',
description: 'Write AGENTS.md (mode=full|patch|diff). For patch/diff, provide a unified diff string: use hunk headers like @@ -l,c +l,c @@ and lines prefixed with space (context), + (add), - (delete). If deleting a markdown list item that starts with "- ", the diff line must start with "-- " (delete marker + literal dash). Lines must preserve leading spaces in context. Optionally include a commit message via comment.' + agentsReminder,
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
content: { type: 'string', description: 'Full file contents when mode=full (default)' },
patch: { type: 'string', description: 'Unified diff (git-style) when mode=patch/diff' },
mode: { type: 'string', enum: ['full', 'patch', 'diff'], description: 'Edit mode; defaults to full' },
comment: { type: 'string' }
},
required: ['project_id']
}
},
{
name: 'list_project_logs',
description: 'List commit logs (hash, message, created_at) for a project. Requires project_id.',
inputSchema: { type: 'object', properties: { project_id: { type: 'string' } }, required: ['project_id'] }
},
{
name: 'revert_project',
description: 'Revert a project to a previous version by hash. Removes newer hashes from history (no branches). Requires project_id and hash.',
inputSchema: { type: 'object', properties: { project_id: { type: 'string' }, hash: { type: 'string' } }, required: ['project_id', 'hash'] }
},
{
name: 'read_progress',
description: 'Read structured project-level tasks as JSON. Optionally filter by status (pending, in_progress, completed) or synonyms. ' + agentsReminder,
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
only: {
oneOf: [
{ type: 'string', enum: ['todo', 'to-do', 'pending', 'in_progress', 'in-progress', 'done', 'completed'] },
{ type: 'array', items: { type: 'string' } }
]
}
},
required: ['project_id']
}
},
{
name: 'get_agents_md_best_practices_and_examples',
description: examplesToolDesc,
inputSchema: {
type: 'object',
properties: {
include: { oneOf: [ { type: 'string' }, { type: 'array', items: { type: 'string' } } ] }
}
}
},
{
name: 'scratchpad_initialize',
description: 'Start a temporary scratchpad for a one-off task that doesn\'t require documentation in agents.md/progress.md or won\'t need future reference by other agents—like side quests, experiments, or quick calculations outside the main project scope and shouldn\'t belong in the main project tracking. Use this to split the immediate task into manageable (up to 6) small steps (status: open|complete) and keep lightweight notes. The server generates and returns a unique scratchpad_id; use (project name, scratchpad_id) with review/update/append tools. Returns the full scratchpad (tasks + common_memory). If you want to store something non-volatile and is project-level, please edit agents.md or write into the extra_node entry of a task in progress.md.',
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string', description: 'Project id' },
tasks: {
type: 'array',
maxItems: 6,
items: {
type: 'object',
properties: {
task_id: { type: 'string' },
status: { type: 'string', enum: ['open','complete'] },
task_info: { type: 'string' },
scratchpad: { type: 'string' },
comments: { type: 'string' }
},
required: ['task_id','task_info']
}
}
},
required: ['project_id','tasks']
}
},
{
name: 'review_scratchpad',
description: 'Read‑only view of a scratchpad for a one‑off task. Provide (project_id, scratchpad_id). By default returns tasks (max 6) and common_memory. Optionally control output with IncludeCM (boolean) and IncludeTk (array of task_id or task_info needles). If neither is provided, outputs everything; otherwise includes only requested fields and filters tasks.',
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
scratchpad_id: { type: 'string' },
IncludeCM: { type: 'boolean', description: 'When true, include common_memory in the response. If omitted and IncludeTk is set, common_memory is omitted.' },
IncludeTk: {
type: 'array',
items: { type: 'string' },
description: 'Array of task_id values or task_info needles to include. Matches task_id (case-insensitive) or task_info substring (case-insensitive). If omitted, no tasks are returned unless IncludeCM and IncludeTk are both omitted.'
}
},
required: ['project_id','scratchpad_id']
}
},
{
name: 'scratchpad_update_task',
description: 'Update existing scratchpad tasks by task_id to reflect progress on a temporary problem. You can change status (open|complete), task_info, scratchpad (quick notes), and comments. If you need a different set of tasks, create a new scratchpad and use its scratchpad_id. Returns the updated scratchpad.',
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
scratchpad_id: { type: 'string' },
updates: {
type: 'array',
minItems: 1,
items: {
type: 'object',
properties: {
task_id: { type: 'string' },
status: { type: 'string', enum: ['open','complete'] },
task_info: { type: 'string' },
scratchpad: { type: 'string' },
comments: { type: 'string' }
},
required: ['task_id']
}
}
},
required: ['project_id','scratchpad_id','updates']
}
},
{
name: 'scratchpad_append_common_memory',
description: 'Append notes to the scratchpad\'s shared common_memory (append‑only). Use this to log core thinking steps, findings, and conclusions for a one‑off task without editing progress.md. Accepts a string or array of strings and returns the updated scratchpad. If you want to store something non-volatile, please edit agents.md or write into the extra_node entry of a task in progress.md. ',
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
scratchpad_id: { type: 'string' },
append: { oneOf: [ { type: 'string' }, { type: 'array', items: { type: 'string' } } ] }
},
required: ['project_id','scratchpad_id','append']
}
},
{
name: 'scratchpad_subagent_status',
description: 'Check subagent run status by run_id for a project. If status is success or failure, return immediately. If pending/in_progress, poll up to 5 times at 5s intervals until it changes; otherwise return the latest status.',
inputSchema: {
type: 'object',
properties: {
project_id: { type: 'string' },
run_id: { type: 'string' }
},
required: ['project_id','run_id']
}
}
]};
// Hide external-AI tools when USE_EXTERNAL_AI=false
const externalAi = String(process.env.USE_EXTERNAL_AI || '').toLowerCase() !== 'false' ? true : false;
if (!externalAi) {
result.tools = result.tools.filter(t => t.name !== 'scratchpad_subagent' && t.name !== 'scratchpad_subagent_status');
result.tools.push(readProjectFileTool);
}
return result;
});
// Tool invocation handler
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
async function okText(text) {
return { content: [{ type: 'text', text }] };
}
switch (name) {
case 'list_projects': {
const rows = await ops.listProjects();
const projects = rows.map(r => ({ id: r.id, name: r.name, owner_id: r.owner_id, permission: r.permission, read_only: r.permission === 'ro' }));
return okText(JSON.stringify({ projects }));
}
case 'list_file': {
const { project_id } = args || {};
try {
const acc = await dbResolveProjectAccess(userId, String(project_id || ''));
if (!acc) {
return okText(JSON.stringify({ error: 'project_not_found', message: 'project not found' }));
}
const rows = await dbListProjectFiles(acc.owner_id, acc.project_id);
const baseDir = path.join(getDataDir(), acc.project_id);
const providerMeta = getProviderMeta();
const canNativePdfPages = providerMeta?.key === 'google' || providerMeta?.key === 'openai';
async function getPdfPagesCount(fileId) {
const p = path.join(baseDir, String(fileId));
try {
const buf = await fsp.readFile(p);
if (pdfParse) {
const parsed = await pdfParse(buf);
if (typeof parsed?.numpages === 'number' && parsed.numpages > 0) return parsed.numpages;
}
} catch {}
return null;
}
const files = [];
for (const row of rows) {
const isPdf = String(row.file_type || '').toLowerCase() === 'application/pdf';
let processed = false;
let total_pages = 'unknown';
let desc = row.description || null;
if (isPdf) {
const sidecar = path.join(baseDir, `${row.file_id}.ocr.json`);
let sidecarPages = null;
try {
const raw = await fsp.readFile(sidecar, 'utf-8');
const j = JSON.parse(raw);
if (Array.isArray(j?.pages)) sidecarPages = j.pages.length;
} catch {}
if (sidecarPages != null) {
processed = true;
total_pages = sidecarPages;
} else if (canNativePdfPages) {
const n = await getPdfPagesCount(row.file_id);
if (n != null) {
processed = true;
total_pages = n;
}
}
const pagesLabel = processed && typeof total_pages === 'number' ? `Pages: 1-${total_pages}` : 'Pages: unknown';
desc = (desc && desc.trim()) ? `${desc} (${pagesLabel})` : pagesLabel;
}
files.push({
file_id: row.file_id,
filename: row.original_name,
description: desc,
processed: isPdf ? processed : undefined,
total_pages: isPdf ? total_pages : undefined,
});
}
return okText(JSON.stringify({ files }));
} catch (err) {
const msg = String(err?.message || err || 'list files failed');
return okText(JSON.stringify({ error: 'list_files_failed', message: msg }));
}
}
case 'read_project_file': {
const { project_id, file_id, start, length, pages } = args || {};
const pid = String(project_id || '').trim();
const fid = String(file_id || '').trim();
if (!pid) {
return okText(JSON.stringify({ error: 'project_id_required', message: 'project_id is required' }));
}
if (!fid) {
return okText(JSON.stringify({ error: 'file_id_required', message: 'file_id is required' }));
}
if (!/^[a-f0-9]{16}$/i.test(fid)) {
return okText(JSON.stringify({ error: 'invalid_file_id', message: 'file_id must be 16-character hex string' }));
}
try {
const acc = await dbResolveProjectAccess(userId, pid);
if (!acc) {
return okText(JSON.stringify({ error: 'project_not_found', message: 'project not found' }));
}
if (acc.permission === 'ro') {
return okText(JSON.stringify({ error: 'read_only_project', message: 'You have read-only access to this project.' }));
}
const rows = await dbListProjectFiles(acc.owner_id, acc.project_id);
const meta = rows.find(r => String(r.file_id) === fid);
if (!meta) {
return okText(JSON.stringify({ error: 'file_not_found', message: 'file_id not found for this project' }));
}
const baseDir = path.join(getDataDir(), acc.project_id);
const filePath = path.join(baseDir, fid);
const rel = path.relative(baseDir, filePath);
if (rel.startsWith('..')) {
return okText(JSON.stringify({ error: 'invalid_path', message: 'Invalid file location' }));
}
const stats = await fsp.stat(filePath);
const totalBytes = stats.size;
const DEFAULT_LENGTH = 10_000;
const MAX_LENGTH = 100_000;
const rawStart = Number(start);
const rawLength = Number(length);
const safeStart = Number.isFinite(rawStart) && rawStart >= 0 ? Math.floor(rawStart) : 0;
let safeLength = Number.isFinite(rawLength) && rawLength > 0 ? Math.floor(rawLength) : DEFAULT_LENGTH;
if (safeLength > MAX_LENGTH) safeLength = MAX_LENGTH;
const fileType = String(meta.file_type || '').toLowerCase();
const fileName = String(meta.original_name || '');
const isPdf = fileType.includes('pdf') || /\.pdf$/i.test(fileName);
// Validate mutually exclusive paging vs byte ranges
const hasPages = typeof pages === 'string' && pages.trim().length > 0;
const hasOffsets = (typeof start !== 'undefined') || (typeof length !== 'undefined');