roam-research-mcp 5.1.0 → 5.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -137,43 +137,28 @@ export class SearchUtils {
137
137
  return tagMap;
138
138
  }
139
139
  /**
140
- * Generate case variations for case-insensitive search.
141
- * Returns: [original, capitalized first letter, ALL CAPS, all lowercase]
140
+ * Quote literal search text for Roam's Java regex engine. (?iu) enables
141
+ * Unicode-aware case-insensitivity; metacharacters retain their literal meaning.
142
+ * Roam's backend supports re-pattern/re-find, but not clojure.string/lower-case.
142
143
  */
143
- static getCaseVariations(text, caseSensitive = false) {
144
- if (caseSensitive) {
145
- return [text];
146
- }
147
- return [
148
- text,
149
- text.charAt(0).toUpperCase() + text.slice(1),
150
- text.toUpperCase(),
151
- text.toLowerCase()
152
- ];
144
+ static caseInsensitivePattern(text) {
145
+ return ednString(`(?iu)${text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`);
153
146
  }
154
- /**
155
- * Build OR where clause for case-insensitive text search.
156
- * @param text - The search text
157
- * @param variable - The Datomic variable name (e.g., "?block-str")
158
- * @param caseSensitive - Whether to use case-sensitive matching
159
- * @returns Datomic OR clause string
160
- */
147
+ /** Match a literal substring, optionally ignoring capitalization. */
161
148
  static buildTextSearchClause(text, variable, caseSensitive = false) {
162
- const variations = this.getCaseVariations(text, caseSensitive);
163
- const clauses = variations.map(term => `[(clojure.string/includes? ${variable} ${ednString(term)})]`);
164
- return `(or ${clauses.join(' ')})`;
149
+ if (caseSensitive) {
150
+ return `[(clojure.string/includes? ${variable} ${ednString(text)})]`;
151
+ }
152
+ return `[(re-pattern ${this.caseInsensitivePattern(text)}) ${variable}-pattern]
153
+ [(re-find ${variable}-pattern ${variable})]`;
165
154
  }
166
- /**
167
- * Build OR where clause for case-insensitive tag/page title matching.
168
- * @param tag - The tag/page title to match
169
- * @param variable - The Datomic variable name (e.g., "?ref-page")
170
- * @param caseSensitive - Whether to use case-sensitive matching
171
- * @returns Datomic OR clause string
172
- */
155
+ /** Match a whole referenced page title, optionally ignoring capitalization. */
173
156
  static buildTagMatchClause(tag, variable, caseSensitive = false) {
174
- const variations = this.getCaseVariations(tag, caseSensitive);
175
- const clauses = variations.map(t => `[${variable} :node/title ${ednString(t)}]`);
176
- return `(or ${clauses.join(' ')})`;
157
+ if (caseSensitive)
158
+ return `[${variable} :node/title ${ednString(tag)}]`;
159
+ return `[${variable} :node/title ${variable}-title]
160
+ [(re-pattern ${this.caseInsensitivePattern(tag)}) ${variable}-pattern]
161
+ [(re-matches ${variable}-pattern ${variable}-title)]`;
177
162
  }
178
163
  /**
179
164
  * The two spellings of a status marker: `{{[[TODO]]}}` (what Roam's checkbox
@@ -198,11 +198,11 @@ export class RoamServer {
198
198
  return toolResult(request.params.name, result);
199
199
  }
200
200
  case 'roam_search_for_tag': {
201
- const { primary_tag, page_title_uid, near_tag } = cleanedArgs;
201
+ const { primary_tag, page_title_uid, near_tag, case_sensitive } = cleanedArgs;
202
202
  if (!primary_tag) {
203
203
  throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter: primary_tag (the tag to search for). Use page_title_uid to limit search to a specific page.');
204
204
  }
205
- const result = await toolHandlers.searchForTag(primary_tag, page_title_uid, near_tag);
205
+ const result = await toolHandlers.searchForTag(primary_tag, page_title_uid, near_tag, case_sensitive);
206
206
  return toolResult(request.params.name, result);
207
207
  }
208
208
  case 'roam_search_by_status': {
@@ -1,5 +1,8 @@
1
+ import { q } from '@roam-research/roam-api-sdk';
2
+ import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
1
3
  import { TagSearchHandlerImpl, BlockRefSearchHandlerImpl, HierarchySearchHandlerImpl, TextSearchHandlerImpl, StatusSearchHandlerImpl, DatomicSearchHandlerImpl } from './handlers.js';
2
4
  import { collectHiddenUids, filterHiddenMatches } from '../../helpers/hidden.js';
5
+ import { resolveRefs } from '../../helpers/refs.js';
3
6
  export class SearchOperations {
4
7
  constructor(graph) {
5
8
  this.graph = graph;
@@ -69,11 +72,12 @@ export class SearchOperations {
69
72
  message: `Found ${matches.length} block(s) with status ${status}${include ? ` including "${include}"` : ''}${exclude ? ` excluding "${exclude}"` : ''}`
70
73
  };
71
74
  }
72
- async searchForTag(primary_tag, page_title_uid, near_tag) {
75
+ async searchForTag(primary_tag, page_title_uid, near_tag, case_sensitive) {
73
76
  const handler = new TagSearchHandlerImpl(this.graph, {
74
77
  primary_tag,
75
78
  page_title_uid,
76
79
  near_tag,
80
+ case_sensitive,
77
81
  });
78
82
  return this.withoutHidden(await handler.execute());
79
83
  }
@@ -97,35 +101,63 @@ export class SearchOperations {
97
101
  return handler.execute();
98
102
  }
99
103
  async searchByDate(params) {
100
- // Convert dates to timestamps
101
- const startTimestamp = new Date(`${params.start_date}T00:00:00`).getTime();
102
- const endTimestamp = params.end_date ? new Date(`${params.end_date}T23:59:59`).getTime() : undefined;
103
- // Use text search handler for content-based filtering
104
- const handler = new TextSearchHandlerImpl(this.graph, {
105
- text: '', // Empty text to match all blocks
106
- });
107
- // Filtered before the map below, which renames block_uid -> uid; after it
108
- // the hidden-UID closure would have nothing to match on.
109
- const result = await this.withoutHidden(await handler.execute());
110
- // Filter results by date
111
- const matches = result.matches
112
- .filter(match => {
113
- const time = params.type === 'created' ?
114
- new Date(match.content || '').getTime() : // Use content date for creation time
115
- Date.now(); // Use current time for modification time (simplified)
116
- return time >= startTimestamp && (!endTimestamp || time <= endTimestamp);
117
- })
118
- .map(match => ({
119
- uid: match.block_uid,
120
- type: 'block',
121
- time: params.type === 'created' ?
122
- new Date(match.content || '').getTime() :
123
- Date.now(),
124
- ...(params.include_content && { content: match.content }),
125
- page_title: match.page_title
104
+ const parseDay = (value) => {
105
+ const day = new Date(`${value}T00:00:00`);
106
+ const parts = value.split('-').map(Number);
107
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value) || !Number.isFinite(day.getTime()) ||
108
+ day.getFullYear() !== parts[0] || day.getMonth() + 1 !== parts[1] || day.getDate() !== parts[2]) {
109
+ throw new McpError(ErrorCode.InvalidParams, `Invalid date "${value}"; expected YYYY-MM-DD.`);
110
+ }
111
+ return day;
112
+ };
113
+ const start = parseDay(params.start_date).getTime();
114
+ const endDay = params.end_date === undefined ? undefined : parseDay(params.end_date);
115
+ if (endDay && endDay.getTime() < start) {
116
+ throw new McpError(ErrorCode.InvalidParams, 'end_date must be on or after start_date.');
117
+ }
118
+ // Next calendar midnight includes the entire final day, including .999,
119
+ // and handles days shortened or lengthened by daylight-saving transitions.
120
+ endDay?.setDate(endDay.getDate() + 1);
121
+ const inputs = endDay ? [start, endDay.getTime()] : [start];
122
+ const timeClause = params.type === 'both'
123
+ ? '(or [?e :create/time ?time] [?e :edit/time ?time])'
124
+ : `[?e :${params.type === 'created' ? 'create' : 'edit'}/time ?time]`;
125
+ const scopes = params.scope === 'both'
126
+ ? ['block', 'page'] : [params.scope === 'pages' ? 'page' : 'block'];
127
+ const results = await Promise.all(scopes.map(async (type) => {
128
+ const entityClause = type === 'block'
129
+ ? `[?e :block/string ?content]
130
+ [?e :block/page ?page]
131
+ [?page :node/title ?page-title]`
132
+ : `[?e :node/title ?content]
133
+ [?e :node/title ?page-title]`;
134
+ const query = `[:find ?uid ?content ?page-title ?time
135
+ :in $ ?start ${endDay ? '?end' : ''}
136
+ :where [?e :block/uid ?uid]
137
+ ${entityClause}
138
+ ${timeClause}
139
+ [(>= ?time ?start)]
140
+ ${endDay ? '[(< ?time ?end)]' : ''}]`;
141
+ const rows = await q(this.graph, query, inputs);
142
+ return rows.map(([block_uid, content, page_title, time]) => ({ block_uid, content, page_title, time, type }));
126
143
  }));
127
- // Sort by time
128
- const sortedMatches = matches.sort((a, b) => b.time - a.time);
144
+ const hidden = await collectHiddenUids(this.graph);
145
+ const visible = filterHiddenMatches(results.flat(), hidden);
146
+ const matchesByUid = new Map();
147
+ for (const match of visible) {
148
+ const previous = matchesByUid.get(match.block_uid);
149
+ // With type=both an entity may match twice. Return it once, with the
150
+ // latest timestamp that actually falls inside the requested range.
151
+ if (!previous || match.time > previous.time)
152
+ matchesByUid.set(match.block_uid, match);
153
+ }
154
+ const matches = await Promise.all([...matchesByUid.values()]
155
+ .map(async ({ block_uid, content, ...match }) => ({
156
+ uid: block_uid,
157
+ ...match,
158
+ ...(params.include_content !== false && { content: await resolveRefs(this.graph, content) }),
159
+ })));
160
+ const sortedMatches = matches.sort((a, b) => b.time - a.time || a.uid.localeCompare(b.uid));
129
161
  return {
130
162
  success: true,
131
163
  matches: sortedMatches,
@@ -417,7 +417,7 @@ export const toolSchemas = {
417
417
  },
418
418
  case_sensitive: {
419
419
  type: 'boolean',
420
- description: 'Optional: Whether the search should be case-sensitive. If false, it will search for the provided tag, capitalized versions, and first word capitalized versions.',
420
+ description: 'Optional: Whether the search should be case-sensitive. Defaults to Unicode-aware case-insensitive matching of the complete tag title.',
421
421
  default: false
422
422
  },
423
423
  limit: {
@@ -562,7 +562,7 @@ export const toolSchemas = {
562
562
  },
563
563
  case_sensitive: {
564
564
  type: 'boolean',
565
- description: 'Optional: Whether the search should be case-sensitive. If false, it will search for the provided text, capitalized versions, and first word capitalized versions. Only used when scope is "blocks".',
565
+ description: 'Optional: Whether the search should be case-sensitive. Defaults to Unicode-aware case-insensitive matching of literal text. Only used when scope is "blocks".',
566
566
  default: false
567
567
  },
568
568
  limit: {
@@ -588,16 +588,16 @@ export const toolSchemas = {
588
588
  properties: withMultiGraphParams({
589
589
  start_date: {
590
590
  type: 'string',
591
- description: 'Start date in ISO format (YYYY-MM-DD)',
591
+ description: 'Inclusive start date in ISO format (YYYY-MM-DD), in the server\'s local timezone.',
592
592
  },
593
593
  end_date: {
594
594
  type: 'string',
595
- description: 'Optional: End date in ISO format (YYYY-MM-DD)',
595
+ description: 'Optional: Inclusive end date in ISO format (YYYY-MM-DD), in the server\'s local timezone. Omit for no upper bound.',
596
596
  },
597
597
  type: {
598
598
  type: 'string',
599
599
  enum: ['created', 'modified', 'both'],
600
- description: 'Whether to search by creation date, modification date, or both',
600
+ description: 'Whether to search stored creation timestamps, modification timestamps, or either. With "both", each entity is returned once with its latest matching timestamp.',
601
601
  },
602
602
  scope: {
603
603
  type: 'string',
@@ -606,7 +606,7 @@ export const toolSchemas = {
606
606
  },
607
607
  include_content: {
608
608
  type: 'boolean',
609
- description: 'Whether to include the content of matching blocks/pages',
609
+ description: 'Whether to include matching block text or page titles. Defaults to true.',
610
610
  default: true,
611
611
  }
612
612
  }),
@@ -62,8 +62,8 @@ export class ToolHandlers {
62
62
  async searchByStatus(status, page_title_uid, include, exclude) {
63
63
  return this.searchOps.searchByStatus(status, page_title_uid, include, exclude);
64
64
  }
65
- async searchForTag(primary_tag, page_title_uid, near_tag) {
66
- return this.searchOps.searchForTag(primary_tag, page_title_uid, near_tag);
65
+ async searchForTag(primary_tag, page_title_uid, near_tag, case_sensitive) {
66
+ return this.searchOps.searchForTag(primary_tag, page_title_uid, near_tag, case_sensitive);
67
67
  }
68
68
  async searchBlockRefs(params) {
69
69
  return this.searchOps.searchBlockRefs(params);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roam-research-mcp",
3
- "version": "5.1.0",
3
+ "version": "5.1.1",
4
4
  "description": "MCP server and CLI for Roam Research",
5
5
  "private": false,
6
6
  "repository": {