obsidian-lite-mcp 1.0.0__tar.gz
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.
- obsidian_lite_mcp-1.0.0/LICENSE +21 -0
- obsidian_lite_mcp-1.0.0/PKG-INFO +158 -0
- obsidian_lite_mcp-1.0.0/README.md +145 -0
- obsidian_lite_mcp-1.0.0/obsidian_lite_mcp.egg-info/PKG-INFO +158 -0
- obsidian_lite_mcp-1.0.0/obsidian_lite_mcp.egg-info/SOURCES.txt +9 -0
- obsidian_lite_mcp-1.0.0/obsidian_lite_mcp.egg-info/dependency_links.txt +1 -0
- obsidian_lite_mcp-1.0.0/obsidian_lite_mcp.egg-info/entry_points.txt +2 -0
- obsidian_lite_mcp-1.0.0/obsidian_lite_mcp.egg-info/top_level.txt +1 -0
- obsidian_lite_mcp-1.0.0/obsidian_lite_mcp.py +431 -0
- obsidian_lite_mcp-1.0.0/pyproject.toml +26 -0
- obsidian_lite_mcp-1.0.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dabusoft
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: obsidian-lite-mcp
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Small MCP server that reads an Obsidian vault from disk: Obsidian-accurate links and backlinks, sections, search. No app, no dependencies.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/DabuSoft-pl/obsidian-lite-mcp
|
|
7
|
+
Project-URL: Issues, https://github.com/DabuSoft-pl/obsidian-lite-mcp/issues
|
|
8
|
+
Keywords: mcp,obsidian,claude,model-context-protocol,markdown
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# obsidian-lite-mcp
|
|
15
|
+
|
|
16
|
+
<!-- mcp-name: io.github.DabuSoft-pl/obsidian-lite-mcp -->
|
|
17
|
+
|
|
18
|
+
A tiny MCP server that lets AI agents read an Obsidian vault straight from disk.
|
|
19
|
+
|
|
20
|
+
- **No Obsidian app running**, no plugins, no REST API: the vault is just a folder of `.md` files.
|
|
21
|
+
- **No shell needed**: works in MCP clients that can't run `grep` at all, such as Claude Desktop.
|
|
22
|
+
- **Links the way Obsidian sees them**: backlinks that match case-insensitively, through `[[Folder/Note]]` paths,
|
|
23
|
+
aliases and Markdown links, and skip links inside code. Plain `grep "[[Name"` gets these wrong.
|
|
24
|
+
- **One file, zero dependencies**: Python standard library only.
|
|
25
|
+
- **Read-only by default.** Writing is opt-in and limited to creating new notes in one folder.
|
|
26
|
+
- **Pull only what's needed**: every result carries its size (`~N tok`), and a big note can be read one section
|
|
27
|
+
at a time. See [Measured](#measured) for what that buys and where it doesn't.
|
|
28
|
+
|
|
29
|
+
## Tools
|
|
30
|
+
|
|
31
|
+
| Tool | What it does |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `search` | Regex over text and paths, plus `tag` and frontmatter `property` filters (`key` or `key=value`). Ranked by matches, then recency. `links: broken` lists notes with unresolved links (attachments excluded), `links: orphans` notes nothing links to. |
|
|
34
|
+
| `read` | A note by `[[link]]` name, alias or path, with outgoing links and backlinks. `Note#Heading` returns one section; `outline: true` returns headings with the size of each section. Notes over 8000 tokens return their outline unless `full: true`. |
|
|
35
|
+
| `remember` | Only with `--write-dir`: creates a new note in that folder, tagged `claude`. Never edits or overwrites. |
|
|
36
|
+
|
|
37
|
+
Links resolve the way Obsidian does: exact path first, then note name or `aliases`, shortest path on ties.
|
|
38
|
+
Markdown links (`[text](Folder/Note.md)`) count too. Tags come from frontmatter and `#inline` tags outside code.
|
|
39
|
+
Folders listed in Obsidian's *Excluded files* setting are skipped, as are hidden folders like `.obsidian` and `.trash`.
|
|
40
|
+
|
|
41
|
+
Fast on big vaults: files are re-read only when they change, and on a 5000-note vault a `read` with backlinks
|
|
42
|
+
takes about 0.05 s.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
uvx obsidian-lite-mcp /path/to/vault
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Or skip packaging entirely: download `obsidian_lite_mcp.py` and run `python3 obsidian_lite_mcp.py /path/to/vault`.
|
|
51
|
+
|
|
52
|
+
### Claude Code
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
claude mcp add -s user vault -- uvx obsidian-lite-mcp /path/to/vault
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
To let the agent save new notes into `Inbox/` (date key in their frontmatter: `VAULT_DATE_KEY`, default `created`):
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
claude mcp add -s user vault -- uvx obsidian-lite-mcp /path/to/vault --write-dir Inbox
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Other clients
|
|
65
|
+
|
|
66
|
+
Any MCP client that runs stdio servers works:
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
{
|
|
70
|
+
"mcpServers": {
|
|
71
|
+
"vault": { "command": "uvx", "args": ["obsidian-lite-mcp", "/path/to/vault"] }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Project context at session start
|
|
77
|
+
|
|
78
|
+
Give a project note a `repo` property listing the repository folder names:
|
|
79
|
+
|
|
80
|
+
```yaml
|
|
81
|
+
---
|
|
82
|
+
repo:
|
|
83
|
+
- my-api
|
|
84
|
+
- my-frontend
|
|
85
|
+
---
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`obsidian-lite-mcp context /path/to/vault "$PWD"` then prints a short index for whichever repo you are in:
|
|
89
|
+
the note's first line, ADRs (notes tagged `adr`) grouped by `status`, open `- [ ]` task counts and the three most
|
|
90
|
+
recently changed notes, all from the project note's folder. Measured in a real Claude Code session: about 450 tokens.
|
|
91
|
+
Details come from `read`.
|
|
92
|
+
|
|
93
|
+
In Claude Code, add it as a `SessionStart` hook in `~/.claude/settings.json`:
|
|
94
|
+
|
|
95
|
+
```json
|
|
96
|
+
{
|
|
97
|
+
"hooks": {
|
|
98
|
+
"SessionStart": [
|
|
99
|
+
{
|
|
100
|
+
"matcher": "startup|clear|compact",
|
|
101
|
+
"hooks": [
|
|
102
|
+
{
|
|
103
|
+
"type": "command",
|
|
104
|
+
"command": "uvx obsidian-lite-mcp context /path/to/vault \"$CLAUDE_PROJECT_DIR\"",
|
|
105
|
+
"timeout": 10
|
|
106
|
+
}
|
|
107
|
+
]
|
|
108
|
+
}
|
|
109
|
+
]
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Outside a known repo it prints nothing. `VAULT_CONTEXT=off` silences it for one run (handy for A/B token measurements).
|
|
115
|
+
|
|
116
|
+
## Measured
|
|
117
|
+
|
|
118
|
+
Same questions, Claude Code headless (`claude -p`, Haiku), two runs per setup. *grep* had only Read, Grep and Glob;
|
|
119
|
+
*obsidian-lite-mcp* had only this server's tools. Tokens are total input tokens for the whole task.
|
|
120
|
+
|
|
121
|
+
**Obsidian's own help vault** ([obsidianmd/obsidian-help](https://github.com/obsidianmd/obsidian-help) `en/`,
|
|
122
|
+
181 notes): two backlink counts, two answers from sections of a 16k-token note, one alias lookup.
|
|
123
|
+
|
|
124
|
+
| Setup | Correct | Turns | Input tokens | Output tokens | Cost |
|
|
125
|
+
|---|---|---|---|---|---|
|
|
126
|
+
| grep | 5/5, 5/5 | 20, 15 | 821k, 510k | 12.6k, 11.6k | $0.084, $0.026 |
|
|
127
|
+
| obsidian-lite-mcp | 5/5, 5/5 | 11, 12 | 225k, 277k | 3.7k, 4.3k | $0.014, $0.013 |
|
|
128
|
+
|
|
129
|
+
Both got everything right, but only because the prompt spelled out Obsidian's link rules; grep needed about
|
|
130
|
+
twice the turns and 2-4x the tokens to apply them. Naive `grep -rlF "[[Command palette"` reports 62 backlinks
|
|
131
|
+
instead of 64 (it misses `[[command palette]]`), and 32 instead of 31 for Properties (it counts `[[Properties view]]`).
|
|
132
|
+
|
|
133
|
+
**A small personal vault** (90 notes, simple links): five lookups (ADR status, backlink count, a section, open
|
|
134
|
+
tasks, find by topic). Both setups 5/5; input tokens grep 184k and 123k, obsidian-lite-mcp 147k and 247k.
|
|
135
|
+
**No measurable difference**: on a small vault with plain links, grep is just as good.
|
|
136
|
+
|
|
137
|
+
The `context` hook costs about 450 input tokens per session (A/B with `VAULT_CONTEXT=off`).
|
|
138
|
+
|
|
139
|
+
Search stays regex-only on purpose. A plain-words mode (any order, BM25-ranked) was tried on four topic questions
|
|
140
|
+
over the personal vault, three runs per setup: both 3/3 correct, regex 6 turns and about 73k input tokens every run,
|
|
141
|
+
words 6-8 turns and 77k-116k. Models already write good regexes (`PHP 8\.[45]`, `a|b`), so it was dropped.
|
|
142
|
+
|
|
143
|
+
## Limits
|
|
144
|
+
|
|
145
|
+
- Every call checks file timestamps (about 0.04 s for 5000 notes); the first call reads everything (about 1 s).
|
|
146
|
+
- Frontmatter parsing covers scalars, `[a, b]` and `- item` lists; nested YAML is skipped.
|
|
147
|
+
- Token counts are estimates (characters / 2, measured on Polish notes; English text is cheaper).
|
|
148
|
+
- `.base` and `.canvas` files are not indexed.
|
|
149
|
+
|
|
150
|
+
## Development
|
|
151
|
+
|
|
152
|
+
```sh
|
|
153
|
+
python3 -m unittest
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## License
|
|
157
|
+
|
|
158
|
+
MIT
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
# obsidian-lite-mcp
|
|
2
|
+
|
|
3
|
+
<!-- mcp-name: io.github.DabuSoft-pl/obsidian-lite-mcp -->
|
|
4
|
+
|
|
5
|
+
A tiny MCP server that lets AI agents read an Obsidian vault straight from disk.
|
|
6
|
+
|
|
7
|
+
- **No Obsidian app running**, no plugins, no REST API: the vault is just a folder of `.md` files.
|
|
8
|
+
- **No shell needed**: works in MCP clients that can't run `grep` at all, such as Claude Desktop.
|
|
9
|
+
- **Links the way Obsidian sees them**: backlinks that match case-insensitively, through `[[Folder/Note]]` paths,
|
|
10
|
+
aliases and Markdown links, and skip links inside code. Plain `grep "[[Name"` gets these wrong.
|
|
11
|
+
- **One file, zero dependencies**: Python standard library only.
|
|
12
|
+
- **Read-only by default.** Writing is opt-in and limited to creating new notes in one folder.
|
|
13
|
+
- **Pull only what's needed**: every result carries its size (`~N tok`), and a big note can be read one section
|
|
14
|
+
at a time. See [Measured](#measured) for what that buys and where it doesn't.
|
|
15
|
+
|
|
16
|
+
## Tools
|
|
17
|
+
|
|
18
|
+
| Tool | What it does |
|
|
19
|
+
|---|---|
|
|
20
|
+
| `search` | Regex over text and paths, plus `tag` and frontmatter `property` filters (`key` or `key=value`). Ranked by matches, then recency. `links: broken` lists notes with unresolved links (attachments excluded), `links: orphans` notes nothing links to. |
|
|
21
|
+
| `read` | A note by `[[link]]` name, alias or path, with outgoing links and backlinks. `Note#Heading` returns one section; `outline: true` returns headings with the size of each section. Notes over 8000 tokens return their outline unless `full: true`. |
|
|
22
|
+
| `remember` | Only with `--write-dir`: creates a new note in that folder, tagged `claude`. Never edits or overwrites. |
|
|
23
|
+
|
|
24
|
+
Links resolve the way Obsidian does: exact path first, then note name or `aliases`, shortest path on ties.
|
|
25
|
+
Markdown links (`[text](Folder/Note.md)`) count too. Tags come from frontmatter and `#inline` tags outside code.
|
|
26
|
+
Folders listed in Obsidian's *Excluded files* setting are skipped, as are hidden folders like `.obsidian` and `.trash`.
|
|
27
|
+
|
|
28
|
+
Fast on big vaults: files are re-read only when they change, and on a 5000-note vault a `read` with backlinks
|
|
29
|
+
takes about 0.05 s.
|
|
30
|
+
|
|
31
|
+
## Install
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
uvx obsidian-lite-mcp /path/to/vault
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Or skip packaging entirely: download `obsidian_lite_mcp.py` and run `python3 obsidian_lite_mcp.py /path/to/vault`.
|
|
38
|
+
|
|
39
|
+
### Claude Code
|
|
40
|
+
|
|
41
|
+
```sh
|
|
42
|
+
claude mcp add -s user vault -- uvx obsidian-lite-mcp /path/to/vault
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
To let the agent save new notes into `Inbox/` (date key in their frontmatter: `VAULT_DATE_KEY`, default `created`):
|
|
46
|
+
|
|
47
|
+
```sh
|
|
48
|
+
claude mcp add -s user vault -- uvx obsidian-lite-mcp /path/to/vault --write-dir Inbox
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Other clients
|
|
52
|
+
|
|
53
|
+
Any MCP client that runs stdio servers works:
|
|
54
|
+
|
|
55
|
+
```json
|
|
56
|
+
{
|
|
57
|
+
"mcpServers": {
|
|
58
|
+
"vault": { "command": "uvx", "args": ["obsidian-lite-mcp", "/path/to/vault"] }
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Project context at session start
|
|
64
|
+
|
|
65
|
+
Give a project note a `repo` property listing the repository folder names:
|
|
66
|
+
|
|
67
|
+
```yaml
|
|
68
|
+
---
|
|
69
|
+
repo:
|
|
70
|
+
- my-api
|
|
71
|
+
- my-frontend
|
|
72
|
+
---
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`obsidian-lite-mcp context /path/to/vault "$PWD"` then prints a short index for whichever repo you are in:
|
|
76
|
+
the note's first line, ADRs (notes tagged `adr`) grouped by `status`, open `- [ ]` task counts and the three most
|
|
77
|
+
recently changed notes, all from the project note's folder. Measured in a real Claude Code session: about 450 tokens.
|
|
78
|
+
Details come from `read`.
|
|
79
|
+
|
|
80
|
+
In Claude Code, add it as a `SessionStart` hook in `~/.claude/settings.json`:
|
|
81
|
+
|
|
82
|
+
```json
|
|
83
|
+
{
|
|
84
|
+
"hooks": {
|
|
85
|
+
"SessionStart": [
|
|
86
|
+
{
|
|
87
|
+
"matcher": "startup|clear|compact",
|
|
88
|
+
"hooks": [
|
|
89
|
+
{
|
|
90
|
+
"type": "command",
|
|
91
|
+
"command": "uvx obsidian-lite-mcp context /path/to/vault \"$CLAUDE_PROJECT_DIR\"",
|
|
92
|
+
"timeout": 10
|
|
93
|
+
}
|
|
94
|
+
]
|
|
95
|
+
}
|
|
96
|
+
]
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Outside a known repo it prints nothing. `VAULT_CONTEXT=off` silences it for one run (handy for A/B token measurements).
|
|
102
|
+
|
|
103
|
+
## Measured
|
|
104
|
+
|
|
105
|
+
Same questions, Claude Code headless (`claude -p`, Haiku), two runs per setup. *grep* had only Read, Grep and Glob;
|
|
106
|
+
*obsidian-lite-mcp* had only this server's tools. Tokens are total input tokens for the whole task.
|
|
107
|
+
|
|
108
|
+
**Obsidian's own help vault** ([obsidianmd/obsidian-help](https://github.com/obsidianmd/obsidian-help) `en/`,
|
|
109
|
+
181 notes): two backlink counts, two answers from sections of a 16k-token note, one alias lookup.
|
|
110
|
+
|
|
111
|
+
| Setup | Correct | Turns | Input tokens | Output tokens | Cost |
|
|
112
|
+
|---|---|---|---|---|---|
|
|
113
|
+
| grep | 5/5, 5/5 | 20, 15 | 821k, 510k | 12.6k, 11.6k | $0.084, $0.026 |
|
|
114
|
+
| obsidian-lite-mcp | 5/5, 5/5 | 11, 12 | 225k, 277k | 3.7k, 4.3k | $0.014, $0.013 |
|
|
115
|
+
|
|
116
|
+
Both got everything right, but only because the prompt spelled out Obsidian's link rules; grep needed about
|
|
117
|
+
twice the turns and 2-4x the tokens to apply them. Naive `grep -rlF "[[Command palette"` reports 62 backlinks
|
|
118
|
+
instead of 64 (it misses `[[command palette]]`), and 32 instead of 31 for Properties (it counts `[[Properties view]]`).
|
|
119
|
+
|
|
120
|
+
**A small personal vault** (90 notes, simple links): five lookups (ADR status, backlink count, a section, open
|
|
121
|
+
tasks, find by topic). Both setups 5/5; input tokens grep 184k and 123k, obsidian-lite-mcp 147k and 247k.
|
|
122
|
+
**No measurable difference**: on a small vault with plain links, grep is just as good.
|
|
123
|
+
|
|
124
|
+
The `context` hook costs about 450 input tokens per session (A/B with `VAULT_CONTEXT=off`).
|
|
125
|
+
|
|
126
|
+
Search stays regex-only on purpose. A plain-words mode (any order, BM25-ranked) was tried on four topic questions
|
|
127
|
+
over the personal vault, three runs per setup: both 3/3 correct, regex 6 turns and about 73k input tokens every run,
|
|
128
|
+
words 6-8 turns and 77k-116k. Models already write good regexes (`PHP 8\.[45]`, `a|b`), so it was dropped.
|
|
129
|
+
|
|
130
|
+
## Limits
|
|
131
|
+
|
|
132
|
+
- Every call checks file timestamps (about 0.04 s for 5000 notes); the first call reads everything (about 1 s).
|
|
133
|
+
- Frontmatter parsing covers scalars, `[a, b]` and `- item` lists; nested YAML is skipped.
|
|
134
|
+
- Token counts are estimates (characters / 2, measured on Polish notes; English text is cheaper).
|
|
135
|
+
- `.base` and `.canvas` files are not indexed.
|
|
136
|
+
|
|
137
|
+
## Development
|
|
138
|
+
|
|
139
|
+
```sh
|
|
140
|
+
python3 -m unittest
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## License
|
|
144
|
+
|
|
145
|
+
MIT
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: obsidian-lite-mcp
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Small MCP server that reads an Obsidian vault from disk: Obsidian-accurate links and backlinks, sections, search. No app, no dependencies.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/DabuSoft-pl/obsidian-lite-mcp
|
|
7
|
+
Project-URL: Issues, https://github.com/DabuSoft-pl/obsidian-lite-mcp/issues
|
|
8
|
+
Keywords: mcp,obsidian,claude,model-context-protocol,markdown
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# obsidian-lite-mcp
|
|
15
|
+
|
|
16
|
+
<!-- mcp-name: io.github.DabuSoft-pl/obsidian-lite-mcp -->
|
|
17
|
+
|
|
18
|
+
A tiny MCP server that lets AI agents read an Obsidian vault straight from disk.
|
|
19
|
+
|
|
20
|
+
- **No Obsidian app running**, no plugins, no REST API: the vault is just a folder of `.md` files.
|
|
21
|
+
- **No shell needed**: works in MCP clients that can't run `grep` at all, such as Claude Desktop.
|
|
22
|
+
- **Links the way Obsidian sees them**: backlinks that match case-insensitively, through `[[Folder/Note]]` paths,
|
|
23
|
+
aliases and Markdown links, and skip links inside code. Plain `grep "[[Name"` gets these wrong.
|
|
24
|
+
- **One file, zero dependencies**: Python standard library only.
|
|
25
|
+
- **Read-only by default.** Writing is opt-in and limited to creating new notes in one folder.
|
|
26
|
+
- **Pull only what's needed**: every result carries its size (`~N tok`), and a big note can be read one section
|
|
27
|
+
at a time. See [Measured](#measured) for what that buys and where it doesn't.
|
|
28
|
+
|
|
29
|
+
## Tools
|
|
30
|
+
|
|
31
|
+
| Tool | What it does |
|
|
32
|
+
|---|---|
|
|
33
|
+
| `search` | Regex over text and paths, plus `tag` and frontmatter `property` filters (`key` or `key=value`). Ranked by matches, then recency. `links: broken` lists notes with unresolved links (attachments excluded), `links: orphans` notes nothing links to. |
|
|
34
|
+
| `read` | A note by `[[link]]` name, alias or path, with outgoing links and backlinks. `Note#Heading` returns one section; `outline: true` returns headings with the size of each section. Notes over 8000 tokens return their outline unless `full: true`. |
|
|
35
|
+
| `remember` | Only with `--write-dir`: creates a new note in that folder, tagged `claude`. Never edits or overwrites. |
|
|
36
|
+
|
|
37
|
+
Links resolve the way Obsidian does: exact path first, then note name or `aliases`, shortest path on ties.
|
|
38
|
+
Markdown links (`[text](Folder/Note.md)`) count too. Tags come from frontmatter and `#inline` tags outside code.
|
|
39
|
+
Folders listed in Obsidian's *Excluded files* setting are skipped, as are hidden folders like `.obsidian` and `.trash`.
|
|
40
|
+
|
|
41
|
+
Fast on big vaults: files are re-read only when they change, and on a 5000-note vault a `read` with backlinks
|
|
42
|
+
takes about 0.05 s.
|
|
43
|
+
|
|
44
|
+
## Install
|
|
45
|
+
|
|
46
|
+
```sh
|
|
47
|
+
uvx obsidian-lite-mcp /path/to/vault
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Or skip packaging entirely: download `obsidian_lite_mcp.py` and run `python3 obsidian_lite_mcp.py /path/to/vault`.
|
|
51
|
+
|
|
52
|
+
### Claude Code
|
|
53
|
+
|
|
54
|
+
```sh
|
|
55
|
+
claude mcp add -s user vault -- uvx obsidian-lite-mcp /path/to/vault
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
To let the agent save new notes into `Inbox/` (date key in their frontmatter: `VAULT_DATE_KEY`, default `created`):
|
|
59
|
+
|
|
60
|
+
```sh
|
|
61
|
+
claude mcp add -s user vault -- uvx obsidian-lite-mcp /path/to/vault --write-dir Inbox
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Other clients
|
|
65
|
+
|
|
66
|
+
Any MCP client that runs stdio servers works:
|
|
67
|
+
|
|
68
|
+
```json
|
|
69
|
+
{
|
|
70
|
+
"mcpServers": {
|
|
71
|
+
"vault": { "command": "uvx", "args": ["obsidian-lite-mcp", "/path/to/vault"] }
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Project context at session start
|
|
77
|
+
|
|
78
|
+
Give a project note a `repo` property listing the repository folder names:
|
|
79
|
+
|
|
80
|
+
```yaml
|
|
81
|
+
---
|
|
82
|
+
repo:
|
|
83
|
+
- my-api
|
|
84
|
+
- my-frontend
|
|
85
|
+
---
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
`obsidian-lite-mcp context /path/to/vault "$PWD"` then prints a short index for whichever repo you are in:
|
|
89
|
+
the note's first line, ADRs (notes tagged `adr`) grouped by `status`, open `- [ ]` task counts and the three most
|
|
90
|
+
recently changed notes, all from the project note's folder. Measured in a real Claude Code session: about 450 tokens.
|
|
91
|
+
Details come from `read`.
|
|
92
|
+
|
|
93
|
+
In Claude Code, add it as a `SessionStart` hook in `~/.claude/settings.json`:
|
|
94
|
+
|
|
95
|
+
```json
|
|
96
|
+
{
|
|
97
|
+
"hooks": {
|
|
98
|
+
"SessionStart": [
|
|
99
|
+
{
|
|
100
|
+
"matcher": "startup|clear|compact",
|
|
101
|
+
"hooks": [
|
|
102
|
+
{
|
|
103
|
+
"type": "command",
|
|
104
|
+
"command": "uvx obsidian-lite-mcp context /path/to/vault \"$CLAUDE_PROJECT_DIR\"",
|
|
105
|
+
"timeout": 10
|
|
106
|
+
}
|
|
107
|
+
]
|
|
108
|
+
}
|
|
109
|
+
]
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Outside a known repo it prints nothing. `VAULT_CONTEXT=off` silences it for one run (handy for A/B token measurements).
|
|
115
|
+
|
|
116
|
+
## Measured
|
|
117
|
+
|
|
118
|
+
Same questions, Claude Code headless (`claude -p`, Haiku), two runs per setup. *grep* had only Read, Grep and Glob;
|
|
119
|
+
*obsidian-lite-mcp* had only this server's tools. Tokens are total input tokens for the whole task.
|
|
120
|
+
|
|
121
|
+
**Obsidian's own help vault** ([obsidianmd/obsidian-help](https://github.com/obsidianmd/obsidian-help) `en/`,
|
|
122
|
+
181 notes): two backlink counts, two answers from sections of a 16k-token note, one alias lookup.
|
|
123
|
+
|
|
124
|
+
| Setup | Correct | Turns | Input tokens | Output tokens | Cost |
|
|
125
|
+
|---|---|---|---|---|---|
|
|
126
|
+
| grep | 5/5, 5/5 | 20, 15 | 821k, 510k | 12.6k, 11.6k | $0.084, $0.026 |
|
|
127
|
+
| obsidian-lite-mcp | 5/5, 5/5 | 11, 12 | 225k, 277k | 3.7k, 4.3k | $0.014, $0.013 |
|
|
128
|
+
|
|
129
|
+
Both got everything right, but only because the prompt spelled out Obsidian's link rules; grep needed about
|
|
130
|
+
twice the turns and 2-4x the tokens to apply them. Naive `grep -rlF "[[Command palette"` reports 62 backlinks
|
|
131
|
+
instead of 64 (it misses `[[command palette]]`), and 32 instead of 31 for Properties (it counts `[[Properties view]]`).
|
|
132
|
+
|
|
133
|
+
**A small personal vault** (90 notes, simple links): five lookups (ADR status, backlink count, a section, open
|
|
134
|
+
tasks, find by topic). Both setups 5/5; input tokens grep 184k and 123k, obsidian-lite-mcp 147k and 247k.
|
|
135
|
+
**No measurable difference**: on a small vault with plain links, grep is just as good.
|
|
136
|
+
|
|
137
|
+
The `context` hook costs about 450 input tokens per session (A/B with `VAULT_CONTEXT=off`).
|
|
138
|
+
|
|
139
|
+
Search stays regex-only on purpose. A plain-words mode (any order, BM25-ranked) was tried on four topic questions
|
|
140
|
+
over the personal vault, three runs per setup: both 3/3 correct, regex 6 turns and about 73k input tokens every run,
|
|
141
|
+
words 6-8 turns and 77k-116k. Models already write good regexes (`PHP 8\.[45]`, `a|b`), so it was dropped.
|
|
142
|
+
|
|
143
|
+
## Limits
|
|
144
|
+
|
|
145
|
+
- Every call checks file timestamps (about 0.04 s for 5000 notes); the first call reads everything (about 1 s).
|
|
146
|
+
- Frontmatter parsing covers scalars, `[a, b]` and `- item` lists; nested YAML is skipped.
|
|
147
|
+
- Token counts are estimates (characters / 2, measured on Polish notes; English text is cheaper).
|
|
148
|
+
- `.base` and `.canvas` files are not indexed.
|
|
149
|
+
|
|
150
|
+
## Development
|
|
151
|
+
|
|
152
|
+
```sh
|
|
153
|
+
python3 -m unittest
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
## License
|
|
157
|
+
|
|
158
|
+
MIT
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
obsidian_lite_mcp.py
|
|
4
|
+
pyproject.toml
|
|
5
|
+
obsidian_lite_mcp.egg-info/PKG-INFO
|
|
6
|
+
obsidian_lite_mcp.egg-info/SOURCES.txt
|
|
7
|
+
obsidian_lite_mcp.egg-info/dependency_links.txt
|
|
8
|
+
obsidian_lite_mcp.egg-info/entry_points.txt
|
|
9
|
+
obsidian_lite_mcp.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
obsidian_lite_mcp
|
|
@@ -0,0 +1,431 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Read-first MCP server (stdio) for an Obsidian vault. No Obsidian app, no dependencies.
|
|
3
|
+
|
|
4
|
+
Usage: obsidian-lite-mcp /path/to/vault [--write-dir Inbox] MCP server on stdio; --write-dir enables `remember`
|
|
5
|
+
obsidian-lite-mcp context /path/to/vault CWD project brief for the repo in CWD (notes with `repo:` property)
|
|
6
|
+
"""
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
import posixpath
|
|
10
|
+
import re
|
|
11
|
+
import sys
|
|
12
|
+
import time
|
|
13
|
+
import unicodedata
|
|
14
|
+
from urllib.parse import unquote
|
|
15
|
+
|
|
16
|
+
__version__ = "1.0.0"
|
|
17
|
+
|
|
18
|
+
WIKI_RE = re.compile(r"!?\[\[([^\]|#]*)[^\]]*\]\]")
|
|
19
|
+
MD_LINK_RE = re.compile(r"\]\((?:<([^>]+?\.md)>|([^)\s]+?\.md))(?:#[^)]*)?\)")
|
|
20
|
+
TAG_RE = re.compile(r"(?<![\w/#&])#([^\W\d][\w/-]*)")
|
|
21
|
+
CODE_RE = re.compile(r"```.*?```|`[^`\n]*`", re.S)
|
|
22
|
+
TASK_RE = re.compile(r"^\s*- \[ \] ", re.M)
|
|
23
|
+
MAX_RESULTS = 20
|
|
24
|
+
MAX_READ_TOKENS = 8000 # bigger reads return the outline instead, unless full=true
|
|
25
|
+
DATE_KEY = os.environ.get("VAULT_DATE_KEY", "created") # frontmatter key for the date on notes `remember` creates
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def nfc(s):
|
|
29
|
+
"""macOS may hand back NFD file names; links are typed in NFC. Compare everything in NFC."""
|
|
30
|
+
return unicodedata.normalize("NFC", s)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def parse_frontmatter(text):
|
|
34
|
+
"""Return (props, body). shortcut: handles scalars, [a, b] and '- item' lists only; nested YAML is skipped."""
|
|
35
|
+
if not text.startswith("---\n"):
|
|
36
|
+
return {}, text
|
|
37
|
+
end = text.find("\n---", 4)
|
|
38
|
+
if end == -1:
|
|
39
|
+
return {}, text
|
|
40
|
+
props, key = {}, None
|
|
41
|
+
for line in text[4:end].splitlines():
|
|
42
|
+
item = re.match(r"\s+-\s*(.*)", line)
|
|
43
|
+
if item and key is not None:
|
|
44
|
+
if not isinstance(props[key], list):
|
|
45
|
+
props[key] = []
|
|
46
|
+
props[key].append(item.group(1).strip().strip("\"'"))
|
|
47
|
+
continue
|
|
48
|
+
kv = re.match(r"([^\s:][^:]*):\s*(.*)", line)
|
|
49
|
+
if not kv:
|
|
50
|
+
continue
|
|
51
|
+
key, val = kv.group(1).strip(), kv.group(2).strip()
|
|
52
|
+
if val.startswith("[") and val.endswith("]") and not val.startswith("[["):
|
|
53
|
+
props[key] = [v.strip().strip("\"'") for v in val[1:-1].split(",") if v.strip()]
|
|
54
|
+
else:
|
|
55
|
+
props[key] = val.strip("\"'")
|
|
56
|
+
return props, text[end + 4:].lstrip("\n")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def as_list(value):
|
|
60
|
+
return [value] if isinstance(value, str) else value or []
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def links_in(text, rel):
|
|
64
|
+
"""Link targets in text: [[wikilinks]] by name, and [x](note.md) links as vault-relative paths. Code is not linked."""
|
|
65
|
+
text = CODE_RE.sub("", text)
|
|
66
|
+
# rstrip: inside tables the alias pipe is escaped, [[Note\|alias]]
|
|
67
|
+
out = [nfc(l.strip().rstrip("\\").strip()) for l in WIKI_RE.findall(text) if l.strip().rstrip("\\").strip()]
|
|
68
|
+
for a, b in MD_LINK_RE.findall(text):
|
|
69
|
+
target = nfc(unquote(a or b))
|
|
70
|
+
if not re.match(r"[A-Za-z][\w+.-]*:", target): # skip https:, mailto:, obsidian: ...
|
|
71
|
+
out.append(posixpath.normpath(posixpath.join(posixpath.dirname(rel), target)))
|
|
72
|
+
return out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def parse_note(text, rel, mtime):
|
|
76
|
+
props, body = parse_frontmatter(text)
|
|
77
|
+
tags = {t.lstrip("#").lower() for t in as_list(props.get("tags")) if t}
|
|
78
|
+
tags |= {t.lower() for t in TAG_RE.findall(CODE_RE.sub("", body))}
|
|
79
|
+
aliases = [nfc(a) for a in as_list(props.get("aliases") or props.get("alias")) if a]
|
|
80
|
+
return {"text": text, "props": props, "tags": tags, "mtime": mtime, "aliases": aliases, "links": links_in(text, rel)}
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Notes(dict):
|
|
84
|
+
"""path -> note, plus lookup indexes so link resolution and backlinks are O(1) per link."""
|
|
85
|
+
|
|
86
|
+
def __init__(self, entries):
|
|
87
|
+
super().__init__(entries)
|
|
88
|
+
self.by_path = {p[:-3].lower(): p for p in self}
|
|
89
|
+
self.by_name = {}
|
|
90
|
+
for p, n in self.items():
|
|
91
|
+
for key in [posixpath.basename(p)[:-3], *n["aliases"]]:
|
|
92
|
+
self.by_name.setdefault(key.lower(), []).append(p)
|
|
93
|
+
self._backlinks = None
|
|
94
|
+
|
|
95
|
+
def backlinks(self, path):
|
|
96
|
+
if self._backlinks is None:
|
|
97
|
+
self._backlinks = {}
|
|
98
|
+
for p, n in self.items():
|
|
99
|
+
for l in n["links"]:
|
|
100
|
+
target = resolve(l, self)
|
|
101
|
+
if target and target != p:
|
|
102
|
+
self._backlinks.setdefault(target, set()).add(p)
|
|
103
|
+
return sorted(self._backlinks.get(path, ()))
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def ignore_filters(vault):
|
|
107
|
+
"""Obsidian's Settings > Files and links > Excluded files: path prefixes, or /regex/."""
|
|
108
|
+
try:
|
|
109
|
+
with open(os.path.join(vault, ".obsidian", "app.json"), encoding="utf-8") as f:
|
|
110
|
+
raw = json.load(f).get("userIgnoreFilters") or []
|
|
111
|
+
except (OSError, ValueError, AttributeError):
|
|
112
|
+
return []
|
|
113
|
+
out = []
|
|
114
|
+
for s in raw:
|
|
115
|
+
if isinstance(s, str) and len(s) > 2 and s.startswith("/") and s.endswith("/"):
|
|
116
|
+
try:
|
|
117
|
+
out.append(re.compile(s[1:-1]).search)
|
|
118
|
+
except re.error:
|
|
119
|
+
pass
|
|
120
|
+
elif isinstance(s, str) and s:
|
|
121
|
+
out.append(lambda p, s=nfc(s): p.startswith(s))
|
|
122
|
+
return out
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
_CACHE = {} # vault -> {rel: (mtime, size, note)}; files are re-read only when they change
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def load(vault):
|
|
129
|
+
vault = os.path.abspath(vault)
|
|
130
|
+
old, new = _CACHE.get(vault, {}), {}
|
|
131
|
+
skip = ignore_filters(vault)
|
|
132
|
+
for root, dirs, files in os.walk(vault):
|
|
133
|
+
dirs[:] = sorted(d for d in dirs if not d.startswith("."))
|
|
134
|
+
for f in sorted(files):
|
|
135
|
+
if not f.endswith(".md"):
|
|
136
|
+
continue
|
|
137
|
+
full = os.path.join(root, f)
|
|
138
|
+
rel = nfc(os.path.relpath(full, vault).replace(os.sep, "/"))
|
|
139
|
+
if any(match(rel) for match in skip):
|
|
140
|
+
continue
|
|
141
|
+
try:
|
|
142
|
+
st = os.stat(full)
|
|
143
|
+
cached = old.get(rel)
|
|
144
|
+
if cached and cached[:2] == (st.st_mtime, st.st_size):
|
|
145
|
+
new[rel] = cached
|
|
146
|
+
continue
|
|
147
|
+
with open(full, encoding="utf-8", errors="replace") as fh:
|
|
148
|
+
new[rel] = (st.st_mtime, st.st_size, parse_note(fh.read(), rel, st.st_mtime))
|
|
149
|
+
except OSError:
|
|
150
|
+
continue # deleted or unreadable mid-scan
|
|
151
|
+
_CACHE[vault] = new
|
|
152
|
+
return Notes({rel: entry[2] for rel, entry in new.items()})
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def tok(text):
|
|
156
|
+
"""Rough token estimate shown to the agent so it can decide whether a fetch is worth it."""
|
|
157
|
+
# shortcut: chars/2 measured on Polish notes (~1.8 chars/token, 2026-11-27); English runs ~4, so this overestimates there
|
|
158
|
+
return len(text) // 2 + 1
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def headings(text):
|
|
162
|
+
"""Yield (line_index, level, title) for Markdown headings outside code fences."""
|
|
163
|
+
fence = False
|
|
164
|
+
for i, line in enumerate(text.splitlines()):
|
|
165
|
+
if line.lstrip().startswith("```"):
|
|
166
|
+
fence = not fence
|
|
167
|
+
m = None if fence else re.match(r"(#{1,6})\s+(.*)", line)
|
|
168
|
+
if m:
|
|
169
|
+
yield i, len(m.group(1)), m.group(2).strip()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def resolve(name, notes):
|
|
173
|
+
"""Obsidian-style lookup: exact path, else note name or alias; shortest path wins on ties."""
|
|
174
|
+
t = nfc(name).strip()
|
|
175
|
+
t = (t[:-3] if t.lower().endswith(".md") else t).lower()
|
|
176
|
+
if t in notes.by_path:
|
|
177
|
+
return notes.by_path[t]
|
|
178
|
+
base = posixpath.basename(t)
|
|
179
|
+
hits = [p for p in notes.by_name.get(base, ()) if base == t or p[:-3].lower().endswith("/" + t)]
|
|
180
|
+
return min(hits, key=len) if hits else None
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
ATTACHMENT_RE = re.compile(r"\.(?!md$)[A-Za-z0-9]{1,5}$", re.I) # ![[pic.png]] etc. are not notes
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def search(notes, query=None, tag=None, property=None, links=None):
|
|
187
|
+
if links not in (None, "broken", "orphans"):
|
|
188
|
+
raise ValueError("links must be 'broken' or 'orphans'")
|
|
189
|
+
rx = re.compile(query, re.I) if query else None
|
|
190
|
+
if property:
|
|
191
|
+
pkey, _, pval = property.partition("=")
|
|
192
|
+
pkey, pval = pkey.strip().lower(), pval.strip().lower()
|
|
193
|
+
hits = []
|
|
194
|
+
for path, n in notes.items():
|
|
195
|
+
if tag and tag.lstrip("#").lower() not in n["tags"]:
|
|
196
|
+
continue
|
|
197
|
+
if property:
|
|
198
|
+
vals = [v for k, v in n["props"].items() if k.lower() == pkey]
|
|
199
|
+
if not vals:
|
|
200
|
+
continue
|
|
201
|
+
if pval and not any(pval in v.lower() for v in as_list(vals[0])):
|
|
202
|
+
continue
|
|
203
|
+
if links == "orphans" and notes.backlinks(path):
|
|
204
|
+
continue
|
|
205
|
+
lines = []
|
|
206
|
+
if rx:
|
|
207
|
+
lines = [l.strip()[:160] for l in n["text"].splitlines() if rx.search(l)]
|
|
208
|
+
if not lines and not rx.search(path):
|
|
209
|
+
continue
|
|
210
|
+
rank = len(lines)
|
|
211
|
+
if links == "broken":
|
|
212
|
+
bad = [l for l in n["links"] if not ATTACHMENT_RE.search(l) and not resolve(l, notes)]
|
|
213
|
+
if not bad:
|
|
214
|
+
continue
|
|
215
|
+
lines = ["broken: " + ", ".join(f"[[{l}]]" for l in dict.fromkeys(bad))] + lines
|
|
216
|
+
hits.append((rank, n["mtime"], f"{path} (~{tok(n['text'])} tok)" + "".join(f"\n {l}" for l in lines[:3])))
|
|
217
|
+
hits.sort(key=lambda h: (-h[0], -h[1])) # most matching lines first, then most recently changed
|
|
218
|
+
out = [h[2] for h in hits[:MAX_RESULTS]]
|
|
219
|
+
if len(hits) > MAX_RESULTS:
|
|
220
|
+
out.append(f"... {len(hits) - MAX_RESULTS} more, narrow the query")
|
|
221
|
+
return "\n".join(out) or "No results."
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def remember(vault, write_dir, title, text, tags=None):
|
|
225
|
+
"""Create a new note in write_dir. Never edits or overwrites an existing note."""
|
|
226
|
+
title = nfc(title or "").strip()
|
|
227
|
+
if not title or len(title) > 120 or title.startswith(".") or re.search(r'[\\/:*?"<>|#^\[\]\n]', title):
|
|
228
|
+
raise ValueError("Bad title: no / \\ : * ? \" < > | # ^ [ ], no leading dot, max 120 chars")
|
|
229
|
+
vault = os.path.realpath(vault)
|
|
230
|
+
target_dir = os.path.realpath(os.path.join(vault, write_dir))
|
|
231
|
+
path = os.path.join(target_dir, title + ".md")
|
|
232
|
+
if os.path.dirname(os.path.realpath(path)) != target_dir:
|
|
233
|
+
raise ValueError("Path outside the write folder")
|
|
234
|
+
tags = ["claude", *(t.lstrip("#") for t in as_list(tags) if t and t.lstrip("#") != "claude")]
|
|
235
|
+
front = "---\ntags:\n" + "".join(f" - {t}\n" for t in tags) + f"{DATE_KEY}: {time.strftime('%Y-%m-%d')}\n---\n"
|
|
236
|
+
rel = os.path.relpath(path, vault).replace(os.sep, "/")
|
|
237
|
+
try:
|
|
238
|
+
with open(path, "x", encoding="utf-8") as f:
|
|
239
|
+
f.write(front + str(text).strip() + "\n")
|
|
240
|
+
except FileExistsError:
|
|
241
|
+
raise ValueError(f"Note already exists: {rel}; pick another title")
|
|
242
|
+
return f"Saved: {rel}"
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def section(text, heading):
|
|
246
|
+
"""Lines from the matching heading up to the next heading of the same or higher level (code fences skipped)."""
|
|
247
|
+
lines, start, level = text.splitlines(), None, 0
|
|
248
|
+
for i, lvl, title in headings(text):
|
|
249
|
+
if start is None and nfc(title).lower() == nfc(heading).strip().lower():
|
|
250
|
+
start, level = i, lvl
|
|
251
|
+
elif start is not None and lvl <= level:
|
|
252
|
+
return "\n".join(lines[start:i])
|
|
253
|
+
if start is None:
|
|
254
|
+
raise ValueError(f"No such section: {heading}")
|
|
255
|
+
return "\n".join(lines[start:])
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def outline(text):
|
|
259
|
+
"""Headings with the size of each section's own text (up to the next heading), for picking one to read."""
|
|
260
|
+
lines, hs = text.splitlines(), list(headings(text))
|
|
261
|
+
out = [f"{' ' * (lvl - 1)}{title} (~{tok(chr(10).join(lines[i:hs[k + 1][0] if k + 1 < len(hs) else None]))} tok)"
|
|
262
|
+
for k, (i, lvl, title) in enumerate(hs)]
|
|
263
|
+
return "\n".join(out) or "(no headings)"
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def read(notes, name, outline_only=False, full=False):
|
|
267
|
+
name, _, heading = name.partition("#")
|
|
268
|
+
path = resolve(name, notes)
|
|
269
|
+
if not path:
|
|
270
|
+
raise ValueError(f"No such note: {name}")
|
|
271
|
+
n = notes[path]
|
|
272
|
+
text = section(n["text"], heading) if heading else n["text"]
|
|
273
|
+
if outline_only or (not full and tok(text) > MAX_READ_TOKENS):
|
|
274
|
+
note = "" if outline_only else (f"\n\n(~{tok(text)} tok is over the {MAX_READ_TOKENS} limit: "
|
|
275
|
+
"read one section with 'Note#Heading', or pass full=true)")
|
|
276
|
+
return f"# {path} (~{tok(n['text'])} tok)\n{outline(text)}{note}"
|
|
277
|
+
outgoing = []
|
|
278
|
+
for l in dict.fromkeys(links_in(text, path)):
|
|
279
|
+
target = resolve(l, notes)
|
|
280
|
+
outgoing.append(target or f"{l} (missing)")
|
|
281
|
+
return (f"# {path}\n\n{text}\n\n---\nLinks: " + (", ".join(outgoing) or "none")
|
|
282
|
+
+ "\nBacklinks: " + (", ".join(notes.backlinks(path)) or "none"))
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def context(notes, cwd):
|
|
286
|
+
"""Project brief for a repo: the note whose `repo` property names a folder in cwd, plus ADRs and open tasks beside it."""
|
|
287
|
+
project = None
|
|
288
|
+
for part in reversed(os.path.normpath(cwd).split(os.sep)):
|
|
289
|
+
part, key = nfc(part), nfc(part).lower()
|
|
290
|
+
project = next((p for p, n in notes.items() if key in (nfc(r).lower() for r in as_list(n["props"].get("repo")))), None)
|
|
291
|
+
if project:
|
|
292
|
+
repo = part
|
|
293
|
+
break
|
|
294
|
+
if not project:
|
|
295
|
+
return ""
|
|
296
|
+
# Index only, not content: the agent pulls details with `read` when needed (keeps every session start cheap).
|
|
297
|
+
scope = posixpath.dirname(project)
|
|
298
|
+
scope = scope + "/" if scope else ""
|
|
299
|
+
in_scope = [p for p in notes if p.startswith(scope)]
|
|
300
|
+
name = lambda p: posixpath.basename(p)[:-3]
|
|
301
|
+
body = parse_frontmatter(notes[project]["text"])[1]
|
|
302
|
+
about = next((l.strip() for l in body.splitlines() if l.strip() and not l.lstrip().startswith(("#", "|", "!", "```"))), "")
|
|
303
|
+
adrs = {}
|
|
304
|
+
for p in in_scope:
|
|
305
|
+
if "adr" in notes[p]["tags"]:
|
|
306
|
+
adrs.setdefault(notes[p]["props"].get("status", "?"), []).append(name(p))
|
|
307
|
+
tasks = [(name(p), len(TASK_RE.findall(notes[p]["text"]))) for p in in_scope]
|
|
308
|
+
out = [f"Obsidian vault: repo `{repo}` → [[{name(project)}]]. {about[:200]}"]
|
|
309
|
+
out += [f"ADR {status}: " + "; ".join(sorted(ns)) for status, ns in sorted(adrs.items(), key=lambda kv: str(kv[0]))]
|
|
310
|
+
if any(n for _, n in tasks):
|
|
311
|
+
out.append("Open tasks: " + ", ".join(f"[[{t}]] {n}" for t, n in tasks if n))
|
|
312
|
+
recent = sorted(in_scope, key=lambda p: notes[p]["mtime"], reverse=True)[:3]
|
|
313
|
+
out.append("Recently changed: " + ", ".join(
|
|
314
|
+
f"[[{name(p)}]] {time.strftime('%Y-%m-%d', time.localtime(notes[p]['mtime']))}" for p in recent))
|
|
315
|
+
return "\n".join(out)
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
TOOLS = [
|
|
319
|
+
{"name": "search",
|
|
320
|
+
"description": "Search Obsidian vault notes; filters optional, ANDed.",
|
|
321
|
+
"inputSchema": {"type": "object", "properties": {
|
|
322
|
+
"query": {"type": "string", "description": "case-insensitive regex on text and path"},
|
|
323
|
+
"tag": {"type": "string"},
|
|
324
|
+
"property": {"type": "string", "description": "'key' or 'key=value substring'"},
|
|
325
|
+
"links": {"enum": ["broken", "orphans"], "description": "notes with unresolved links / no backlinks"}}},
|
|
326
|
+
"annotations": {"readOnlyHint": True}},
|
|
327
|
+
{"name": "read",
|
|
328
|
+
"description": "Read a note by [[link]] name, alias or path; 'Note#Heading' reads one section. Includes links and "
|
|
329
|
+
"backlinks. For big notes call with outline=true first (headings + ~tokens), then read one section.",
|
|
330
|
+
"inputSchema": {"type": "object", "properties": {
|
|
331
|
+
"name": {"type": "string"}, "outline": {"type": "boolean"},
|
|
332
|
+
"full": {"type": "boolean", "description": f"return text over {MAX_READ_TOKENS} tokens anyway"}},
|
|
333
|
+
"required": ["name"]},
|
|
334
|
+
"annotations": {"readOnlyHint": True}},
|
|
335
|
+
]
|
|
336
|
+
REMEMBER = {
|
|
337
|
+
"name": "remember",
|
|
338
|
+
"description": "Save a new note (decision, finding, lesson) to the vault's inbox folder for the user to review. "
|
|
339
|
+
"Cannot edit existing notes. Link related notes with [[name]] in text.",
|
|
340
|
+
"inputSchema": {"type": "object", "properties": {
|
|
341
|
+
"title": {"type": "string"}, "text": {"type": "string"},
|
|
342
|
+
"tags": {"type": "array", "items": {"type": "string"}}}, "required": ["title", "text"]},
|
|
343
|
+
"annotations": {"readOnlyHint": False, "destructiveHint": False}}
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def call_tool(name, args, vault, write_dir):
|
|
347
|
+
if name == "remember" and write_dir:
|
|
348
|
+
return remember(vault, write_dir, args.get("title"), args.get("text", ""), args.get("tags"))
|
|
349
|
+
if name == "search":
|
|
350
|
+
return search(load(vault), args.get("query"), args.get("tag"), args.get("property"), args.get("links"))
|
|
351
|
+
if name == "read":
|
|
352
|
+
return read(load(vault), str(args.get("name", "")), bool(args.get("outline")), bool(args.get("full")))
|
|
353
|
+
raise ValueError(f"Unknown tool: {name}")
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def handle(msg, vault, write_dir=None):
|
|
357
|
+
method, params = msg.get("method"), msg.get("params") or {}
|
|
358
|
+
if method == "initialize":
|
|
359
|
+
return {"protocolVersion": params.get("protocolVersion", "2025-06-18"), "capabilities": {"tools": {}},
|
|
360
|
+
"serverInfo": {"name": "obsidian-lite-mcp", "version": __version__}}
|
|
361
|
+
if method == "ping":
|
|
362
|
+
return {}
|
|
363
|
+
if method == "tools/list":
|
|
364
|
+
return {"tools": TOOLS + ([REMEMBER] if write_dir else [])}
|
|
365
|
+
if method == "tools/call":
|
|
366
|
+
args = params.get("arguments")
|
|
367
|
+
try:
|
|
368
|
+
text = call_tool(params.get("name"), args if isinstance(args, dict) else {}, vault, write_dir)
|
|
369
|
+
return {"content": [{"type": "text", "text": text}]}
|
|
370
|
+
except Exception as e: # a bad call must not kill the server; the agent sees the reason and can retry
|
|
371
|
+
return {"content": [{"type": "text", "text": f"{type(e).__name__}: {e}"}], "isError": True}
|
|
372
|
+
raise LookupError(method)
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def error(id_, code, message):
|
|
376
|
+
return {"jsonrpc": "2.0", "id": id_, "error": {"code": code, "message": message}}
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def respond(line, vault, write_dir):
|
|
380
|
+
"""One JSON-RPC line in, one reply (or None for notifications) out."""
|
|
381
|
+
try:
|
|
382
|
+
msg = json.loads(line)
|
|
383
|
+
except ValueError:
|
|
384
|
+
return error(None, -32700, "Parse error")
|
|
385
|
+
if not isinstance(msg, dict) or not isinstance(msg.get("method"), str):
|
|
386
|
+
return error(msg.get("id") if isinstance(msg, dict) else None, -32600, "Invalid request")
|
|
387
|
+
if "id" not in msg:
|
|
388
|
+
return None # notification
|
|
389
|
+
try:
|
|
390
|
+
return {"jsonrpc": "2.0", "id": msg["id"], "result": handle(msg, vault, write_dir)}
|
|
391
|
+
except LookupError as e:
|
|
392
|
+
return error(msg["id"], -32601, f"Method not found: {e}")
|
|
393
|
+
except Exception as e:
|
|
394
|
+
return error(msg["id"], -32603, f"Internal error: {e}")
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def main():
|
|
398
|
+
for stream in (sys.stdin, sys.stdout):
|
|
399
|
+
stream.reconfigure(encoding="utf-8", newline="\n") # Windows consoles default to a legacy code page
|
|
400
|
+
if sys.argv[1:2] == ["context"]: # context VAULT CWD -> brief for a SessionStart hook
|
|
401
|
+
if len(sys.argv) == 4 and os.path.isdir(sys.argv[2]) and os.environ.get("VAULT_CONTEXT") != "off":
|
|
402
|
+
print(context(load(sys.argv[2]), sys.argv[3]))
|
|
403
|
+
return
|
|
404
|
+
if sys.argv[1:2] in (["--version"], ["-V"]):
|
|
405
|
+
print(__version__)
|
|
406
|
+
return
|
|
407
|
+
args, write_dir = sys.argv[1:], None
|
|
408
|
+
if "--write-dir" in args:
|
|
409
|
+
i = args.index("--write-dir")
|
|
410
|
+
if i + 1 >= len(args):
|
|
411
|
+
sys.exit("--write-dir needs a folder name")
|
|
412
|
+
write_dir, args = args[i + 1], args[:i] + args[i + 2:]
|
|
413
|
+
if not args and "VAULT_PATH" not in os.environ:
|
|
414
|
+
sys.exit(__doc__.strip())
|
|
415
|
+
vault = os.path.abspath(args[0] if args else os.environ["VAULT_PATH"])
|
|
416
|
+
if not os.path.isdir(vault):
|
|
417
|
+
sys.exit(f"Vault folder not found: {vault}")
|
|
418
|
+
if write_dir:
|
|
419
|
+
target = os.path.realpath(os.path.join(vault, write_dir))
|
|
420
|
+
if not target.startswith(os.path.realpath(vault) + os.sep) or not os.path.isdir(target):
|
|
421
|
+
sys.exit(f"--write-dir {write_dir!r} must be an existing folder inside {vault}")
|
|
422
|
+
for line in sys.stdin:
|
|
423
|
+
if line.strip():
|
|
424
|
+
reply = respond(line, vault, write_dir)
|
|
425
|
+
if reply is not None:
|
|
426
|
+
sys.stdout.write(json.dumps(reply, ensure_ascii=False) + "\n")
|
|
427
|
+
sys.stdout.flush()
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
if __name__ == "__main__":
|
|
431
|
+
main()
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "obsidian-lite-mcp"
|
|
3
|
+
dynamic = ["version"]
|
|
4
|
+
description = "Small MCP server that reads an Obsidian vault from disk: Obsidian-accurate links and backlinks, sections, search. No app, no dependencies."
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
license = "MIT"
|
|
7
|
+
requires-python = ">=3.10"
|
|
8
|
+
dependencies = []
|
|
9
|
+
keywords = ["mcp", "obsidian", "claude", "model-context-protocol", "markdown"]
|
|
10
|
+
|
|
11
|
+
[project.urls]
|
|
12
|
+
Homepage = "https://github.com/DabuSoft-pl/obsidian-lite-mcp"
|
|
13
|
+
Issues = "https://github.com/DabuSoft-pl/obsidian-lite-mcp/issues"
|
|
14
|
+
|
|
15
|
+
[project.scripts]
|
|
16
|
+
obsidian-lite-mcp = "obsidian_lite_mcp:main"
|
|
17
|
+
|
|
18
|
+
[build-system]
|
|
19
|
+
requires = ["setuptools>=77"]
|
|
20
|
+
build-backend = "setuptools.build_meta"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools]
|
|
23
|
+
py-modules = ["obsidian_lite_mcp"]
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.dynamic]
|
|
26
|
+
version = { attr = "obsidian_lite_mcp.__version__" }
|