@stellar_ai/mcp_fossil_scm 0.1.2 → 0.1.3

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,9 +1,30 @@
1
1
  import { spawn } from 'node:child_process';
2
- import { mkdir } from 'node:fs/promises';
2
+ import { statSync } from 'node:fs';
3
3
  import path from 'node:path';
4
- import { AUTO_SETTINGS, DEFAULT_TIMEOUT_MS, FOSSIL_BIN, MAX_CAPTURE_BYTES, MAX_OUTPUT_CHARS, REPOS_DIR_NAME, getDefaultCwd, } from '../config.js';
4
+ import { DEFAULT_TIMEOUT_MS, FOSSIL_BIN, MAX_CAPTURE_BYTES, MAX_OUTPUT_CHARS, getDefaultWorkspace, } from '../config.js';
5
5
  /** How much partial output is kept when a command times out. */
6
6
  const PARTIAL_OUTPUT_CHARS = 4_000;
7
+ /** True when `dir` exists and is a directory. */
8
+ function isDirectory(dir) {
9
+ try {
10
+ return statSync(dir).isDirectory();
11
+ }
12
+ catch {
13
+ return false;
14
+ }
15
+ }
16
+ /**
17
+ * Buffers `chunk` within the remaining allowance of MAX_CAPTURE_BYTES and
18
+ * returns how many bytes were kept, so the cap is measured in bytes.
19
+ */
20
+ function keepChunk(chunk, captured, target) {
21
+ const remaining = MAX_CAPTURE_BYTES - captured;
22
+ if (remaining <= 0)
23
+ return 0;
24
+ const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk;
25
+ target.push(slice);
26
+ return slice.length;
27
+ }
7
28
  /**
8
29
  * Quotes a string so it survives copy/paste into a POSIX or Windows shell.
9
30
  * Only used for error messages, never for building the argument vector.
@@ -34,9 +55,12 @@ export function truncateOutput(text, limit = MAX_OUTPUT_CHARS) {
34
55
  text.slice(text.length - tailLength),
35
56
  ].join('');
36
57
  }
37
- /** Resolves the working directory used for a command. */
38
- export function resolveWorkspace(cwd) {
39
- const candidate = cwd?.trim() || getDefaultCwd();
58
+ /**
59
+ * Resolves the workspace a command runs in: the explicit value, else the
60
+ * configured default, else the process working directory.
61
+ */
62
+ export function resolveWorkspace(workspace) {
63
+ const candidate = workspace?.trim() || getDefaultWorkspace();
40
64
  return candidate ? path.resolve(candidate) : process.cwd();
41
65
  }
42
66
  /**
@@ -44,14 +68,14 @@ export function resolveWorkspace(cwd) {
44
68
  * can never hang the server), enforces a timeout and never throws.
45
69
  */
46
70
  export function runFossil(args, options = {}) {
47
- const cwd = resolveWorkspace(options.cwd);
71
+ const workspace = resolveWorkspace(options.workspace);
48
72
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
49
73
  const startedAt = Date.now();
50
74
  return new Promise((resolve) => {
51
75
  let child;
52
76
  try {
53
77
  child = spawn(FOSSIL_BIN, args, {
54
- cwd,
78
+ cwd: workspace,
55
79
  env: options.env ? { ...process.env, ...options.env } : process.env,
56
80
  stdio: ['pipe', 'pipe', 'pipe'],
57
81
  windowsHide: true,
@@ -60,7 +84,7 @@ export function runFossil(args, options = {}) {
60
84
  catch (error) {
61
85
  resolve({
62
86
  argv: args,
63
- cwd,
87
+ workspace,
64
88
  code: null,
65
89
  signal: null,
66
90
  stdout: '',
@@ -69,18 +93,20 @@ export function runFossil(args, options = {}) {
69
93
  timeoutMs,
70
94
  spawnFailed: true,
71
95
  spawnError: error instanceof Error ? error.message : String(error),
96
+ workspaceMissing: !isDirectory(workspace),
72
97
  ok: false,
73
98
  durationMs: Date.now() - startedAt,
74
99
  });
75
100
  return;
76
101
  }
77
- let stdout = '';
78
- let stderr = '';
102
+ const stdoutChunks = [];
103
+ const stderrChunks = [];
79
104
  let stdoutBytes = 0;
80
105
  let stderrBytes = 0;
81
106
  let timedOut = false;
82
107
  let spawnFailed = false;
83
108
  let spawnError;
109
+ let workspaceMissing = false;
84
110
  let settled = false;
85
111
  let hardKillTimer;
86
112
  const finish = (code, signal) => {
@@ -91,15 +117,16 @@ export function runFossil(args, options = {}) {
91
117
  clearTimeout(hardKillTimer);
92
118
  resolve({
93
119
  argv: args,
94
- cwd,
120
+ workspace,
95
121
  code,
96
122
  signal,
97
- stdout,
98
- stderr,
123
+ stdout: Buffer.concat(stdoutChunks).toString('utf8'),
124
+ stderr: Buffer.concat(stderrChunks).toString('utf8'),
99
125
  timedOut,
100
126
  timeoutMs,
101
127
  spawnFailed,
102
128
  spawnError,
129
+ workspaceMissing,
103
130
  ok: !timedOut && !spawnFailed && code === 0,
104
131
  durationMs: Date.now() - startedAt,
105
132
  });
@@ -113,23 +140,23 @@ export function runFossil(args, options = {}) {
113
140
  finish(null, 'SIGKILL');
114
141
  }, 2_000);
115
142
  }, timeoutMs);
116
- child.stdout?.setEncoding('utf8');
117
- child.stderr?.setEncoding('utf8');
118
143
  child.stdout?.on('data', (chunk) => {
119
- if (stdoutBytes >= MAX_CAPTURE_BYTES)
120
- return;
121
- stdoutBytes += chunk.length;
122
- stdout += chunk;
144
+ stdoutBytes += keepChunk(chunk, stdoutBytes, stdoutChunks);
123
145
  });
124
146
  child.stderr?.on('data', (chunk) => {
125
- if (stderrBytes >= MAX_CAPTURE_BYTES)
126
- return;
127
- stderrBytes += chunk.length;
128
- stderr += chunk;
147
+ stderrBytes += keepChunk(chunk, stderrBytes, stderrChunks);
129
148
  });
130
149
  child.on('error', (error) => {
131
150
  spawnFailed = true;
132
- spawnError = error.code === 'ENOENT' ? `'${FOSSIL_BIN}' not found in PATH` : error.message;
151
+ // Node reports the same ENOENT both for a missing executable and for a
152
+ // missing child cwd, so the workspace decides which message is true.
153
+ if (error.code === 'ENOENT' && !isDirectory(workspace)) {
154
+ workspaceMissing = true;
155
+ spawnError = `workspace directory '${workspace}' does not exist`;
156
+ }
157
+ else {
158
+ spawnError = error.code === 'ENOENT' ? `'${FOSSIL_BIN}' not found in PATH` : error.message;
159
+ }
133
160
  finish(null, null);
134
161
  });
135
162
  child.on('close', (code, signal) => finish(code, signal));
@@ -150,14 +177,13 @@ function errorDetails(outcome) {
150
177
  /** Renders a failed/timed-out outcome as a human-readable error block. */
151
178
  export function formatFailure(outcome) {
152
179
  const command = `${FOSSIL_BIN} ${outcome.argv.map(quoteArg).join(' ')}`;
153
- const footer = `COMMAND: ${command}\nCWD: ${outcome.cwd}`;
180
+ const footer = `COMMAND: ${command}\nWORKSPACE: ${outcome.workspace}`;
154
181
  let text;
155
182
  if (outcome.spawnFailed) {
156
- text = [
157
- `ERROR: ${outcome.spawnError ?? 'could not start fossil'}.`,
158
- 'Install Fossil SCM and make sure it is on PATH, or set FOSSIL_BIN to the executable path.',
159
- footer,
160
- ].join('\n');
183
+ const hint = outcome.workspaceMissing
184
+ ? 'Point `workspace` (or --workspace) at a directory that exists and retry.'
185
+ : 'Install Fossil SCM and make sure it is on PATH, or set FOSSIL_BIN to the executable path.';
186
+ text = [`ERROR: ${outcome.spawnError ?? 'could not start fossil'}.`, hint, footer].join('\n');
161
187
  }
162
188
  else if (outcome.timedOut) {
163
189
  const partial = truncateOutput(errorDetails(outcome), PARTIAL_OUTPUT_CHARS);
@@ -202,53 +228,15 @@ export function renderSections(sections) {
202
228
  ...(sections.length > 0 && sections.every((section) => !section.outcome.ok) ? { isError: true } : {}),
203
229
  };
204
230
  }
205
- /** Concatenates several successful reports (e.g. open + auto-configuration). */
206
- export function combineText(parts) {
207
- return parts.filter((part) => Boolean(part && part.trim())).join('\n\n');
208
- }
209
- /**
210
- * Resolves the workspace directory, the repository database path and the
211
- * project name.
212
- *
213
- * Explicit `db_name` values containing a separator (or an absolute path) are
214
- * honored verbatim; bare names land in `<parent>/.fossil_repositories`.
215
- */
216
- export async function resolveRepoPaths(dbName, cwd) {
217
- const workspaceDir = resolveWorkspace(cwd);
218
- const projectName = path.basename(workspaceDir);
219
- const explicitName = dbName?.trim();
220
- if (explicitName && (explicitName.includes('/') || explicitName.includes('\\') || path.isAbsolute(explicitName))) {
221
- return {
222
- workspaceDir,
223
- repoDbPath: path.isAbsolute(explicitName) ? path.normalize(explicitName) : path.resolve(workspaceDir, explicitName),
224
- projectName,
225
- };
226
- }
227
- const reposDir = path.join(path.dirname(workspaceDir), REPOS_DIR_NAME);
228
- await mkdir(reposDir, { recursive: true });
229
- const fileName = explicitName ? (explicitName.endsWith('.fossil') ? explicitName : `${explicitName}.fossil`) : `${projectName}.fossil`;
230
- return { workspaceDir, repoDbPath: path.join(reposDir, fileName), projectName };
231
- }
232
- /** Builds the SQL that applies every {@link AUTO_SETTINGS} entry in one statement batch. */
233
- function buildAutoSettingsSql() {
234
- return AUTO_SETTINGS.map(([name, value]) => `REPLACE INTO config(name,value) VALUES('${escapeSqlLiteral(name)}','${escapeSqlLiteral(value)}');`).join(' ');
235
- }
236
231
  /**
237
- * Applies the standard settings directly through `fossil sql`.
238
- *
239
- * A single fossil invocation replaces the four sequential ones used before,
240
- * which removes three process spawns from every init/open.
241
- *
242
- * @param options.dbPath repository database; omitted when running inside a check-out.
243
- * @param options.cwd directory the command runs in.
232
+ * Resolves a repository database path: absolute paths verbatim, relative ones
233
+ * against the workspace. There is deliberately no default location and no
234
+ * implicit `.fossil` suffix - the caller (the prompt) always states where the
235
+ * repository lives.
244
236
  */
245
- export async function applyAutoSettings(options = {}) {
246
- const args = ['sql'];
247
- if (options.dbPath)
248
- args.push('-R', options.dbPath);
249
- args.push(buildAutoSettingsSql());
250
- const outcome = await runFossil(args, { cwd: options.cwd });
251
- if (outcome.ok)
252
- return [];
253
- return [`Failed to apply automatic settings: ${formatFailure(outcome).content[0].text}`];
237
+ export function resolveRepoPath(repoPath, workspace) {
238
+ const value = repoPath.trim();
239
+ if (!value)
240
+ throw new Error('a repository path is required');
241
+ return path.isAbsolute(value) ? path.normalize(value) : path.resolve(resolveWorkspace(workspace), value);
254
242
  }
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Translation of `.gitignore` rules into the glob patterns Fossil's
3
+ * `ignore-glob` setting understands.
4
+ *
5
+ * Fossil globs are matched by SQLite's GLOB operator against the complete
6
+ * check-out-relative name, so `*` also matches `/`, a matching directory
7
+ * excludes everything below it, and there is no negation, no comment syntax
8
+ * and no `.gitignore`-relative anchoring.
9
+ */
10
+ function trimTrailingSpaces(line) {
11
+ let end = line.length;
12
+ while (end > 0 && line[end - 1] === ' ') {
13
+ let backslashes = 0;
14
+ for (let i = end - 2; i >= 0 && line[i] === '\\'; i -= 1)
15
+ backslashes += 1;
16
+ if (backslashes % 2 === 1) {
17
+ // An escaped space is part of the pattern; the backslash is consumed.
18
+ return `${line.slice(0, end - 2)} ${line.slice(end)}`;
19
+ }
20
+ end -= 1;
21
+ }
22
+ return line.slice(0, end);
23
+ }
24
+ function unescapeGit(line) {
25
+ return line.replace(/\\([\\#!\s])/g, '$1');
26
+ }
27
+ /**
28
+ * Quotes a pattern when the glob list parser would split it. Fossil ends a
29
+ * quoted pattern at the matching quote and has no escape for quotes, so a
30
+ * pattern holding both kinds is returned unchanged and reported by the caller.
31
+ */
32
+ export function quoteGlob(pattern) {
33
+ if (!/[,\s'"]/.test(pattern))
34
+ return pattern;
35
+ if (!pattern.includes("'"))
36
+ return `'${pattern}'`;
37
+ if (!pattern.includes('"'))
38
+ return `"${pattern}"`;
39
+ return pattern;
40
+ }
41
+ /**
42
+ * Converts the text of one `.gitignore` file. `prefix` is the directory the
43
+ * file lives in, relative to the check-out root (`''` for the root file).
44
+ */
45
+ export function convertGitignore(text, options = {}) {
46
+ const prefix = normalizePrefix(options.prefix ?? '');
47
+ const patterns = [];
48
+ const warnings = [];
49
+ let lineCount = 0;
50
+ const push = (pattern) => {
51
+ const quoted = quoteGlob(pattern);
52
+ if (quoted === pattern && /[,\s]/.test(pattern)) {
53
+ warnings.push(`${pattern} contains a comma, space and both quote kinds, so Fossil cannot hold it as one pattern`);
54
+ }
55
+ if (!patterns.includes(quoted))
56
+ patterns.push(quoted);
57
+ };
58
+ for (const rawLine of text.split('\n')) {
59
+ const raw = rawLine.replace(/\r$/, '');
60
+ if (raw.trim() === '')
61
+ continue;
62
+ if (raw.startsWith('#'))
63
+ continue;
64
+ const line = trimTrailingSpaces(raw);
65
+ if (line === '')
66
+ continue;
67
+ lineCount += 1;
68
+ if (line.startsWith('!')) {
69
+ warnings.push(`negation ${line} skipped: ignore-glob has no negation, so the path stays visible`);
70
+ continue;
71
+ }
72
+ let pattern = unescapeGit(line);
73
+ const anchored = pattern.startsWith('/');
74
+ if (anchored)
75
+ pattern = pattern.slice(1);
76
+ if (pattern.endsWith('/'))
77
+ pattern = pattern.slice(0, -1);
78
+ if (pattern === '' || pattern === '.')
79
+ continue;
80
+ if (pattern.includes('**')) {
81
+ const variants = expandDoubleStar(pattern);
82
+ for (const variant of variants) {
83
+ for (const expanded of expandRule(variant, prefix, variant.includes('/')))
84
+ push(expanded);
85
+ }
86
+ warnings.push(variants.length > 1
87
+ ? `\`**\` in ${line} expanded to ${variants.length} patterns`
88
+ : `\`**\` in ${line} treated as \`*\``);
89
+ continue;
90
+ }
91
+ for (const expanded of expandRule(pattern, prefix, pattern.includes('/')))
92
+ push(expanded);
93
+ }
94
+ return { patterns, warnings, lineCount };
95
+ }
96
+ function normalizePrefix(prefix) {
97
+ const trimmed = prefix.replace(/^\.\/+/, '').replace(/\/+$/, '');
98
+ return trimmed === '' || trimmed === '.' ? '' : `${trimmed}/`;
99
+ }
100
+ /**
101
+ * Splits a pattern containing a double-star segment into the equivalent set of
102
+ * plain patterns: a double star matches zero or more directories, so both the
103
+ * zero-directory and the one-or-more-directory forms are emitted.
104
+ */
105
+ function expandDoubleStar(pattern) {
106
+ let variants = [[]];
107
+ for (const segment of pattern.split('/')) {
108
+ if (segment === '**') {
109
+ const next = [];
110
+ for (const parts of variants)
111
+ next.push([...parts], [...parts, '*']);
112
+ variants = next;
113
+ continue;
114
+ }
115
+ variants = variants.map((parts) => [...parts, segment]);
116
+ }
117
+ return variants.map((parts) => parts.join('/')).filter((value) => value !== '' && value !== '/');
118
+ }
119
+ function expandRule(pattern, prefix, anchored) {
120
+ if (anchored)
121
+ return [`${prefix}${pattern}`];
122
+ // A rule without a slash applies at every depth. Fossil matches the whole
123
+ // path and its `*` also covers separators, so a pattern that already starts
124
+ // with a wildcard spans directories on its own; a literal name needs the
125
+ // extra "one or more directories" form.
126
+ const spansDirectories = /^[*?[]/.test(pattern);
127
+ if (spansDirectories)
128
+ return [`${prefix}${pattern}`];
129
+ return prefix === ''
130
+ ? [pattern, `*/${pattern}`]
131
+ : [`${prefix}${pattern}`, `${prefix}*/${pattern}`];
132
+ }
133
+ /** Renders a conversion result as the text of an `ignore-glob` file. */
134
+ export function renderGlobFile(conversion) {
135
+ return conversion.patterns.join('\n') + (conversion.patterns.length > 0 ? '\n' : '');
136
+ }
package/dist/core/sql.js CHANGED
@@ -9,10 +9,12 @@ export async function runSql(sql, options = {}) {
9
9
  const args = ['sql'];
10
10
  if (options.readonly)
11
11
  args.push('--readonly');
12
+ if (options.repository)
13
+ args.push('-R', options.repository);
12
14
  if (options.database)
13
15
  args.push('--no-repository', options.database);
14
16
  args.push('-json', sql);
15
- const outcome = await runFossil(args, { cwd: options.cwd, timeoutMs: options.timeoutMs });
17
+ const outcome = await runFossil(args, { workspace: options.workspace, timeoutMs: options.timeoutMs });
16
18
  if (!outcome.ok)
17
19
  return { ok: false, rows: [], error: formatFailure(outcome).content[0].text };
18
20
  const raw = outcome.stdout.trim();
package/dist/index.js CHANGED
@@ -2,10 +2,13 @@
2
2
  /**
3
3
  * Single entry point. `-c` takes the capability initials written together:
4
4
  *
5
- * fossil-scm -c a # admin only (5) fossil-scm -c v # VCS only (20)
6
- * fossil-scm -c avf # admin + VCS + forum (28) fossil-scm -c w # wiki only (3)
7
- * fossil-scm -c A # everything (38)
5
+ * fossil-scm -c a # admin only
6
+ * fossil-scm -c v # VCS only
7
+ * fossil-scm -c avf # admin + VCS + forum
8
+ * fossil-scm -c A # everything
8
9
  * fossil-scm # FOSSIL_CAPABILITIES, else everything
10
+ *
11
+ * Run with `--help` for the per-capability tool counts.
9
12
  */
10
13
  import { run } from './cli.js';
11
14
  run();
@@ -0,0 +1,167 @@
1
+ import { z } from 'zod';
2
+ const workspaceArg = z
3
+ .string()
4
+ .min(1)
5
+ .optional()
6
+ .describe('Check-out directory to work in. Omit to use the server default workspace.');
7
+ function userMessage(text) {
8
+ return { messages: [{ role: 'user', content: { type: 'text', text } }] };
9
+ }
10
+ function workspaceLine(workspace) {
11
+ return workspace ? `Pass \`workspace: "${workspace}"\` to every tool call.` : 'Keep the default workspace for every tool call.';
12
+ }
13
+ /**
14
+ * Registers the workflow prompts whose capabilities are enabled.
15
+ *
16
+ * Each prompt is a short recipe that spells out which tools to call in which
17
+ * order, so an agent can follow it without rediscovering the tool set.
18
+ */
19
+ export function registerPrompts(server, ids) {
20
+ const has = (id) => ids.includes(id);
21
+ if (has('v')) {
22
+ server.registerPrompt('fossil-review-changes', {
23
+ title: 'Review uncommitted changes',
24
+ description: 'Inspect the working tree, group the edits by intent and propose a commit message without committing.',
25
+ argsSchema: z.object({ workspace: workspaceArg }),
26
+ }, ({ workspace }) => userMessage([
27
+ 'Review the uncommitted work in this Fossil check-out.',
28
+ workspaceLine(workspace),
29
+ '',
30
+ '1. Call `fossil_status` to see the check-out and repository state.',
31
+ '2. Call `fossil_changes` for the changed files; read the edits with `fossil_diff`.',
32
+ '3. Group the changes by intent and note anything incomplete, debug-only or accidental.',
33
+ '4. Propose one commit message per group, following the style of `fossil_timeline { limit: 5 }`.',
34
+ '',
35
+ 'Report the findings and stop before committing.',
36
+ ].join('\n')));
37
+ server.registerPrompt('fossil-commit-workflow', {
38
+ title: 'Stage and commit',
39
+ description: 'Stage the working tree changes, review the diff and create one check-in with a message.',
40
+ argsSchema: z.object({
41
+ message: z.string().min(1).optional().describe('Commit message to use. Omit to derive one from the diff.'),
42
+ workspace: workspaceArg,
43
+ }),
44
+ }, ({ message, workspace }) => userMessage([
45
+ 'Create a Fossil check-in for the current changes.',
46
+ workspaceLine(workspace),
47
+ '',
48
+ '1. Call `fossil_addremove` with `dry_run: true` to preview what would be staged.',
49
+ '2. Run it again without `dry_run` to stage the additions and removals.',
50
+ '3. Call `fossil_diff` and `fossil_changes` to confirm exactly what the check-in will contain.',
51
+ message
52
+ ? `4. Commit with \`fossil_commit { message: ${JSON.stringify(message)} }\`.`
53
+ : '4. Write a one-line message in the style of the recent history, then commit with `fossil_commit`.',
54
+ '5. Confirm the result with `fossil_timeline { limit: 1 }`.',
55
+ ].join('\n')));
56
+ server.registerPrompt('fossil-ignore-conversion', {
57
+ title: 'Convert .gitignore to ignore-glob',
58
+ description: 'Turn an existing .gitignore into .fossil-settings/ignore-glob and verify what Fossil now hides.',
59
+ argsSchema: z.object({
60
+ source: z.string().min(1).optional().describe('Path of the .gitignore file, relative to the workspace.'),
61
+ workspace: workspaceArg,
62
+ }),
63
+ }, ({ source, workspace }) => userMessage([
64
+ 'Give this check-out the same ignore rules it had under Git.',
65
+ workspaceLine(workspace),
66
+ '',
67
+ '1. Call `fossil_extras` to see which untracked files currently show up.',
68
+ `2. Call \`fossil_ignore_from_gitignore\` with \`write: false\`${source ? ` and \`source: "${source}"\`` : ''} to preview the patterns.`,
69
+ '3. Read every `NOTE:` line: negated rules cannot be expressed, and `**` rules are expanded.',
70
+ '4. Write the file with `write: true`, adding `overwrite: true` when the tool reports an existing ignore-glob.',
71
+ '5. Call `fossil_extras` again and report which paths are now ignored.',
72
+ ].join('\n')));
73
+ server.registerPrompt('fossil-trace-change', {
74
+ title: 'Trace a change',
75
+ description: 'Find out when, why and by whom a file or string changed, using the history tools.',
76
+ argsSchema: z.object({
77
+ target: z.string().min(1).describe('File path or text to trace.'),
78
+ workspace: workspaceArg,
79
+ }),
80
+ }, ({ target, workspace }) => userMessage([
81
+ `Trace the history of \`${target}\`.`,
82
+ workspaceLine(workspace),
83
+ '',
84
+ '1. Use `fossil_whatis` to resolve the name when it looks like a check-in, tag or branch.',
85
+ '2. Use `fossil_finfo` in `log` mode to list the changes of the file, and `fossil_annotate` to see which',
86
+ ' check-in last touched each line.',
87
+ '3. Use `fossil_timeline` around the interesting timestamps to read the surrounding check-ins, and',
88
+ ' `fossil_search` to find the comments that mention the same text.',
89
+ '4. Use `fossil_describe` to name the versions you quote.',
90
+ '',
91
+ 'Summarise the sequence of changes with check-in hashes, dates and comments.',
92
+ ].join('\n')));
93
+ server.registerPrompt('fossil-bisect-hunt', {
94
+ title: 'Hunt a regression',
95
+ description: 'Use bisect to find the check-in that introduced a problem, then explain the change.',
96
+ argsSchema: z.object({
97
+ symptom: z.string().min(1).describe('What breaks, and how to notice it.'),
98
+ workspace: workspaceArg,
99
+ }),
100
+ }, ({ symptom, workspace }) => userMessage([
101
+ `Find the check-in that introduced this problem: ${symptom}`,
102
+ workspaceLine(workspace),
103
+ '',
104
+ '1. Call `fossil_timeline` with a wide `limit` to see the range of check-ins.',
105
+ '2. Mark the known-good version with `fossil_bisect { action: "good", version: "<hash>" }` and the',
106
+ ' known-bad one with `fossil_bisect { action: "bad", version: "tip" }`.',
107
+ '3. Repeat: `fossil_bisect { action: "next" }` updates the check-out, test the symptom, then mark',
108
+ ' good or bad. Use `fossil_bisect { action: "log" }` to review the decisions.',
109
+ '4. Read the offending check-in with `fossil_whatis` and `fossil_diff`, and quote it with `fossil_describe`.',
110
+ '5. Finish with `fossil_bisect { action: "reset" }` and restore the check-out with `fossil_update`.',
111
+ ].join('\n')));
112
+ }
113
+ if (has('a')) {
114
+ server.registerPrompt('fossil-sync-remote', {
115
+ title: 'Sync with a remote',
116
+ description: 'Configure a remote URL and exchange changes with it.',
117
+ argsSchema: z.object({
118
+ url: z.string().min(1).optional().describe('Remote repository URL. Omit when a default remote is already set.'),
119
+ workspace: workspaceArg,
120
+ }),
121
+ }, ({ url, workspace }) => userMessage([
122
+ 'Synchronise this repository with its remote.',
123
+ workspaceLine(workspace),
124
+ url
125
+ ? `1. Register the remote: \`fossil_remote { action: "add", name: "origin", url: "${url}" }\`, then make it the default with \`fossil_remote { action: "set", name: "origin" }\`.`
126
+ : '1. Call `fossil_remote` to check which URL is the default; stop and ask for one when it prints `off`.',
127
+ '2. Call `fossil_pull` and report any conflicts or rejected artifacts.',
128
+ '3. Call `fossil_push` once the local check-ins are ready to share.',
129
+ '4. Confirm with `fossil_sync`, which exchanges both directions.',
130
+ ].join('\n')));
131
+ server.registerPrompt('fossil-repair-repository', {
132
+ title: 'Repair a repository',
133
+ description: 'Check the repository for damage and rebuild it when the schema or content is stale.',
134
+ argsSchema: z.object({
135
+ repository: z.string().min(1).optional().describe('Repository file to repair. Omit for the check-out repository.'),
136
+ workspace: workspaceArg,
137
+ }),
138
+ }, ({ repository, workspace }) => userMessage([
139
+ 'Repair this Fossil repository.',
140
+ workspaceLine(workspace),
141
+ repository ? `Target repository: \`${repository}\`.` : 'Use the repository of the current check-out.',
142
+ '',
143
+ '1. Call `fossil_info` and `fossil_status` to record the current state.',
144
+ '2. Run `fossil_sql` with `SELECT count(*) AS n FROM blob` and `SELECT max(rcvid) AS rcvid FROM blob`',
145
+ ' to confirm the database answers queries.',
146
+ '3. Call `fossil_rebuild` with `ifneeded: true` first; if the schema is current, report that and stop.',
147
+ '4. Otherwise run `fossil_rebuild` with `stats: true` and, when the repository looks bloated, `compress: true`.',
148
+ '5. Repeat step 2 and compare the numbers, then report what changed.',
149
+ ].join('\n')));
150
+ }
151
+ if (has('t')) {
152
+ server.registerPrompt('fossil-ticket-triage', {
153
+ title: 'Triage tickets',
154
+ description: 'Read the open tickets and move the ones that are being worked on.',
155
+ argsSchema: z.object({
156
+ report: z.string().min(1).optional().describe('Ticket report to read. Omit for the default report.'),
157
+ workspace: workspaceArg,
158
+ }),
159
+ }, ({ report, workspace }) => userMessage([
160
+ 'Triage the tickets in this repository.',
161
+ workspaceLine(workspace),
162
+ `1. Call \`fossil_ticket_list\`${report ? ` with \`report: "${report}"\`` : ''} and summarise the open work.`,
163
+ '2. Group the tickets by area and pick the ones that match the current changes.',
164
+ '3. For the tickets actually being worked on, set the status field with `fossil_ticket_update`.',
165
+ ].join('\n')));
166
+ }
167
+ }
package/dist/server.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { CAPABILITIES, allCapabilities, toolCountOf } from './capabilities.js';
3
3
  import { SERVER_NAME, SERVER_VERSION } from './config.js';
4
+ import { registerPrompts } from './prompts.js';
4
5
  function serverIdentity(ids) {
5
6
  if (ids.length === 1) {
6
7
  const capability = CAPABILITIES[ids[0]];
@@ -13,9 +14,9 @@ function buildInstructions(ids) {
13
14
  `MCP server exposing ${toolCountOf(ids)} Fossil SCM tools from ${ids.length} enabled capability ${ids.length === 1 ? 'group' : 'groups'}.`,
14
15
  'Enabled capabilities:',
15
16
  ...ids.map((id) => `- ${CAPABILITIES[id].title}: ${CAPABILITIES[id].description}`),
16
- 'Every tool accepts an optional `cwd` pointing at the check-out or workspace directory;',
17
- 'when omitted the server default is used (set with --repository, FOSSIL_WORKSPACE or FOSSIL_CWD).',
18
- 'Repository databases resolve to the sibling ".fossil_repositories" folder when no explicit db_name is given.',
17
+ 'Every tool accepts an optional `workspace` pointing at the check-out or workspace directory;',
18
+ 'when omitted the --workspace value or FOSSIL_WORKSPACE is used, then the process working directory.',
19
+ 'Repository paths are never defaulted: pass the repository file explicitly to init/open.',
19
20
  ];
20
21
  return lines.join('\n');
21
22
  }
@@ -36,5 +37,6 @@ export function createServer(options = {}) {
36
37
  }, { instructions: buildInstructions(ids) });
37
38
  for (const id of ids)
38
39
  CAPABILITIES[id].register(server);
40
+ registerPrompts(server, ids);
39
41
  return server;
40
42
  }