Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

fix: resolve resource URIs that came from a search result (#169)

Brenno Ferrari7526dc723808
diff --git a/.claude/scripts/lib/mcp-exposure.ts b/.claude/scripts/lib/mcp-exposure.ts
index 5213d74..1e289f2 100644
--- a/.claude/scripts/lib/mcp-exposure.ts
+++ b/.claude/scripts/lib/mcp-exposure.ts
@@ -339,12 +339,102 @@ export function vaultRelKeyRaw(vaultRoot: string, full: string): string {
* inside the policy. Anything outside it returns null, which the caller reports
* as not-found — to this server a URI it does not serve is simply not a
* resource.
+ *
+ * `collection` is optional, and exists because a path a caller reads out of a
+ * `search` result is not a path this resolver would otherwise accept. qmd reports
+ * paths **prefixed with the collection name** and with **spaces replaced by
+ * dashes**, in directory names as well as filenames. So a note at
+ * `projects/notes/2026-01-02 Some Title.md` comes back as
+ * `myvault/projects/notes/2026-01-02-Some-Title.md`, and pasting that into a
+ * resource URI produced a bare not-found the caller had no way to diagnose.
+ * `expand` already tolerated the prefix, which left this the only surface
+ * rejecting the form the server's own search hands out.
+ *
+ * Three tiers, each ending in the same strict resolver, so exposure, traversal,
+ * extension, never-expose and realpath containment are re-run on whatever comes
+ * out. Nothing is loosened; only the spelling is repaired.
+ *
+ * RETURNS A REALPATH. Every other path in this module is built by joining the
+ * unresolved vault root, so a caller stripping a vault-root prefix from THIS
+ * return value must strip with the RESOLVED root. On macOS `/var` is
+ * `/private/var`, the prefix does not match, and `vaultRelKeyRaw` hands back an
+ * absolute filesystem path rather than a relative one — which is how a local
+ * path reached a `vault://note/...` URI during this change. Caught by macOS CI;
+ * it cannot reproduce on Windows or Linux.
*/
export function resolveResourceUri(
vaultRoot: string,
policy: ExposurePolicy,
uri: string,
+ collection?: string | null,
): string | null {
+ const direct = resolveExactResourceUri(vaultRoot, policy, uri);
+ if (direct) return direct;
+
+ // Tier 2: drop an exactly-matching collection prefix and retry.
+ let bare = String(uri);
+ if (collection) {
+ const prefix = `vault://note/${collection}/`;
+ if (bare.startsWith(prefix)) {
+ bare = `vault://note/${bare.slice(prefix.length)}`;
+ const stripped = resolveExactResourceUri(vaultRoot, policy, bare);
+ if (stripped) return stripped;
+ }
+ }
+
+ // Tier 3: de-slugify against the real tree.
+ const m = bare.match(/^vault:\/\/note\/(.+)$/);
+ if (!m?.[1]) return null;
+ let slug: string;
+ try {
+ slug = m[1]
+ .split("/")
+ .map((s) => decodeURIComponent(s))
+ .join("/");
+ } catch {
+ return null;
+ }
+ if (slug.includes("..") || slug.startsWith("/") || /^[A-Za-z]:/.test(slug)) return null;
+
+ const real = unslugPath(vaultRoot, slug);
+ if (!real) return null;
+ return resolveExactResourceUri(
+ vaultRoot,
+ policy,
+ `vault://note/${real.split("/").map(encodeURIComponent).join("/")}`,
+ );
+}
+
+/**
+ * Walk `slug` against the real tree, accepting a segment whose spaces became
+ * dashes. Returns the true vault-relative path, or null.
+ *
+ * Refuses when a segment is AMBIGUOUS. If both `A B.md` and `A-B.md` exist, the
+ * slug `A-B.md` cannot say which was meant, and guessing would silently serve
+ * the wrong note — worse than a not-found. Bounded work: one `readdir` per
+ * segment, and only after exact resolution has already failed.
+ */
+function unslugPath(vaultRoot: string, slug: string): string | null {
+ const parts = slug.split("/").filter(Boolean);
+ if (!parts.length) return null;
+
+ let acc = "";
+ for (const want of parts) {
+ let entries: string[];
+ try {
+ entries = readdirSync(join(vaultRoot, acc));
+ } catch {
+ return null;
+ }
+ const hits = entries.filter((e) => e === want || e.replace(/ /g, "-") === want);
+ if (hits.length !== 1) return null; // missing, or ambiguous
+ acc = acc ? `${acc}/${hits[0]}` : hits[0]!;
+ }
+ return acc;
+}
+
+/** The strict resolver. `resolveResourceUri` is this plus two repair attempts. */
+function resolveExactResourceUri(vaultRoot: string, policy: ExposurePolicy, uri: string): string | null {
const m = String(uri).match(/^vault:\/\/note\/(.+)$/);
if (!m?.[1]) return null;
diff --git a/.claude/scripts/lib/mcp-server.ts b/.claude/scripts/lib/mcp-server.ts
index 6250dac..82c64ac 100644
--- a/.claude/scripts/lib/mcp-server.ts
+++ b/.claude/scripts/lib/mcp-server.ts
@@ -12,7 +12,7 @@
* than an error.
*/
-import { readFileSync } from "node:fs";
+import { readFileSync, realpathSync } from "node:fs";
import { spawn, spawnSync } from "node:child_process";
import type { VaultContext } from "./mcp-context.ts";
@@ -24,6 +24,7 @@ import {
allowedSearchPaths,
listResources,
resolveResourceUri,
+ vaultRelKeyRaw,
} from "./mcp-exposure.ts";
import { expandNote } from "./mcp-graph.ts";
import { qmdSearch, type QmdClient } from "./mcp-qmd-client.ts";
@@ -138,6 +139,22 @@ export function createHandlers(deps: ServerDeps): Handlers {
// One cache per server, living exactly as long as the process that owns it.
const memoryIndex = createMemoryIndex(ctx.vaultRoot, ctx.memoryRoot);
+ // The vault root with symlinks resolved, computed once.
+ //
+ // Needed because `resolveResourceUri` returns a REALPATH, and on macOS the
+ // temp and home trees are reached through symlinks (`/var` is `/private/var`).
+ // Stripping a realpath prefix with the unresolved root silently fails to match,
+ // and `vaultRelKeyRaw` then returns its input unchanged — which is how an
+ // absolute filesystem path ended up inside a `vault://note/...` URI. Caught by
+ // macOS CI; invisible on Linux and Windows.
+ const vaultReal = (() => {
+ try {
+ return realpathSync(ctx.vaultRoot);
+ } catch {
+ return ctx.vaultRoot;
+ }
+ })();
+
/**
* The store, parsed, for READ paths. Lists and stats every file on every
* call; only the re-parse of an unchanged file is skipped.
@@ -621,15 +638,34 @@ export function createHandlers(deps: ServerDeps): Handlers {
"resources/read": async (id, params) => {
await session.identityReady();
const uri = String((params as { uri?: unknown } | undefined)?.uri ?? "");
- const full = resolveResourceUri(ctx.vaultRoot, policy, uri);
+
+ // The collection name is passed so a URI read straight out of a `search`
+ // result resolves. See resolveResourceUri for what qmd does to paths.
+ const full = resolveResourceUri(ctx.vaultRoot, policy, uri, ctx.qmdIndex);
if (!full) {
// Not-found rather than forbidden: to this server, a URI outside
// the served set is simply not a resource it has.
audit("resource_denied", { uri });
return session.fail(id, `no such resource: ${uri}`, -32602);
}
- audit("resource_read", { uri });
- session.ok(id, { contents: [{ uri, mimeType: "text/markdown", text: readFileSync(full, "utf8") }] });
+
+ // The canonical URI goes back, not the requested one, so a caller that
+ // arrived via a prefixed or slugified path learns the form that works.
+ // vaultRelKeyRaw, not vaultRelKey: the latter normalises case for
+ // comparison, and a URI has to round-trip to a real file. Against
+ // `vaultReal`, because `full` is a realpath.
+ const rel = vaultRelKeyRaw(vaultReal, full);
+ // `vaultRelKeyRaw` returns its input unchanged when the prefix does not
+ // match, so anything still absolute means we have no clean relative path.
+ // Echo the request rather than publish a filesystem path.
+ const served =
+ rel === full || rel.startsWith("/") || /^[A-Za-z]:/.test(rel)
+ ? uri
+ : `vault://note/${rel.split("/").map(encodeURIComponent).join("/")}`;
+ audit("resource_read", served === uri ? { uri } : { uri: served, from: uri });
+ session.ok(id, {
+ contents: [{ uri: served, mimeType: "text/markdown", text: readFileSync(full, "utf8") }],
+ });
},
"prompts/list": (id) => session.ok(id, { prompts: PROMPTS }),
diff --git a/.claude/scripts/tests/mcp-exposure.test.ts b/.claude/scripts/tests/mcp-exposure.test.ts
index fa3a933..2e232f3 100644
--- a/.claude/scripts/tests/mcp-exposure.test.ts
+++ b/.claude/scripts/tests/mcp-exposure.test.ts
@@ -404,6 +404,98 @@ describe("resolving a resource URI", () => {
});
});
+ // qmd reports paths PREFIXED with the collection name and with spaces replaced
+ // by dashes, in directory names as well as filenames. So a path read out of a
+ // `search` result names a file that does not exist, and pasting it into a
+ // resource URI produced a bare not-found. Both repairs re-enter the strict
+ // resolver, so these also pin that nothing was loosened.
+
+ test("a collection-prefixed URI resolves once the collection is known", () => {
+ withVault((dir) => {
+ stocked(dir);
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+ const uri = listResources(dir, policy).find((r) => r.uri.includes("Gotchas"))!.uri;
+ const prefixed = uri.replace("vault://note/", "vault://note/myvault/");
+
+ assert.equal(resolveResourceUri(dir, policy, prefixed), null, "refused without the collection");
+ assert.equal(
+ resolveResourceUri(dir, policy, prefixed, "myvault"),
+ resolveResourceUri(dir, policy, uri),
+ "same file once the collection is known",
+ );
+ });
+ });
+
+ test("a slugified path resolves back to the real file, directory names included", () => {
+ withVault((dir) => {
+ stocked(dir);
+ put(dir, "reference/Deep Folder/A Long Note.md", NOTE("the real one"));
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain", "reference"] });
+
+ const truth = resolveResourceUri(dir, policy, "vault://note/reference/Deep Folder/A Long Note.md");
+ assert.ok(truth, "sanity: the true path resolves");
+
+ for (const uri of [
+ "vault://note/reference/Deep Folder/A-Long-Note.md",
+ "vault://note/reference/Deep-Folder/A-Long-Note.md",
+ "vault://note/myvault/reference/Deep-Folder/A-Long-Note.md",
+ ]) {
+ assert.equal(resolveResourceUri(dir, policy, uri, "myvault"), truth, uri);
+ }
+ });
+ });
+
+ test("an ambiguous slug is refused rather than guessed", () => {
+ withVault((dir) => {
+ // Two sibling directories that slugify to the same thing, with the note in
+ // only one. The exact path cannot resolve, so repair runs and finds the
+ // segment matches both. Serving a note from a directory the caller did not
+ // name would be worse than a not-found.
+ put(dir, "reference/Deep Folder/A Long Note.md", NOTE("the real one"));
+ put(dir, "reference/Deep-Folder/Other Note.md", NOTE("a decoy"));
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["reference"] });
+
+ assert.equal(
+ resolveResourceUri(dir, policy, "vault://note/reference/Deep-Folder/A-Long-Note.md", "myvault"),
+ null,
+ "ambiguous directory segment must not be guessed",
+ );
+ assert.ok(
+ resolveResourceUri(dir, policy, "vault://note/reference/Deep Folder/A-Long-Note.md", "myvault"),
+ "unambiguous repair still works",
+ );
+ });
+ });
+
+ test("repair loosens nothing: scope, traversal and never-expose still decide", () => {
+ withVault((dir) => {
+ stocked(dir);
+ put(dir, "work/1-1/Some Person.md", NOTE("a 1:1 note"));
+ const policy = resolveExposure(dir, { mcp_exposed_roots: ["brain"] });
+
+ for (const uri of [
+ // out of scope, reached by slug and by prefix
+ "vault://note/work/1-1/Some-Person.md",
+ "vault://note/myvault/work/1-1/Some-Person.md",
+ "vault://note/myvault/work/1-1/Some Person.md",
+ // traversal, behind both repairs
+ "vault://note/myvault/brain/../work/1-1/Some-Person.md",
+ // only the exact collection name is stripped, and only once
+ "vault://note/other/brain/Gotchas.md",
+ "vault://note/myvault/myvault/brain/Gotchas.md",
+ ]) {
+ assert.equal(resolveResourceUri(dir, policy, uri, "myvault"), null, uri);
+ }
+
+ // A never-expose note stays refused when reached by its slug.
+ assert.equal(
+ resolveResourceUri(dir, policy, "vault://note/brain/Private-Thing.md", "myvault"),
+ null,
+ "private note refused via slug",
+ );
+ });
+ });
+
test("a URI naming an out-of-scope note is refused even though it is well-formed", () => {
withVault((dir) => {
stocked(dir);
diff --git a/.claude/scripts/tests/om-mcp.integration.test.ts b/.claude/scripts/tests/om-mcp.integration.test.ts
index c726282..14d84a7 100644
--- a/.claude/scripts/tests/om-mcp.integration.test.ts
+++ b/.claude/scripts/tests/om-mcp.integration.test.ts
@@ -74,6 +74,12 @@ before(async () => {
put("brain/Gotchas.md", '---\ndate: 2026-07-26\ndescription: "things that bit us"\n---\n\n# Gotchas\n\nSee [[Patterns]].\n');
put("brain/Patterns.md", '---\ndate: 2026-07-26\ndescription: "how we do things"\n---\n\n# Patterns\n\nRelated: [[Gotchas]].\n');
put("reference/Arch.md", '---\ndate: 2026-07-26\ndescription: "architecture"\n---\n\n# Arch\n');
+ // A spaced filename, because that is what qmd slugifies and therefore the only
+ // fixture that exercises the resource-URI repair end to end.
+ put(
+ "reference/Design Notes.md",
+ '---\ndate: 2026-07-26\ndescription: "design notes"\n---\n\n# Design Notes\n',
+ );
put("work/Secret.md", '---\ndate: 2026-07-26\ndescription: "CONFIDENTIAL"\n---\n\n# Secret\n');
put("work/atlas.md", "---\ndate: 2026-07-26\nplatforms: [ios]\n---\n\n# atlas\n");
@@ -162,7 +168,7 @@ describe("the om server on the wire", () => {
test("the resource listing honours the policy — work/ never appears", async () => {
const r = await call("resources/list");
const uris = ((r.result?.resources ?? []) as { uri: string }[]).map((x) => x.uri);
- assert.equal(uris.length, 3);
+ assert.equal(uris.length, 4); // brain x2, reference x2
assert.ok(!uris.some((u) => u.toLowerCase().includes("work")), uris.join(" "));
assert.ok(!uris.some((u) => u.toLowerCase().includes("secret")), uris.join(" "));
});
@@ -173,6 +179,51 @@ describe("the om server on the wire", () => {
assert.match(String(contents[0]?.text), /# Gotchas/);
});
+ // A URI minted by `resources/list` must survive a round trip unchanged.
+ // `resources/read` returns the CANONICAL uri rather than echoing the request,
+ // so if the two ever encoded differently every read would silently hand back a
+ // uri the caller did not ask for. They are built the same way today; this is
+ // what keeps that true.
+ test("a listed URI reads back with the same URI", async () => {
+ const list = await call("resources/list");
+ const uri = ((list.result?.resources ?? []) as { uri: string }[]).find((x) =>
+ x.uri.includes("Design"),
+ )!.uri;
+ assert.match(uri, /%20/, "sanity: the listed uri is percent-encoded");
+
+ const r = await call("resources/read", { uri });
+ const contents = (r.result?.contents ?? []) as { uri?: string; text?: string }[];
+ assert.equal(contents[0]?.uri, uri, "the uri came back unchanged");
+ assert.match(String(contents[0]?.text), /# Design Notes/);
+ });
+
+ // qmd reports paths PREFIXED with the collection name and with spaces turned
+ // into dashes. Both forms are unit-tested against the resolver directly; these
+ // two go over the wire, because the resolver could be perfect while the server
+ // forgot to pass the collection through — every unit test would still pass and
+ // the feature would be dead in production.
+ test("a collection-prefixed URI resolves, so the collection reaches the resolver", async () => {
+ const r = await call("resources/read", {
+ uri: "vault://note/om-int-test/reference/Design%20Notes.md",
+ });
+ const contents = (r.result?.contents ?? []) as { uri?: string; text?: string }[];
+ assert.match(String(contents[0]?.text), /# Design Notes/, JSON.stringify(r.error ?? {}));
+ assert.equal(contents[0]?.uri, "vault://note/reference/Design%20Notes.md", "canonical uri returned");
+ });
+
+ test("a slugified URI resolves and comes back canonical", async () => {
+ const r = await call("resources/read", {
+ uri: "vault://note/om-int-test/reference/Design-Notes.md",
+ });
+ const contents = (r.result?.contents ?? []) as { uri?: string; text?: string }[];
+ assert.match(String(contents[0]?.text), /# Design Notes/, JSON.stringify(r.error ?? {}));
+ assert.equal(
+ contents[0]?.uri,
+ "vault://note/reference/Design%20Notes.md",
+ "the caller learns the uri that works directly",
+ );
+ });
+
test("an unserved note is refused, and the error keeps the URI intact", async () => {
const r = await call("resources/read", { uri: "vault://note/work/Secret.md" });
assert.ok(r.error, "must refuse");