claude-db 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +96 -0
  2. package/README.md +74 -45
  3. package/dist/capture/flush.js +16 -8
  4. package/dist/cli/commands/graph.js +14 -2
  5. package/dist/cli/commands/transfer.d.ts +1 -1
  6. package/dist/cli/commands/transfer.js +4 -2
  7. package/dist/cli/index.js +1 -1
  8. package/dist/cli/install.js +1 -0
  9. package/dist/cli/usage.js +1 -1
  10. package/dist/config/schema.d.ts +2 -1
  11. package/dist/config/schema.js +2 -1
  12. package/dist/graph/index.d.ts +2 -2
  13. package/dist/graph/index.js +2 -2
  14. package/dist/graph/query/format.js +7 -3
  15. package/dist/graph/query/index.d.ts +1 -0
  16. package/dist/graph/query/index.js +1 -0
  17. package/dist/graph/query/lookup.d.ts +1 -0
  18. package/dist/graph/query/lookup.js +6 -0
  19. package/dist/graph/query/suggest.d.ts +5 -0
  20. package/dist/graph/query/suggest.js +65 -0
  21. package/dist/graph/scan/files.d.ts +1 -0
  22. package/dist/graph/scan/files.js +8 -2
  23. package/dist/graph/scan/index.d.ts +1 -1
  24. package/dist/graph/scan/index.js +1 -1
  25. package/dist/hooks/grep-symbols.d.ts +3 -0
  26. package/dist/hooks/grep-symbols.js +22 -0
  27. package/dist/hooks/prefer-usages.d.ts +2 -0
  28. package/dist/hooks/prefer-usages.js +58 -0
  29. package/dist/mcp/server.js +6 -170
  30. package/dist/mcp/tools/kinds.d.ts +1 -0
  31. package/dist/mcp/tools/kinds.js +1 -0
  32. package/dist/mcp/tools/memory.d.ts +3 -0
  33. package/dist/mcp/tools/memory.js +44 -0
  34. package/dist/mcp/tools/observations.d.ts +3 -0
  35. package/dist/mcp/tools/observations.js +55 -0
  36. package/dist/mcp/tools/search.d.ts +3 -0
  37. package/dist/mcp/tools/search.js +54 -0
  38. package/dist/mcp/tools/usages.d.ts +3 -0
  39. package/dist/mcp/tools/usages.js +79 -0
  40. package/dist/search/service.js +3 -0
  41. package/dist/search/stopwords.d.ts +2 -0
  42. package/dist/search/stopwords.js +137 -0
  43. package/dist/store/sqlite/filters.js +3 -5
  44. package/dist/usages/find.d.ts +1 -1
  45. package/dist/usages/find.js +5 -3
  46. package/docs/how-it-works.md +12 -12
  47. package/docs/with-and-without.md +123 -0
  48. package/package.json +3 -1
  49. package/docs/mcp-findings.md +0 -391
  50. package/docs/token-economics.md +0 -216
@@ -2,7 +2,7 @@ import { loadParser } from '../parser.js';
2
2
  import { extractFile } from './extract.js';
3
3
  import { listFiles, readSource } from './files.js';
4
4
  import { resolveEdges } from './resolve.js';
5
- export { currentHashes, hashOf, listFiles, sourceFiles } from './files.js';
5
+ export { SCAN_VERSION, currentHashes, hashOf, listFiles, sourceFiles } from './files.js';
6
6
  export function scanRepository(options) {
7
7
  const { root, project, known, force } = options;
8
8
  loadParser();
@@ -0,0 +1,3 @@
1
+ export declare function isSymbol(pattern: string): boolean;
2
+ /** Symbols a shell command searches the tree for, which the code graph also answers. */
3
+ export declare function symbolsGreppedIn(command: string): string[];
@@ -0,0 +1,22 @@
1
+ const SYMBOL = /^(?=.{4,})(?:[a-z]+(?:[A-Z][a-zA-Z0-9]*)+|[A-Z][a-z0-9]+(?:[A-Z][a-zA-Z0-9]*)*|[a-z][a-z0-9]*(?:_[a-z0-9]+)+)$/;
2
+ const GREP = /\b(?:grep|rg)\b((?:\s+-{1,2}[\w-]+(?:=\S+)?)*)\s+(?:(['"])(.+?)\2|(\S+))([^;&|]*)/g;
3
+ export function isSymbol(pattern) {
4
+ return SYMBOL.test(pattern);
5
+ }
6
+ /** Symbols a shell command searches the tree for, which the code graph also answers. */
7
+ export function symbolsGreppedIn(command) {
8
+ const found = new Set();
9
+ for (const match of command.matchAll(GREP)) {
10
+ const flags = match[1] ?? '';
11
+ const pattern = match[3] ?? match[4] ?? '';
12
+ const rest = match[5] ?? '';
13
+ if (!SYMBOL.test(pattern))
14
+ continue;
15
+ if (/-\w*v/.test(flags))
16
+ continue;
17
+ if (/-\w*[rR]\b|--recursive/.test(flags) || /^\s+[^-|;&>][^\s|;&>]*/.test(rest)) {
18
+ found.add(pattern);
19
+ }
20
+ }
21
+ return [...found].sort();
22
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import { createContext } from '../context.js';
3
+ import { formatGraph, queryGraph } from '../graph/index.js';
4
+ import { isSymbol, symbolsGreppedIn } from './grep-symbols.js';
5
+ import { readPayload, runHook } from './payload.js';
6
+ import { resolveProject } from '../util/project.js';
7
+ import { silenceSqliteWarning } from '../util/warnings.js';
8
+ silenceSqliteWarning();
9
+ const MAX_SYMBOLS = 2;
10
+ const MAX_LINES = 14;
11
+ function requested(payload) {
12
+ const input = payload.tool_input ?? {};
13
+ if (payload.tool_name === 'Grep') {
14
+ const pattern = typeof input['pattern'] === 'string' ? input['pattern'] : '';
15
+ return isSymbol(pattern) ? [pattern] : [];
16
+ }
17
+ if (payload.tool_name === 'Bash') {
18
+ return symbolsGreppedIn(typeof input['command'] === 'string' ? input['command'] : '');
19
+ }
20
+ return [];
21
+ }
22
+ function trim(answer) {
23
+ const lines = answer.split('\n');
24
+ if (lines.length <= MAX_LINES)
25
+ return answer;
26
+ return [...lines.slice(0, MAX_LINES), ` ... more via find_usages`].join('\n');
27
+ }
28
+ await runHook(async () => {
29
+ if (process.env['CLAUDE_DB_USAGES_HOOK'] === 'off')
30
+ return;
31
+ const payload = await readPayload();
32
+ const symbols = requested(payload).slice(0, MAX_SYMBOLS);
33
+ if (symbols.length === 0)
34
+ return;
35
+ const project = resolveProject(payload.cwd);
36
+ const ctx = await createContext();
37
+ const blocks = [];
38
+ try {
39
+ for (const symbol of symbols) {
40
+ const answer = await queryGraph(ctx.store, project, { mode: 'usages', symbol, limit: 20 });
41
+ if (answer.empty)
42
+ continue;
43
+ blocks.push(trim(formatGraph(answer, project)));
44
+ }
45
+ }
46
+ finally {
47
+ await ctx.close();
48
+ }
49
+ if (blocks.length === 0)
50
+ return;
51
+ process.stdout.write(JSON.stringify({
52
+ hookSpecificOutput: {
53
+ hookEventName: 'PreToolUse',
54
+ additionalContext: `Code graph, for the symbol(s) this search names — the grep below still runs, ` +
55
+ `this is the structure it cannot show:\n\n${blocks.join('\n\n')}`,
56
+ },
57
+ }));
58
+ });
@@ -4,17 +4,13 @@ import { dirname, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
7
- import { z } from 'zod';
8
- import { remember } from '../capture/index.js';
9
7
  import { createContext } from '../context.js';
10
- import { toShortId } from '../util/shortid.js';
11
- import { renderFull, renderIndex } from './render.js';
12
- import { resolveProject } from '../util/project.js';
13
- import { findUsages, formatUsages, repoRootFor } from '../usages/index.js';
14
- import { formatGraph, queryGraph, refreshGraph } from '../graph/index.js';
15
8
  import { silenceSqliteWarning } from '../util/warnings.js';
9
+ import * as memory from './tools/memory.js';
10
+ import * as observations from './tools/observations.js';
11
+ import * as search from './tools/search.js';
12
+ import * as usages from './tools/usages.js';
16
13
  silenceSqliteWarning();
17
- const KINDS = ['decision', 'pattern', 'bugfix', 'context', 'deadend', 'preference'];
18
14
  function packageVersion() {
19
15
  try {
20
16
  const path = resolve(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json');
@@ -26,168 +22,8 @@ function packageVersion() {
26
22
  }
27
23
  const ctx = await createContext();
28
24
  const server = new McpServer({ name: 'claude-db', version: packageVersion() });
29
- server.tool('search', 'Layer 1. Search project memory and get a compact index of matches ' +
30
- '(id, kind, date, title, and a line of the matching body) without full ' +
31
- 'bodies. Start here, and use the snippet to decide which ids are worth ' +
32
- 'passing to get_observations rather than expanding on the title alone.', {
33
- query: z.string().describe('Natural language description of what you need'),
34
- project: z
35
- .string()
36
- .optional()
37
- .describe('Absolute project path; defaults to cwd. Pass "*" to search every project'),
38
- kind: z.enum(KINDS).optional(),
39
- tag: z
40
- .string()
41
- .optional()
42
- .describe('Limit to one repository or top-level directory, e.g. "backend". Useful ' +
43
- 'when a workspace pools several repos under one project'),
44
- limit: z.number().int().min(1).max(50).default(10),
45
- }, async ({ query, project, kind, tag, limit }) => {
46
- const entries = await ctx.search.search({
47
- text: query,
48
- limit,
49
- ...(project === '*' ? {} : { project: resolveProject(project) }),
50
- ...(kind ? { kind } : {}),
51
- ...(tag ? { tag } : {}),
52
- });
53
- return { content: [{ type: 'text', text: renderIndex(entries) }] };
54
- });
55
- server.tool('remember', 'Record something the user stated outright that no transcript would capture: ' +
56
- 'a standing rule, preference or constraint ("always use pnpm here"). Use this ' +
57
- 'when the user says to remember something, not for work you just did — that ' +
58
- 'is captured automatically.', {
59
- text: z.string().describe('What to remember, in full. First line becomes the title'),
60
- kind: z.enum(KINDS).default('preference'),
61
- project: z.string().optional().describe('Absolute project path; defaults to cwd'),
62
- key: z
63
- .string()
64
- .optional()
65
- .describe('Stable name for a note meant to be kept current, e.g. "profile:stack". ' +
66
- 'Remembering the same key again replaces it instead of adding a duplicate'),
67
- tags: z.array(z.string()).max(5).optional().describe('Extra tags for filtering'),
68
- }, async ({ text, kind, project, key, tags }) => {
69
- const observation = await remember(ctx, {
70
- project: resolveProject(project),
71
- text,
72
- kind,
73
- ...(key ? { key } : {}),
74
- ...(tags ? { tags } : {}),
75
- });
76
- return {
77
- content: [
78
- {
79
- type: 'text',
80
- text: `Remembered ${toShortId(observation.id)} [${observation.kind}] ${observation.title}`,
81
- },
82
- ],
83
- };
84
- });
85
- server.tool('forget', 'Delete observations by id, for memory that is wrong or obsolete. Ids come ' +
86
- 'from search. This cannot be undone, so confirm with the user first.', { ids: z.array(z.string()).min(1).max(25) }, async ({ ids }) => {
87
- const deleted = await ctx.store.remove({ ids });
88
- return {
89
- content: [{ type: 'text', text: `Forgot ${deleted} observation(s).` }],
90
- };
91
- });
92
- server.tool('timeline', 'Layer 2. Show what happened immediately before and after a given ' +
93
- 'observation, to understand the context a decision was made in.', {
94
- observation_id: z.string(),
95
- before: z.number().int().min(0).max(20).default(5),
96
- after: z.number().int().min(0).max(20).default(5),
97
- }, async ({ observation_id, before, after }) => {
98
- const entries = await ctx.search.timeline({ observationId: observation_id, before, after });
99
- return { content: [{ type: 'text', text: renderIndex(entries) }] };
100
- });
101
- server.tool('get_observations', 'Layer 3. Fetch full bodies for specific observation ids, using the short ' +
102
- 'ids returned by search. Always batch every id you need into one call ' +
103
- 'rather than calling repeatedly.', {
104
- ids: z.array(z.string()).min(1).max(25),
105
- chars: z
106
- .number()
107
- .int()
108
- .min(200)
109
- .max(20000)
110
- .default(2000)
111
- .describe('Characters of each body to return. Bodies run to 4000 and this call ' +
112
- 'takes 25 ids, so the default keeps a batch readable; raise it when a ' +
113
- 'truncated answer says there is more'),
114
- }, async ({ ids, chars }) => {
115
- const observations = await ctx.search.getObservations(ids);
116
- return {
117
- content: [
118
- {
119
- type: 'text',
120
- text: observations.map((obs) => renderFull(obs, chars)).join('\n\n---\n\n'),
121
- },
122
- ],
123
- };
124
- });
125
- server.tool('find_usages', 'Find real usages of a symbol, and how the code around it connects. ' +
126
- '`mode: "text"` (default) is a live `git grep` — never stale, works with no ' +
127
- 'setup, and returns file:line with a best-effort [definition?] marker. The ' +
128
- 'other modes read the code graph built by `claude-db scan`, which knows a ' +
129
- 'call from an import from an inherit: "usages" lists what references the ' +
130
- 'symbol with the relation on each line, "explain" adds what the symbol ' +
131
- 'reaches, and "path" traces how two symbols connect (pass the second as ' +
132
- '`target`). Graph answers re-parse anything that changed before replying, ' +
133
- 'so they cannot report a line the source has moved past. Every edge is ' +
134
- 'tagged EXTRACTED (read literally from the syntax) or INFERRED (matched by ' +
135
- 'name across files, with a score). Use `search` instead for "why is this ' +
136
- 'the way it is" (history).', {
137
- symbol: z
138
- .string()
139
- .min(1)
140
- .max(200)
141
- .describe('Exact name to search for, e.g. "useAuth" or "CartButton"'),
142
- mode: z
143
- .enum(['text', 'usages', 'explain', 'path'])
144
- .default('text')
145
- .describe('How to answer. "text" greps live and needs no scan; the rest query the ' +
146
- 'stored graph and return nothing useful until `claude-db scan` has run'),
147
- target: z.string().optional().describe('The second symbol, for mode "path" only'),
148
- path: z
149
- .string()
150
- .optional()
151
- .describe('A file or directory to narrow the search to; omit to search the whole ' +
152
- 'repository (never narrows on its own — a blast-radius check that quietly ' +
153
- 'skipped part of the repo would be worse than no check). Must be inside a ' +
154
- 'git working tree. Different from the memory tools’ project param, which ' +
155
- 'can point at a folder pooling several repos rather than being one itself'),
156
- regex: z
157
- .boolean()
158
- .default(false)
159
- .describe('Treat symbol as an extended regular expression instead of a literal name'),
160
- context: z
161
- .number()
162
- .int()
163
- .min(0)
164
- .max(10)
165
- .default(0)
166
- .describe('Lines of surrounding context before/after each match'),
167
- limit: z
168
- .number()
169
- .int()
170
- .min(1)
171
- .max(500)
172
- .default(100)
173
- .describe('Cap on matching lines returned; the result says how many more exist'),
174
- }, async ({ symbol, mode, target, path, regex, context, limit }) => {
175
- if (mode === 'text') {
176
- const result = findUsages({ symbol, regex, context, limit, ...(path ? { path } : {}) });
177
- return { content: [{ type: 'text', text: formatUsages(result) }] };
178
- }
179
- const root = repoRootFor(path ?? process.cwd());
180
- const project = resolveProject(undefined);
181
- const refreshed = await refreshGraph(ctx.store, root, project);
182
- const answer = await queryGraph(ctx.store, project, {
183
- mode,
184
- symbol,
185
- ...(target ? { target } : {}),
186
- limit,
187
- });
188
- answer.refreshed = refreshed;
189
- return { content: [{ type: 'text', text: formatGraph(answer, root) }] };
190
- });
25
+ for (const tools of [search, memory, observations, usages])
26
+ tools.register(server, ctx);
191
27
  const transport = new StdioServerTransport();
192
28
  await server.connect(transport);
193
29
  for (const signal of ['SIGINT', 'SIGTERM']) {
@@ -0,0 +1 @@
1
+ export declare const KINDS: readonly ["decision", "pattern", "bugfix", "context", "deadend", "preference"];
@@ -0,0 +1 @@
1
+ export const KINDS = ['decision', 'pattern', 'bugfix', 'context', 'deadend', 'preference'];
@@ -0,0 +1,3 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import type { RecallContext } from '../../context.js';
3
+ export declare function register(server: McpServer, ctx: RecallContext): void;
@@ -0,0 +1,44 @@
1
+ import { z } from 'zod';
2
+ import { KINDS } from './kinds.js';
3
+ import { remember } from '../../capture/index.js';
4
+ import { toShortId } from '../../util/shortid.js';
5
+ import { resolveProject } from '../../util/project.js';
6
+ export function register(server, ctx) {
7
+ server.tool('remember', 'Record something the user stated outright that no transcript would capture: ' +
8
+ 'a standing rule, preference or constraint ("always use pnpm here"). Use this ' +
9
+ 'when the user says to remember something, not for work you just did — that ' +
10
+ 'is captured automatically.', {
11
+ text: z.string().describe('What to remember, in full. First line becomes the title'),
12
+ kind: z.enum(KINDS).default('preference'),
13
+ project: z.string().optional().describe('Absolute project path; defaults to cwd'),
14
+ key: z
15
+ .string()
16
+ .optional()
17
+ .describe('Stable name for a note meant to be kept current, e.g. "profile:stack". ' +
18
+ 'Remembering the same key again replaces it instead of adding a duplicate'),
19
+ tags: z.array(z.string()).max(5).optional().describe('Extra tags for filtering'),
20
+ }, async ({ text, kind, project, key, tags }) => {
21
+ const observation = await remember(ctx, {
22
+ project: resolveProject(project),
23
+ text,
24
+ kind,
25
+ ...(key ? { key } : {}),
26
+ ...(tags ? { tags } : {}),
27
+ });
28
+ return {
29
+ content: [
30
+ {
31
+ type: 'text',
32
+ text: `Remembered ${toShortId(observation.id)} [${observation.kind}] ${observation.title}`,
33
+ },
34
+ ],
35
+ };
36
+ });
37
+ server.tool('forget', 'Delete observations by id, for memory that is wrong or obsolete. Ids come ' +
38
+ 'from search. This cannot be undone, so confirm with the user first.', { ids: z.array(z.string()).min(1).max(25) }, async ({ ids }) => {
39
+ const deleted = await ctx.store.remove({ ids });
40
+ return {
41
+ content: [{ type: 'text', text: `Forgot ${deleted} observation(s).` }],
42
+ };
43
+ });
44
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import type { RecallContext } from '../../context.js';
3
+ export declare function register(server: McpServer, ctx: RecallContext): void;
@@ -0,0 +1,55 @@
1
+ import { z } from 'zod';
2
+ import { renderFull, renderIndex } from '../render.js';
3
+ export function register(server, ctx) {
4
+ server.tool('timeline', 'Given one observation id from search, show what happened immediately before ' +
5
+ 'and after it. Use it when a single result is not enough to explain itself ' +
6
+ 'and you need the session around it — what led to a decision and what came ' +
7
+ 'of it. Ids are the short ids search prints.', {
8
+ observation_id: z.string(),
9
+ before: z.number().int().min(0).max(20).default(5),
10
+ after: z.number().int().min(0).max(20).default(5),
11
+ }, async ({ observation_id, before, after }) => {
12
+ const entries = await ctx.search.timeline({ observationId: observation_id, before, after });
13
+ if (entries.length === 0) {
14
+ const [found] = await ctx.search.getObservations([observation_id]);
15
+ const text = found
16
+ ? `No observations around ${observation_id}; it has no neighbours in that session.`
17
+ : `No observation with id ${observation_id}. Ids come from search, and are the short ` +
18
+ `ids it prints — run search first and pass one of those.`;
19
+ return { content: [{ type: 'text', text }] };
20
+ }
21
+ return { content: [{ type: 'text', text: renderIndex(entries) }] };
22
+ });
23
+ server.tool('get_observations', 'Read the full body of observations search has already found, using the short ' +
24
+ 'ids it printed. Use it whenever a search snippet looks like it answers your ' +
25
+ 'question but is cut off — the snippet is one line, the body is the reasoning. ' +
26
+ 'Always batch every id you need into one call rather than calling repeatedly.', {
27
+ ids: z.array(z.string()).min(1).max(25),
28
+ chars: z
29
+ .number()
30
+ .int()
31
+ .min(200)
32
+ .max(20000)
33
+ .default(2000)
34
+ .describe('Characters of each body to return. Bodies run to 4000 and this call ' +
35
+ 'takes 25 ids, so the default keeps a batch readable; raise it when a ' +
36
+ 'truncated answer says there is more'),
37
+ }, async ({ ids, chars }) => {
38
+ const observations = await ctx.search.getObservations(ids);
39
+ if (observations.length === 0) {
40
+ return {
41
+ content: [
42
+ {
43
+ type: 'text',
44
+ text: `No observation matched ${ids.join(', ')}. Ids come from search — run it first ` +
45
+ `and pass the short ids it prints.`,
46
+ },
47
+ ],
48
+ };
49
+ }
50
+ const missing = ids.filter((id) => !observations.some((obs) => obs.id === id || obs.id.startsWith(id)));
51
+ const body = observations.map((obs) => renderFull(obs, chars)).join('\n\n---\n\n');
52
+ const note = missing.length > 0 ? `\n\n(no observation matched ${missing.join(', ')})` : '';
53
+ return { content: [{ type: 'text', text: body + note }] };
54
+ });
55
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import type { RecallContext } from '../../context.js';
3
+ export declare function register(server: McpServer, ctx: RecallContext): void;
@@ -0,0 +1,54 @@
1
+ import { z } from 'zod';
2
+ import { KINDS } from './kinds.js';
3
+ import { renderIndex } from '../render.js';
4
+ import { resolveProject } from '../../util/project.js';
5
+ export function register(server, ctx) {
6
+ server.tool('search', 'USE THIS BEFORE re-deriving anything this project already decided — before ' +
7
+ 'reading git history to reconstruct why code is the way it is, before saying ' +
8
+ 'you lack context, and before asking the user to re-explain a past decision ' +
9
+ 'or a failed approach. This answers WHY: decisions, dead ends, bugs and the ' +
10
+ 'reasoning behind them, which the source code cannot tell you. Returns a ' +
11
+ 'compact index (id, kind, date, title, and a line of the matching body) ' +
12
+ 'without full bodies; use the snippet to decide which ids are worth passing ' +
13
+ 'to get_observations rather than expanding on the title alone. For a code ' +
14
+ 'symbol use find_usages instead.', {
15
+ query: z.string().describe('Natural language description of what you need'),
16
+ project: z
17
+ .string()
18
+ .optional()
19
+ .describe('Absolute project path; defaults to cwd. Pass "*" to search every project'),
20
+ kind: z.enum(KINDS).optional(),
21
+ tag: z
22
+ .string()
23
+ .optional()
24
+ .describe('Limit to one repository or top-level directory, e.g. "backend". Useful ' +
25
+ 'when a workspace pools several repos under one project'),
26
+ limit: z.number().int().min(1).max(50).default(10),
27
+ }, async ({ query, project, kind, tag, limit }) => {
28
+ const entries = await ctx.search.search({
29
+ text: query,
30
+ limit,
31
+ ...(project === '*' ? {} : { project: resolveProject(project) }),
32
+ ...(kind ? { kind } : {}),
33
+ ...(tag ? { tag } : {}),
34
+ });
35
+ if (entries.length === 0) {
36
+ return { content: [{ type: 'text', text: await noMatches(ctx, project) }] };
37
+ }
38
+ return { content: [{ type: 'text', text: renderIndex(entries) }] };
39
+ });
40
+ }
41
+ async function noMatches(ctx, project) {
42
+ const scope = project === '*' ? undefined : resolveProject(project);
43
+ const any = await ctx.store.list({ ...(scope ? { project: scope } : {}), limit: 1 });
44
+ if (any.length === 0) {
45
+ return scope
46
+ ? `No memory recorded for ${scope} yet. Run \`claude-db flush\` to ingest this ` +
47
+ `project's sessions, or pass project: "*" to search every project.`
48
+ : 'No memory recorded in this database yet. Run `claude-db flush` to ingest sessions.';
49
+ }
50
+ return scope
51
+ ? `No match in ${scope}, though it does have memory. Try broader wording, drop the kind ` +
52
+ `or tag filter, or pass project: "*" to search every project.`
53
+ : 'No match in any project. Try broader wording, or drop the kind or tag filter.';
54
+ }
@@ -0,0 +1,3 @@
1
+ import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import type { RecallContext } from '../../context.js';
3
+ export declare function register(server: McpServer, ctx: RecallContext): void;
@@ -0,0 +1,79 @@
1
+ import { z } from 'zod';
2
+ import { findUsages, formatUsages, repoRootFor } from '../../usages/index.js';
3
+ import { formatGraph, queryGraph, refreshGraph, suggestFor } from '../../graph/index.js';
4
+ import { resolveProject } from '../../util/project.js';
5
+ export function register(server, ctx) {
6
+ server.tool('find_usages', 'USE THIS INSTEAD OF grep/rg WHENEVER THE THING YOU ARE LOOKING UP IS A CODE ' +
7
+ 'SYMBOL — a function, class, method, type, interface, constant or any ' +
8
+ 'identifier — and ALWAYS before editing, renaming or deleting one, because ' +
9
+ 'grep cannot tell a call from an import from an inherit and will not show ' +
10
+ 'you the blast radius. Reach for grep only for what is genuinely text: ' +
11
+ 'plain prose, comments, log output, string literals, multi-pattern regex, ' +
12
+ 'or the scoping flags this tool does not expose. Modes: "usages" lists what ' +
13
+ 'references the symbol with the relation on each line, "explain" adds what ' +
14
+ 'the symbol reaches, "path" traces how two symbols connect (pass the second ' +
15
+ 'as `target`), and `mode: "text"` (default) is a live `git grep` that needs ' +
16
+ 'no scan. Graph modes read the graph built by `claude-db scan` and re-parse ' +
17
+ 'anything that changed before replying, so they cannot report a line the ' +
18
+ 'source has moved past. Every edge is tagged EXTRACTED (read literally from ' +
19
+ 'the syntax) or INFERRED (matched by name across files, with a score). A ' +
20
+ 'miss suggests near names, so a half-remembered symbol is still worth ' +
21
+ 'asking about. Use `search` instead for "why is this the way it is" (history).', {
22
+ symbol: z
23
+ .string()
24
+ .min(1)
25
+ .max(200)
26
+ .describe('Exact name to search for, e.g. "useAuth" or "CartButton"'),
27
+ mode: z
28
+ .enum(['text', 'usages', 'explain', 'path'])
29
+ .default('text')
30
+ .describe('How to answer. "text" greps live and needs no scan; the rest query the ' +
31
+ 'stored graph and return nothing useful until `claude-db scan` has run'),
32
+ target: z.string().optional().describe('The second symbol, for mode "path" only'),
33
+ path: z
34
+ .string()
35
+ .optional()
36
+ .describe('A file or directory to narrow the search to; omit to search the whole ' +
37
+ 'repository (never narrows on its own — a blast-radius check that quietly ' +
38
+ 'skipped part of the repo would be worse than no check). Must be inside a ' +
39
+ 'git working tree. Different from the memory tools’ project param, which ' +
40
+ 'can point at a folder pooling several repos rather than being one itself'),
41
+ regex: z
42
+ .boolean()
43
+ .default(false)
44
+ .describe('Treat symbol as an extended regular expression instead of a literal name'),
45
+ context: z
46
+ .number()
47
+ .int()
48
+ .min(0)
49
+ .max(10)
50
+ .default(0)
51
+ .describe('Lines of surrounding context before/after each match'),
52
+ limit: z
53
+ .number()
54
+ .int()
55
+ .min(1)
56
+ .max(500)
57
+ .default(100)
58
+ .describe('Cap on matching lines returned; the result says how many more exist'),
59
+ }, async ({ symbol, mode, target, path, regex, context, limit }) => {
60
+ if (mode === 'text') {
61
+ const result = findUsages({ symbol, regex, context, limit, ...(path ? { path } : {}) });
62
+ const missed = result.matches.length === 0
63
+ ? await suggestFor(ctx.store, resolveProject(undefined), symbol)
64
+ : [];
65
+ return { content: [{ type: 'text', text: formatUsages(result, missed) }] };
66
+ }
67
+ const root = repoRootFor(path ?? process.cwd());
68
+ const project = resolveProject(undefined);
69
+ const refreshed = await refreshGraph(ctx.store, root, project);
70
+ const answer = await queryGraph(ctx.store, project, {
71
+ mode,
72
+ symbol,
73
+ ...(target ? { target } : {}),
74
+ limit,
75
+ });
76
+ answer.refreshed = refreshed;
77
+ return { content: [{ type: 'text', text: formatGraph(answer, root) }] };
78
+ });
79
+ }
@@ -1,4 +1,5 @@
1
1
  import { applyRecencyBoost, fuse } from './rank.js';
2
+ import { meaningfulTokens } from './stopwords.js';
2
3
  export class SearchService {
3
4
  store;
4
5
  embedder;
@@ -9,6 +10,8 @@ export class SearchService {
9
10
  this.maxScanCandidates = maxScanCandidates;
10
11
  }
11
12
  async search(query) {
13
+ if (meaningfulTokens(query.text).length === 0)
14
+ return [];
12
15
  const wide = {
13
16
  ...query,
14
17
  limit: query.limit * 3,
@@ -0,0 +1,2 @@
1
+ export declare function isStopword(token: string): boolean;
2
+ export declare function meaningfulTokens(text: string): string[];