obsidian-mcp 2.2.1

MCP server for Obsidian vaults — direct filesystem access for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
//! Note CRUD tools: read, create, edit, delete, rename, move.

use std::path::Path;

use rmcp::ErrorData;
use rmcp::model::ErrorCode;
use schemars::JsonSchema;
use serde::Deserialize;

use crate::models::{PatchOperation, PatchRequest, PatchTargetType};
use crate::vault::Vault;

// ── Parameter structs ───────────────────────────────────────────────

#[derive(Deserialize, JsonSchema, Default)]
pub struct NoteReadParams {
    /// Path to the note, relative to vault root (e.g. "folder/note.md").
    pub path: String,
}

#[derive(Deserialize, JsonSchema, Default)]
pub struct NoteCreateParams {
    /// Path for the new note, relative to vault root. Parent dirs are created automatically.
    pub path: String,
    /// Initial body content. Defaults to empty.
    #[serde(default)]
    pub content: Option<String>,
    /// Optional YAML frontmatter as a JSON object (e.g. `{"tags": ["rust"], "draft": true}`).
    #[serde(default)]
    pub frontmatter: Option<serde_json::Value>,
}

#[derive(Deserialize, JsonSchema, Default)]
pub struct NoteWriteParams {
    /// Path to the note, relative to vault root.
    pub path: String,
    /// New content that replaces the entire note.
    pub content: String,
}

#[derive(Deserialize, JsonSchema, Default)]
pub struct NoteInsertParams {
    /// Path to the note, relative to vault root.
    pub path: String,
    /// Content to insert.
    pub content: String,
    /// Where to insert: `"end"` (default) appends after existing content; `"beginning"` inserts after frontmatter (or at the very start if no frontmatter).
    #[serde(default)]
    pub position: Option<String>,
}

#[derive(Deserialize, JsonSchema)]
pub struct NotePatchParams {
    /// Path to the note, relative to vault root.
    pub path: String,
    /// Patch operation: `append`, `prepend`, or `replace`.
    pub operation: PatchOperation,
    /// Target type: `heading`, `block`, or `frontmatter`.
    pub target_type: PatchTargetType,
    /// Target identifier — heading text, block ID, or frontmatter field name.
    pub target: String,
    /// Content to insert or replace with.
    pub content: String,
}

impl Default for NotePatchParams {
    fn default() -> Self {
        Self {
            path: String::new(),
            operation: PatchOperation::Append,
            target_type: PatchTargetType::Heading,
            target: String::new(),
            content: String::new(),
        }
    }
}

#[derive(Deserialize, JsonSchema, Default)]
pub struct NoteDeleteParams {
    /// Path to the note, relative to vault root.
    pub path: String,
    /// Must be `true` to confirm deletion — a safety check to prevent accidental data loss.
    pub confirm: bool,
}

#[derive(Deserialize, JsonSchema, Default)]
pub struct NoteMoveParams {
    /// Current path of the note, relative to vault root.
    pub from: String,
    /// Destination path, relative to vault root.
    pub to: String,
}

// ── Handler functions ───────────────────────────────────────────────

pub async fn note_read(vault: &Vault, params: NoteReadParams) -> Result<String, ErrorData> {
    Ok(vault.read_note(Path::new(&params.path))?)
}

pub async fn note_create(vault: &Vault, params: NoteCreateParams) -> Result<String, ErrorData> {
    vault.create_note(
        Path::new(&params.path),
        params.content.as_deref().unwrap_or(""),
        params.frontmatter.as_ref(),
    )?;
    Ok(format!("Created note: {}", params.path))
}

pub async fn note_write(vault: &Vault, params: NoteWriteParams) -> Result<String, ErrorData> {
    vault.write_note(Path::new(&params.path), &params.content)?;
    Ok(format!("Written to: {}", params.path))
}

pub async fn note_insert(vault: &Vault, params: NoteInsertParams) -> Result<String, ErrorData> {
    let position = params.position.as_deref().unwrap_or("end");

    if position.eq_ignore_ascii_case("end") {
        vault.append_note(Path::new(&params.path), &params.content)?;
        Ok(format!("Inserted into: {}", params.path))
    } else if position.eq_ignore_ascii_case("beginning") {
        vault.prepend_note(Path::new(&params.path), &params.content)?;
        Ok(format!("Inserted into: {}", params.path))
    } else {
        Err(ErrorData::new(
            ErrorCode::INVALID_PARAMS,
            format!("Unknown position '{position}'. Valid values: \"end\", \"beginning\""),
            None::<serde_json::Value>,
        ))
    }
}

pub async fn note_patch(vault: &Vault, params: NotePatchParams) -> Result<String, ErrorData> {
    let request = PatchRequest {
        operation: params.operation,
        target_type: params.target_type,
        target: params.target,
        content: params.content,
    };
    vault.patch_note(Path::new(&params.path), &request)?;
    Ok(format!("Patched: {}", params.path))
}

pub async fn note_delete(vault: &Vault, params: NoteDeleteParams) -> Result<String, ErrorData> {
    if !params.confirm {
        return Err(ErrorData::new(
            ErrorCode::INVALID_PARAMS,
            "Deletion requires `confirm: true` as a safety check",
            None::<serde_json::Value>,
        ));
    }
    vault.delete_note(Path::new(&params.path))?;
    Ok(format!("Deleted: {}", params.path))
}

pub async fn note_move(vault: &Vault, params: NoteMoveParams) -> Result<String, ErrorData> {
    let new_path = vault.move_note(Path::new(&params.from), Path::new(&params.to))?;
    Ok(format!("Moved to: {}", new_path.display()))
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use super::*;
    use crate::test_helpers::{create_test_vault, test_config};
    use crate::vault::Vault;

    // ── note_read ───────────────────────────────────────────────────

    #[tokio::test]
    async fn read_existing_note() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault
            .write_note(Path::new("hello.md"), "# Hello\nWorld")
            .unwrap();

        let content = note_read(
            &vault,
            NoteReadParams {
                path: "hello.md".into(),
            },
        )
        .await
        .unwrap();
        assert_eq!(content, "# Hello\nWorld");
    }

    #[tokio::test]
    async fn read_nonexistent_note_errors() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();

        let result = note_read(
            &vault,
            NoteReadParams {
                path: "missing.md".into(),
            },
        )
        .await;
        assert!(result.is_err());
    }

    // ── note_create ─────────────────────────────────────────────────

    #[tokio::test]
    async fn create_new_note() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();

        let msg = note_create(
            &vault,
            NoteCreateParams {
                path: "new.md".into(),
                content: Some("body".into()),
                frontmatter: Some(serde_json::json!({"status": "draft"})),
            },
        )
        .await
        .unwrap();
        assert!(msg.contains("new.md"));

        let content = vault.read_note(Path::new("new.md")).unwrap();
        assert!(content.contains("body"));
        assert!(content.contains("status"));
    }

    #[tokio::test]
    async fn create_duplicate_note_errors() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();

        note_create(
            &vault,
            NoteCreateParams {
                path: "dup.md".into(),
                ..Default::default()
            },
        )
        .await
        .unwrap();

        let result = note_create(
            &vault,
            NoteCreateParams {
                path: "dup.md".into(),
                ..Default::default()
            },
        )
        .await;
        assert!(result.is_err());
    }

    // ── note_write ──────────────────────────────────────────────────

    #[tokio::test]
    async fn write_overwrites_content() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault
            .write_note(Path::new("note.md"), "old content")
            .unwrap();

        note_write(
            &vault,
            NoteWriteParams {
                path: "note.md".into(),
                content: "new content".into(),
            },
        )
        .await
        .unwrap();

        let content = vault.read_note(Path::new("note.md")).unwrap();
        assert_eq!(content, "new content");
    }

    // ── note_insert ────────────────────────────────────────────────

    #[tokio::test]
    async fn insert_end_appends_to_note() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault.write_note(Path::new("note.md"), "start").unwrap();

        note_insert(
            &vault,
            NoteInsertParams {
                path: "note.md".into(),
                content: "\nmore".into(),
                position: Some("end".into()),
            },
        )
        .await
        .unwrap();

        let content = vault.read_note(Path::new("note.md")).unwrap();
        assert!(content.ends_with("more"));
        assert!(content.starts_with("start"));
    }

    #[tokio::test]
    async fn insert_default_position_appends() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault.write_note(Path::new("note.md"), "start").unwrap();

        note_insert(
            &vault,
            NoteInsertParams {
                path: "note.md".into(),
                content: "\nmore".into(),
                position: None,
            },
        )
        .await
        .unwrap();

        let content = vault.read_note(Path::new("note.md")).unwrap();
        assert!(content.ends_with("more"));
        assert!(content.starts_with("start"));
    }

    #[tokio::test]
    async fn insert_beginning_after_frontmatter() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault
            .write_note(Path::new("note.md"), "---\ntags: [a]\n---\n# Heading\n")
            .unwrap();

        note_insert(
            &vault,
            NoteInsertParams {
                path: "note.md".into(),
                content: "injected\n".into(),
                position: Some("beginning".into()),
            },
        )
        .await
        .unwrap();

        let content = vault.read_note(Path::new("note.md")).unwrap();
        assert!(content.starts_with("---\ntags:"));
        assert!(content.contains("injected"));
        assert!(content.contains("# Heading"));
    }

    #[tokio::test]
    async fn insert_invalid_position_errors() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault.write_note(Path::new("note.md"), "content").unwrap();

        let result = note_insert(
            &vault,
            NoteInsertParams {
                path: "note.md".into(),
                content: "text".into(),
                position: Some("middle".into()),
            },
        )
        .await;
        let err = result.unwrap_err();
        assert!(err.message.contains("Unknown position"));
        assert!(err.message.contains("middle"));
    }

    #[tokio::test]
    async fn insert_position_is_case_insensitive() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault.write_note(Path::new("note.md"), "start").unwrap();

        note_insert(
            &vault,
            NoteInsertParams {
                path: "note.md".into(),
                content: "\nmore".into(),
                position: Some("END".into()),
            },
        )
        .await
        .unwrap();

        let content = vault.read_note(Path::new("note.md")).unwrap();
        assert!(content.ends_with("more"));
    }

    // ── note_patch ──────────────────────────────────────────────────

    #[tokio::test]
    async fn patch_heading_append() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault
            .write_note(Path::new("patched.md"), "# Title\nBody\n## Sub\nSub body\n")
            .unwrap();

        note_patch(
            &vault,
            NotePatchParams {
                path: "patched.md".into(),
                operation: PatchOperation::Append,
                target_type: PatchTargetType::Heading,
                target: "Sub".into(),
                content: "appended\n".into(),
            },
        )
        .await
        .unwrap();

        let content = vault.read_note(Path::new("patched.md")).unwrap();
        assert!(content.contains("Sub body"));
        assert!(content.contains("appended"));
    }

    // ── note_delete ─────────────────────────────────────────────────

    #[tokio::test]
    async fn delete_requires_confirm() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault.write_note(Path::new("note.md"), "content").unwrap();

        let result = note_delete(
            &vault,
            NoteDeleteParams {
                path: "note.md".into(),
                confirm: false,
            },
        )
        .await;
        assert!(result.is_err());
        assert!(vault.read_note(Path::new("note.md")).is_ok());
    }

    #[tokio::test]
    async fn delete_with_confirm_succeeds() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault.write_note(Path::new("note.md"), "content").unwrap();

        note_delete(
            &vault,
            NoteDeleteParams {
                path: "note.md".into(),
                confirm: true,
            },
        )
        .await
        .unwrap();
        assert!(vault.read_note(Path::new("note.md")).is_err());
    }

    // ── note_move ───────────────────────────────────────────────────

    #[tokio::test]
    async fn move_renames_note() {
        let dir = tempfile::tempdir().unwrap();
        create_test_vault(dir.path());
        let vault = Vault::open(&test_config(dir.path())).await.unwrap();
        vault.write_note(Path::new("old.md"), "content").unwrap();

        let msg = note_move(
            &vault,
            NoteMoveParams {
                from: "old.md".into(),
                to: "new.md".into(),
            },
        )
        .await
        .unwrap();
        assert!(msg.contains("new.md"));

        assert!(vault.read_note(Path::new("old.md")).is_err());
        assert_eq!(vault.read_note(Path::new("new.md")).unwrap(), "content");
    }
}