roam-research-mcp 5.0.1 → 5.1.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.
package/README.md CHANGED
@@ -307,7 +307,7 @@ ROAM_SYSTEM_WRITE_KEY=your-secret-key
307
307
  | `protected` | No | If `true`, writes require `ROAM_SYSTEM_WRITE_KEY` confirmation — **except on the default graph**, see below |
308
308
  | `memoriesTag` | No | Tag for `roam_remember`/`roam_recall` (overrides global default) |
309
309
 
310
- **Two kinds of access control (and how they differ)**
310
+ <a id="two-kinds-of-access-control-and-how-they-differ"></a>**Two kinds of access control (and how they differ)**
311
311
 
312
312
  The server has two independent locks. They're easy to mix up because both are "keys" — here's the plain version (both are **optional and off by default**):
313
313
 
@@ -320,7 +320,7 @@ The server has two independent locks. They're easy to mix up because both are "k
320
320
  | When you need it | Only if the server is reachable beyond your own machine (e.g. `-H 0.0.0.0`) | Whenever you want a guard against accidental edits to important graphs |
321
321
  | How it's sent | HTTP header: `Authorization: Bearer <token>` | A `write_key` argument on write tools / CLI commands |
322
322
 
323
- Think of a house: the **bearer token locks the front door** (keeps strangers out entirely), and the **write key locks a safe inside** (even someone already in the house needs it to change what's in the safe). On your own machine bound to `127.0.0.1`, the front door faces a wall — you don't need the bearer token there. The write key is still handy locally as an "are you sure?" guard, because **Roam has no undo**.
323
+ Think of a house: the **bearer token locks the front door** (keeps strangers out entirely), and the **write key locks a safe inside** (even someone already in the house needs it to change what's in the safe). On your own machine bound to `127.0.0.1`, the front door faces a wall, and a server without a token also turns away web pages that try to reach it by DNS rebinding (see `HTTP_ALLOWED_HOSTS` below), so you don't need the bearer token there. The write key is still handy locally as an "are you sure?" guard, because **Roam has no undo**.
324
324
 
325
325
  So: to mark a graph as needing the write key, set `protected: true` on it and configure `ROAM_SYSTEM_WRITE_KEY`; callers then pass a matching `write_key` for any write to that graph.
326
326
 
@@ -330,7 +330,9 @@ So: to mark a graph as needing the write key, set `protected: true` on it and co
330
330
  - `ROAM_MEMORIES_TAG`: Default tag for `roam_remember`/`roam_recall` (fallback when per-graph `memoriesTag` not set).
331
331
  - `HTTP_STREAM_PORT`: Port for the HTTP Stream transport (defaults to 8088). **`--server` mode only** — stdio mode opens no socket, so this is ignored there.
332
332
  - `HTTP_STREAM_HOST`: Host to bind the HTTP transport to (defaults to `127.0.0.1`, loopback-only). **`--server` mode only.** Set to `0.0.0.0` to expose on the LAN, and set `HTTP_AUTH_TOKEN` when you do.
333
- - `HTTP_AUTH_TOKEN`: Optional bearer token that locks the **whole** HTTP endpoint. Unset = open (fine for loopback). When set, every MCP request must send `Authorization: Bearer <token>` (`GET /health` stays open). Use it whenever you bind beyond `127.0.0.1`. Different from `ROAM_SYSTEM_WRITE_KEY` — see [Two kinds of access control](#two-kinds-of-access-control-and-how-they-differ).
333
+ - `HTTP_AUTH_TOKEN`: Optional bearer token that locks the **whole** HTTP endpoint. Unset = no token: the server then answers only requests addressed to `localhost`, an IP address, or a name in `HTTP_ALLOWED_HOSTS`, and only browser requests from an origin in `CORS_ORIGIN`. When set, every MCP request must send `Authorization: Bearer <token>` (`GET /health` stays open). Use it whenever you bind beyond `127.0.0.1`. Different from `ROAM_SYSTEM_WRITE_KEY` — see [Two kinds of access control](#two-kinds-of-access-control-and-how-they-differ).
334
+ - `HTTP_ALLOWED_HOSTS`: Hostnames a server **without** `HTTP_AUTH_TOKEN` answers to, beyond `localhost` and IP addresses (comma-separated; ports are ignored), e.g. `roam-mcp` for a Docker service name or `mybox.local`. A request addressed to any other name gets a 403. That is what stops a web page from reaching the server by pointing its own hostname at `127.0.0.1` (DNS rebinding). Ignored when `HTTP_AUTH_TOKEN` is set.
335
+ - `CORS_ORIGIN`: Browser origins allowed to call the HTTP server (comma-separated; defaults to `http://localhost:5678,https://roamresearch.com`; `*` allows any). Without `HTTP_AUTH_TOKEN`, a request from any other origin gets a 403.
334
336
 
335
337
  ### Running the Server
336
338
 
@@ -382,7 +384,7 @@ Point MCP clients at it with an HTTP transport config:
382
384
 
383
385
  Env vars (tokens, graphs) live with the **server** process, not the client config.
384
386
 
385
- **Securing an exposed server (two layers):**
387
+ <a id="securing-an-exposed-server-two-layers"></a>**Securing an exposed server (two layers):**
386
388
  If you bind beyond loopback (`-H 0.0.0.0`), add the perimeter lock:
387
389
 
388
390
  ```bash
@@ -418,9 +420,16 @@ curl -s http://127.0.0.1:8088/health # verify
418
420
  **3. Docker**
419
421
 
420
422
  ```bash
421
- docker run -p 8088:8088 --env-file .env roam-research-mcp --server
423
+ docker build -t roam-research-mcp .
424
+ docker run --init -p 127.0.0.1:8088:8088 \
425
+ -e HTTP_STREAM_HOST=0.0.0.0 -e HTTP_STREAM_PORT=8088 \
426
+ --env-file .env roam-research-mcp --server
422
427
  ```
423
428
 
429
+ Set `HTTP_AUTH_TOKEN` to a random secret in `.env` before running; MCP requests must include `Authorization: Bearer <token>`. The published port is loopback-only by default. For remote access, follow [Securing an exposed server](#securing-an-exposed-server-two-layers) and intentionally publish on the required host address.
430
+
431
+ The `-e` values win over `--env-file`, so the server listens on the published port whatever `.env` says. `--init` lets `docker stop` end the server straight away instead of killing it after 10 seconds.
432
+
424
433
  ### Configuring in LLMs
425
434
 
426
435
  **Claude Desktop / Cline:**
@@ -5,6 +5,7 @@ import { q } from '@roam-research/roam-api-sdk';
5
5
  import { capitalizeWords } from '../../tools/helpers/text.js';
6
6
  import { formatRoamDate } from '../../utils/helpers.js';
7
7
  import { pageUidCache } from '../../cache/page-uid-cache.js';
8
+ import { ednString } from '../../shared/datalog.js';
8
9
  /**
9
10
  * Resolve a page title to its UID, trying multiple case variations
10
11
  */
@@ -20,7 +21,7 @@ export async function resolvePageUid(graph, title) {
20
21
  capitalizeWords(title),
21
22
  title.toLowerCase()
22
23
  ];
23
- const orClause = variations.map(v => `[?e :node/title "${v}"]`).join(' ');
24
+ const orClause = variations.map(v => `[?e :node/title ${ednString(v)}]`).join(' ');
24
25
  const searchQuery = `[:find ?uid .
25
26
  :where [?e :block/uid ?uid]
26
27
  (or ${orClause})]`;
@@ -1,6 +1,7 @@
1
1
  import * as dotenv from 'dotenv';
2
2
  import { dirname, join } from 'path';
3
3
  import { existsSync } from 'fs';
4
+ import { hostnameOf } from '../utils/host-validation.js';
4
5
  // Get the project root from the script path
5
6
  const scriptPath = process.argv[1]; // Full path to the running script
6
7
  const projectRoot = dirname(dirname(scriptPath)); // Go up two levels from build/index.js
@@ -16,12 +17,20 @@ const HTTP_STREAM_PORT = process.env.HTTP_STREAM_PORT || '8088';
16
17
  const HTTP_STREAM_HOST = process.env.HTTP_STREAM_HOST || '127.0.0.1';
17
18
  // Optional transport-level bearer token (authentication). When set, every HTTP
18
19
  // MCP request must send `Authorization: Bearer <token>` (the /health probe stays
19
- // open). Unset = open, i.e. unchanged. This is the perimeter lock; it is separate
20
+ // open). Unset = no token, and the server refuses DNS-rebinding requests instead
21
+ // (see utils/host-validation.ts). This is the perimeter lock; it is separate
20
22
  // from ROAM_SYSTEM_WRITE_KEY, which is per-graph write authorization.
21
23
  const HTTP_AUTH_TOKEN = process.env.HTTP_AUTH_TOKEN;
22
24
  const CORS_ORIGINS = (process.env.CORS_ORIGIN || 'http://localhost:5678,https://roamresearch.com')
23
25
  .split(',')
24
26
  .map(origin => origin.trim());
27
+ // Hostnames, beyond `localhost` and IP addresses, that a server without a token
28
+ // answers to (comma-separated, ports ignored), e.g. a Docker service name.
29
+ // Ignored when HTTP_AUTH_TOKEN is set.
30
+ const HTTP_ALLOWED_HOSTS = (process.env.HTTP_ALLOWED_HOSTS || '')
31
+ .split(',')
32
+ .map(host => hostnameOf(host))
33
+ .filter(Boolean);
25
34
  // Re-export for backwards compatibility with single-graph mode
26
35
  // These are still used by CLI commands and for validation
27
36
  const API_TOKEN = process.env.ROAM_API_TOKEN;
@@ -89,4 +98,4 @@ export function validateEnvironment() {
89
98
  }
90
99
  }
91
100
  }
92
- export { API_TOKEN, GRAPH_NAME, HTTP_STREAM_PORT, HTTP_STREAM_HOST, HTTP_AUTH_TOKEN, CORS_ORIGINS, ROAM_GRAPHS, ROAM_DEFAULT_GRAPH };
101
+ export { API_TOKEN, GRAPH_NAME, HTTP_STREAM_PORT, HTTP_STREAM_HOST, HTTP_AUTH_TOKEN, CORS_ORIGINS, HTTP_ALLOWED_HOSTS, ROAM_GRAPHS, ROAM_DEFAULT_GRAPH };
@@ -3,6 +3,7 @@
3
3
  *
4
4
  * Converts parsed query nodes into Datalog WHERE clauses
5
5
  */
6
+ import { ednString } from '../shared/datalog.js';
6
7
  export class DatalogGenerator {
7
8
  constructor() {
8
9
  this.refCounter = 0;
@@ -117,7 +118,7 @@ export class DatalogGenerator {
117
118
  const refVar = `?ref-${this.refCounter++}`;
118
119
  // A tag reference means the block has :block/refs pointing to a page with that title
119
120
  const where = [
120
- `[${refVar} :node/title "${this.escapeString(tagName)}"]`,
121
+ `[${refVar} :node/title ${ednString(tagName)}]`,
121
122
  `[${blockVar} :block/refs ${refVar}]`
122
123
  ];
123
124
  return { where, inputs: [], inputValues: [] };
@@ -127,7 +128,7 @@ export class DatalogGenerator {
127
128
  // This can be through :block/refs or embedded in the string
128
129
  const refVar = `?block-ref-${this.refCounter++}`;
129
130
  const where = [
130
- `[${refVar} :block/uid "${this.escapeString(uid)}"]`,
131
+ `[${refVar} :block/uid ${ednString(uid)}]`,
131
132
  `[${blockVar} :block/refs ${refVar}]`
132
133
  ];
133
134
  return { where, inputs: [], inputValues: [] };
@@ -135,7 +136,7 @@ export class DatalogGenerator {
135
136
  generateSearch(text, blockVar) {
136
137
  // Search uses clojure.string/includes? to find text in block content
137
138
  const where = [
138
- `[(clojure.string/includes? ?block-str "${this.escapeString(text)}")]`
139
+ `[(clojure.string/includes? ?block-str ${ednString(text)})]`
139
140
  ];
140
141
  return { where, inputs: [], inputValues: [] };
141
142
  }
@@ -152,20 +153,19 @@ export class DatalogGenerator {
152
153
  generateBy(user, blockVar) {
153
154
  // "by" matches blocks created OR edited by the user
154
155
  // Uses or-join to match either condition
155
- const escapedUser = this.escapeString(user);
156
156
  const where = [
157
157
  `(or-join [${blockVar}]
158
158
  (and [${blockVar} :create/user ?by-creator]
159
- [?by-creator :user/display-name "${escapedUser}"])
159
+ [?by-creator :user/display-name ${ednString(user)}])
160
160
  (and [${blockVar} :edit/user ?by-editor]
161
- [?by-editor :user/display-name "${escapedUser}"]))`
161
+ [?by-editor :user/display-name ${ednString(user)}]))`
162
162
  ];
163
163
  return { where, inputs: [], inputValues: [] };
164
164
  }
165
165
  generateUserClause(user, blockVar, attribute, varName) {
166
166
  const where = [
167
167
  `[${blockVar} ${attribute} ?${varName}]`,
168
- `[?${varName} :user/display-name "${this.escapeString(user)}"]`
168
+ `[?${varName} :user/display-name ${ednString(user)}]`
169
169
  ];
170
170
  return { where, inputs: [], inputValues: [] };
171
171
  }
@@ -277,9 +277,6 @@ export class DatalogGenerator {
277
277
  return date.getTime();
278
278
  }
279
279
  }
280
- escapeString(str) {
281
- return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
282
- }
283
280
  }
284
281
  /**
285
282
  * Build a complete Datalog query from generated clauses
@@ -1,6 +1,7 @@
1
1
  import { q } from '@roam-research/roam-api-sdk';
2
2
  import { BaseSearchHandler } from './types.js';
3
3
  import { SearchUtils } from './utils.js';
4
+ import { ednString } from '../shared/datalog.js';
4
5
  export class TagSearchHandler extends BaseSearchHandler {
5
6
  constructor(graph, params) {
6
7
  super(graph);
@@ -55,12 +56,12 @@ export class TagSearchHandler extends BaseSearchHandler {
55
56
  if (nearTagUid) {
56
57
  queryWhereClauses += `
57
58
  [?b :block/refs ?near-tag-page]
58
- [?near-tag-page :block/uid "${nearTagUid}"]`;
59
+ [?near-tag-page :block/uid ${ednString(nearTagUid)}]`;
59
60
  }
60
61
  if (excludeTagUid) {
61
62
  queryWhereClauses += `
62
63
  (not [?b :block/refs ?exclude-tag-page])
63
- [?exclude-tag-page :block/uid "${excludeTagUid}"]`;
64
+ [?exclude-tag-page :block/uid ${ednString(excludeTagUid)}]`;
64
65
  }
65
66
  if (targetPageUid) {
66
67
  inClause += ` ?target-page-uid`;
@@ -1,6 +1,7 @@
1
1
  import { q } from '@roam-research/roam-api-sdk';
2
2
  import { BaseSearchHandler } from './types.js';
3
3
  import { SearchUtils } from './utils.js';
4
+ import { ednString } from '../shared/datalog.js';
4
5
  export class TextSearchHandler extends BaseSearchHandler {
5
6
  constructor(graph, params) {
6
7
  super(graph);
@@ -90,14 +91,14 @@ export class TextSearchHandler extends BaseSearchHandler {
90
91
  :where
91
92
  [?e :node/title ?title]
92
93
  [?e :block/uid ?uid]
93
- [(clojure.string/starts-with? ?title "${namespace}")]]`;
94
+ [(clojure.string/starts-with? ?title ${ednString(namespace)})]]`;
94
95
  const rawResults = await q(this.graph, queryStr, []);
95
96
  // Get total count
96
97
  const countQueryStr = `[:find (count ?e)
97
98
  :in $
98
99
  :where
99
100
  [?e :node/title ?title]
100
- [(clojure.string/starts-with? ?title "${namespace}")]]`;
101
+ [(clojure.string/starts-with? ?title ${ednString(namespace)})]]`;
101
102
  const totalCountResults = await q(this.graph, countQueryStr, []);
102
103
  const totalCount = totalCountResults[0] ? totalCountResults[0][0] : 0;
103
104
  // Format results: page UID as block_uid, title as content
@@ -1,6 +1,7 @@
1
1
  import { ErrorCode, McpError } from '@modelcontextprotocol/sdk/types.js';
2
2
  import { q } from '@roam-research/roam-api-sdk';
3
3
  import { normalizeToRoamDate } from '../utils/helpers.js';
4
+ import { ednString } from '../shared/datalog.js';
4
5
  export class SearchUtils {
5
6
  /**
6
7
  * Find a page by title or UID.
@@ -22,7 +23,7 @@ export class SearchUtils {
22
23
  }
23
24
  }
24
25
  // Try as UID
25
- const uidQuery = `[:find ?uid :where [?e :block/uid "${titleOrUid}"] [?e :block/uid ?uid]]`;
26
+ const uidQuery = `[:find ?uid :where [?e :block/uid ${ednString(titleOrUid)}] [?e :block/uid ?uid]]`;
26
27
  const uidResults = await q(graph, uidQuery, []);
27
28
  if (!uidResults || uidResults.length === 0) {
28
29
  throw new McpError(ErrorCode.InvalidRequest, `Page with title/UID "${titleOrUid}" not found`);
@@ -117,7 +118,7 @@ export class SearchUtils {
117
118
  return new Map();
118
119
  }
119
120
  // Build OR clause for all UIDs
120
- const uidClauses = blockUids.map(uid => `[?b :block/uid "${uid}"]`).join(' ');
121
+ const uidClauses = blockUids.map(uid => `[?b :block/uid ${ednString(uid)}]`).join(' ');
121
122
  const queryStr = `[:find ?block-uid ?tag-title
122
123
  :where
123
124
  (or ${uidClauses})
@@ -159,7 +160,7 @@ export class SearchUtils {
159
160
  */
160
161
  static buildTextSearchClause(text, variable, caseSensitive = false) {
161
162
  const variations = this.getCaseVariations(text, caseSensitive);
162
- const clauses = variations.map(term => `[(clojure.string/includes? ${variable} "${term}")]`);
163
+ const clauses = variations.map(term => `[(clojure.string/includes? ${variable} ${ednString(term)})]`);
163
164
  return `(or ${clauses.join(' ')})`;
164
165
  }
165
166
  /**
@@ -171,7 +172,7 @@ export class SearchUtils {
171
172
  */
172
173
  static buildTagMatchClause(tag, variable, caseSensitive = false) {
173
174
  const variations = this.getCaseVariations(tag, caseSensitive);
174
- const clauses = variations.map(t => `[${variable} :node/title "${t}"]`);
175
+ const clauses = variations.map(t => `[${variable} :node/title ${ednString(t)}]`);
175
176
  return `(or ${clauses.join(' ')})`;
176
177
  }
177
178
  /**
@@ -4,6 +4,7 @@ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/
4
4
  import { CallToolRequestSchema, ErrorCode, ListResourcesRequestSchema, ReadResourceRequestSchema, McpError, ListToolsRequestSchema, ListPromptsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
5
  import { HTTP_STREAM_PORT, HTTP_STREAM_HOST, HTTP_AUTH_TOKEN, validateEnvironment } from '../config/environment.js';
6
6
  import { isBearerAuthorized } from '../utils/auth.js';
7
+ import { rebindingRefusal } from '../utils/host-validation.js';
7
8
  import { RoamError, toErrorResult } from '../shared/errors.js';
8
9
  import { createRegistryFromEnv } from '../config/graph-registry.js';
9
10
  import { toolSchemas } from '../tools/schemas.js';
@@ -13,7 +14,7 @@ import { join, dirname } from 'node:path';
13
14
  import { createServer } from 'node:http';
14
15
  import { fileURLToPath } from 'node:url';
15
16
  import { isPortInUse } from '../utils/net.js';
16
- import { CORS_ORIGINS } from '../config/environment.js';
17
+ import { CORS_ORIGINS, HTTP_ALLOWED_HOSTS } from '../config/environment.js';
17
18
  const __filename = fileURLToPath(import.meta.url);
18
19
  const __dirname = dirname(__filename);
19
20
  // Read package.json to get the version
@@ -334,6 +335,21 @@ export class RoamServer {
334
335
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, Mcp-Session-Id, MCP-Protocol-Version, Last-Event-ID');
335
336
  res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id');
336
337
  res.setHeader('Access-Control-Allow-Credentials', 'true');
338
+ // Without a token, refuse what a DNS-rebinding web page sends: a Host
339
+ // this server doesn't answer to, or an Origin CORS_ORIGIN doesn't allow.
340
+ // Checked before /health, which lists the graph names.
341
+ if (!HTTP_AUTH_TOKEN) {
342
+ const refusal = rebindingRefusal(req, HTTP_ALLOWED_HOSTS, CORS_ORIGINS);
343
+ if (refusal) {
344
+ res.writeHead(403, { 'Content-Type': 'application/json' });
345
+ res.end(JSON.stringify({
346
+ jsonrpc: '2.0',
347
+ error: { code: -32001, message: `Forbidden: ${refusal}` },
348
+ id: null,
349
+ }));
350
+ return;
351
+ }
352
+ }
337
353
  // Handle preflight OPTIONS requests
338
354
  if (req.method === 'OPTIONS') {
339
355
  res.writeHead(204); // No Content
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Datalog query text helpers.
3
+ */
4
+ /**
5
+ * Render a value as a Datalog (EDN) string literal, quotes included.
6
+ *
7
+ * Every value placed inside a query string goes through this. Interpolating
8
+ * it raw lets a `"` close the literal early: `Alex "Sandy" Pentland` becomes
9
+ * `"Alex "Sandy" Pentland"`, which Roam rejects with IndexOutOfBoundsException,
10
+ * and a `\` is read as the start of an escape. Prefer binding the value with
11
+ * `:in` where the query shape allows; this is for the places it does not,
12
+ * such as an `or` over several case variations.
13
+ */
14
+ export function ednString(value) {
15
+ return `"${value.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
16
+ }
@@ -6,6 +6,7 @@ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
6
6
  import { formatRoamDate, normalizeToRoamDate } from '../../utils/helpers.js';
7
7
  import { pageUidCache } from '../../cache/page-uid-cache.js';
8
8
  import { capitalizeWords } from './text.js';
9
+ import { ednString } from '../../shared/datalog.js';
9
10
  /**
10
11
  * Find a page UID by title with case variation matching and caching.
11
12
  * Tries: original, capitalized words, lowercase.
@@ -31,7 +32,7 @@ export async function getPageUid(graph, title) {
31
32
  }
32
33
  }
33
34
  // Query database with OR clause for all variations
34
- const orClause = variations.map(v => `[?e :node/title "${v}"]`).join(' ');
35
+ const orClause = variations.map(v => `[?e :node/title ${ednString(v)}]`).join(' ');
35
36
  const searchQuery = `[:find ?uid .
36
37
  :where [?e :block/uid ?uid]
37
38
  (or ${orClause})]`;
@@ -110,7 +111,7 @@ export async function findOrCreatePage(graph, titleOrUid, options = {}) {
110
111
  }
111
112
  // If not found as title, try as UID
112
113
  const uidQuery = `[:find ?uid
113
- :where [?e :block/uid "${titleOrUid}"]
114
+ :where [?e :block/uid ${ednString(titleOrUid)}]
114
115
  [?e :block/uid ?uid]]`;
115
116
  const uidResult = await q(graph, uidQuery, []);
116
117
  if (uidResult && uidResult.length > 0) {
@@ -3,6 +3,7 @@ import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
3
3
  import { resolveBlockRefs } from '../helpers/refs.js';
4
4
  import { fetchChildrenByDepth } from '../helpers/fetch-children.js';
5
5
  import { pruneHiddenBlocks, isHiddenBlockString } from '../helpers/hidden.js';
6
+ import { ednString } from '../../shared/datalog.js';
6
7
  export class BlockRetrievalOperations {
7
8
  constructor(graph) {
8
9
  this.graph = graph;
@@ -41,7 +42,7 @@ export class BlockRetrievalOperations {
41
42
  if (include_ancestors) {
42
43
  const ancestorQuery = `[:find (pull ?b [:block/uid :block/string
43
44
  {:block/parents [:block/uid :block/string :node/title]}])
44
- :where [?b :block/uid "${block_uid}"]]`;
45
+ :where [?b :block/uid ${ednString(block_uid)}]]`;
45
46
  const ancestorResults = await q(this.graph, ancestorQuery, []);
46
47
  if (ancestorResults && ancestorResults.length > 0) {
47
48
  const blockData = ancestorResults[0][0] || ancestorResults[0];
@@ -1,5 +1,6 @@
1
1
  import { q, moveBlock as moveRoamBlock } from '@roam-research/roam-api-sdk';
2
2
  import { McpError, ErrorCode } from '@modelcontextprotocol/sdk/types.js';
3
+ import { ednString } from '../../shared/datalog.js';
3
4
  export class BlockOperations {
4
5
  constructor(graph) {
5
6
  this.graph = graph;
@@ -13,7 +14,7 @@ export class BlockOperations {
13
14
  }
14
15
  // Verify the block exists
15
16
  const blockQuery = `[:find ?uid .
16
- :where [?b :block/uid "${block_uid}"]
17
+ :where [?b :block/uid ${ednString(block_uid)}]
17
18
  [?b :block/uid ?uid]]`;
18
19
  const blockExists = await q(this.graph, blockQuery, []);
19
20
  if (!blockExists) {
@@ -5,6 +5,7 @@ import { findOrCreatePage, getPageUid, getOrCreateTodayPage } from '../helpers/p
5
5
  import { executeBatch } from '../helpers/batch-utils.js';
6
6
  import { parseMarkdown, nestUnderHeadings, convertToRoamActions, convertToRoamActionsWithBlocks, convertToRoamMarkdown } from '../../markdown-utils.js';
7
7
  import { executeStagedBatch } from '../../shared/staged-batch.js';
8
+ import { ednString } from '../../shared/datalog.js';
8
9
  // Threshold for skipping child fetch during verification
9
10
  const VERIFICATION_THRESHOLD = 5;
10
11
  /**
@@ -38,9 +39,9 @@ export class OutlineOperations {
38
39
  async findBlockWithRetry(pageUid, blockString, maxRetries = 2, initialDelay = 1000) {
39
40
  // Use only the most reliable query strategy (direct page and string match)
40
41
  const query = `[:find ?b-uid ?order
41
- :where [?p :block/uid "${pageUid}"]
42
+ :where [?p :block/uid ${ednString(pageUid)}]
42
43
  [?b :block/page ?p]
43
- [?b :block/string "${blockString}"]
44
+ [?b :block/string ${ednString(blockString)}]
44
45
  [?b :block/order ?order]
45
46
  [?b :block/uid ?b-uid]]`;
46
47
  for (let retry = 0; retry < maxRetries; retry++) {
@@ -201,7 +202,7 @@ export class OutlineOperations {
201
202
  if (this.isValidUid(block_text_uid)) {
202
203
  // First try to find block by UID
203
204
  const uidQuery = `[:find ?uid
204
- :where [?e :block/uid "${block_text_uid}"]
205
+ :where [?e :block/uid ${ednString(block_text_uid)}]
205
206
  [?e :block/uid ?uid]]`;
206
207
  const uidResult = await q(this.graph, uidQuery, []);
207
208
  if (uidResult && uidResult.length > 0) {
@@ -321,7 +322,7 @@ export class OutlineOperations {
321
322
  let targetPageUid = page_uid;
322
323
  // If page_uid is provided, verify it exists
323
324
  if (page_uid) {
324
- const verifyQuery = `[:find ?uid :where [?e :block/uid "${page_uid}"] [?e :block/uid ?uid]]`;
325
+ const verifyQuery = `[:find ?uid :where [?e :block/uid ${ednString(page_uid)}] [?e :block/uid ?uid]]`;
325
326
  const verifyResult = await q(this.graph, verifyQuery, []);
326
327
  if (!verifyResult || verifyResult.length === 0) {
327
328
  throw new McpError(ErrorCode.InvalidRequest, `Page/block with UID "${page_uid}" not found`);
@@ -12,6 +12,7 @@ import { pageUidCache } from '../../cache/page-uid-cache.js';
12
12
  import { buildTableActions } from './table.js';
13
13
  import { BatchOperations } from './batch.js';
14
14
  import { parseExistingBlocks, pruneHiddenExistingBlocks, countHiddenExistingBlocks, flattenExistingBlocks, markdownToBlocks, diffBlockTrees, generateBatchActions, getDiffStats, isDiffEmpty, summarizeActions, } from '../../diff/index.js';
15
+ import { ednString } from '../../shared/datalog.js';
15
16
  // Helper to get ordinal suffix for dates
16
17
  function getOrdinalSuffix(day) {
17
18
  if (day > 3 && day < 21)
@@ -105,7 +106,7 @@ export class PageOperations {
105
106
  const year = today.getFullYear();
106
107
  const dailyPageTitle = `${month} ${day}${getOrdinalSuffix(day)}, ${year}`;
107
108
  // Get or create daily page UID
108
- const dailyPageQuery = `[:find ?uid . :where [?e :node/title "${dailyPageTitle}"] [?e :block/uid ?uid]]`;
109
+ const dailyPageQuery = `[:find ?uid . :where [?e :node/title ${ednString(dailyPageTitle)}] [?e :block/uid ?uid]]`;
109
110
  let dailyPageUid = await q(this.graph, dailyPageQuery, []);
110
111
  if (!dailyPageUid) {
111
112
  // Create daily page first
@@ -149,7 +150,7 @@ export class PageOperations {
149
150
  // Idempotency check: If page already has content, skip adding more
150
151
  // This prevents duplicate content when the tool is called twice
151
152
  const existingBlocksQuery = `[:find (count ?b) .
152
- :where [?p :block/uid "${pageUid}"]
153
+ :where [?p :block/uid ${ednString(pageUid)}]
153
154
  [?p :block/children ?b]]`;
154
155
  const existingBlockCountResult = await q(this.graph, existingBlocksQuery, []);
155
156
  const existingBlockCount = typeof existingBlockCountResult === 'number' ? existingBlockCountResult : 0;
@@ -343,7 +344,7 @@ export class PageOperations {
343
344
  return null;
344
345
  }
345
346
  // First get the page title
346
- const titleQuery = `[:find ?title . :where [?e :block/uid "${uid}"] [?e :node/title ?title]]`;
347
+ const titleQuery = `[:find ?title . :where [?e :block/uid ${ednString(uid)}] [?e :node/title ?title]]`;
347
348
  const title = await q(this.graph, titleQuery, []);
348
349
  if (!title) {
349
350
  return null;
@@ -675,7 +676,7 @@ export class PageOperations {
675
676
  :block/heading
676
677
  {:block/children ...}
677
678
  ]) .
678
- :where [?page :block/uid "${pageUid}"]]`;
679
+ :where [?page :block/uid ${ednString(pageUid)}]]`;
679
680
  const pageData = await q(this.graph, blocksQuery, []);
680
681
  if (!pageData) {
681
682
  throw new McpError(ErrorCode.InternalError, `Failed to fetch page data for "${title}"`);
@@ -0,0 +1,56 @@
1
+ import { isIP } from 'node:net';
2
+ /**
3
+ * DNS-rebinding checks for an HTTP server running WITHOUT a bearer token.
4
+ *
5
+ * A web page can point its own hostname at 127.0.0.1 after it loads. The
6
+ * browser then treats this server as same-origin, so CORS never applies and
7
+ * the page can call every tool. Two headers still give it away: `Host` carries
8
+ * the page's hostname rather than one this server answers to, and `Origin`
9
+ * names the page. With a token set none of this is needed: the page cannot
10
+ * authenticate.
11
+ */
12
+ /**
13
+ * The hostname in a Host header or an allow-list entry: port and IPv6
14
+ * brackets removed, lowercased, trailing dot dropped.
15
+ */
16
+ export function hostnameOf(host) {
17
+ const value = host.trim().toLowerCase();
18
+ if (value.startsWith('[')) {
19
+ const end = value.indexOf(']');
20
+ return end === -1 ? value : value.slice(1, end);
21
+ }
22
+ const colon = value.lastIndexOf(':');
23
+ return (colon === -1 ? value : value.slice(0, colon)).replace(/\.$/, '');
24
+ }
25
+ /**
26
+ * `localhost` and IP addresses always pass: a rebinding page can only put a
27
+ * hostname it controls in the header, never an IP. Anything else must be
28
+ * listed. A missing Host passes too, since every browser sends one.
29
+ */
30
+ function isAllowedHost(host, allowedHosts) {
31
+ if (!host)
32
+ return true;
33
+ const name = hostnameOf(host);
34
+ return name === 'localhost' || isIP(name) !== 0 || allowedHosts.includes(name);
35
+ }
36
+ /** No Origin (not a browser, or a same-origin GET), or one CORS_ORIGIN allows. */
37
+ function isAllowedOrigin(origin, corsOrigins) {
38
+ if (!origin)
39
+ return true;
40
+ return corsOrigins.includes('*') || corsOrigins.includes(origin);
41
+ }
42
+ /**
43
+ * Why a request to a server without a bearer token must be refused, or null if
44
+ * it may be answered. Preflights skip the Origin check: the CORS headers
45
+ * already decide what a browser may do after one.
46
+ */
47
+ export function rebindingRefusal(req, allowedHosts, corsOrigins) {
48
+ const { host, origin } = req.headers;
49
+ if (!isAllowedHost(host, allowedHosts)) {
50
+ return `Host ${JSON.stringify(host)} is not allowed: add its name to HTTP_ALLOWED_HOSTS, or set HTTP_AUTH_TOKEN`;
51
+ }
52
+ if (req.method !== 'OPTIONS' && !isAllowedOrigin(origin, corsOrigins)) {
53
+ return `Origin ${JSON.stringify(origin)} is not allowed: add it to CORS_ORIGIN, or set HTTP_AUTH_TOKEN`;
54
+ }
55
+ return null;
56
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "roam-research-mcp",
3
- "version": "5.0.1",
3
+ "version": "5.1.0",
4
4
  "description": "MCP server and CLI for Roam Research",
5
5
  "private": false,
6
6
  "repository": {