-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathindex.ts
291 lines (261 loc) · 8.42 KB
/
index.ts
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
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js"
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import {
CallToolRequestSchema,
ListToolsRequestSchema,
ToolSchema,
} from "@modelcontextprotocol/sdk/types.js"
import fs from "fs/promises"
import path from "path"
import os from "os"
import { z } from "zod"
import { zodToJsonSchema } from "zod-to-json-schema"
// Maximum number of search results to return
const SEARCH_LIMIT = 200
// Command line argument parsing
const args = process.argv.slice(2)
if (args.length === 0) {
console.error("Usage: mcp-obsidian <vault-directory>")
process.exit(1)
}
// Normalize all paths consistently
function normalizePath(p: string): string {
return path.normalize(p).toLowerCase()
}
function expandHome(filepath: string): string {
if (filepath.startsWith("~/") || filepath === "~") {
return path.join(os.homedir(), filepath.slice(1))
}
return filepath
}
// Store allowed directories in normalized form
const vaultDirectories = [normalizePath(path.resolve(expandHome(args[0])))]
// Validate that all directories exist and are accessible
await Promise.all(
args.map(async (dir) => {
try {
const stats = await fs.stat(dir)
if (!stats.isDirectory()) {
console.error(`Error: ${dir} is not a directory`)
process.exit(1)
}
} catch (error) {
console.error(`Error accessing directory ${dir}:`, error)
process.exit(1)
}
})
)
// Security utilities
async function validatePath(requestedPath: string): Promise<string> {
// Ignore hidden files/directories starting with "."
const pathParts = requestedPath.split(path.sep)
if (pathParts.some((part) => part.startsWith("."))) {
throw new Error("Access denied - hidden files/directories not allowed")
}
const expandedPath = expandHome(requestedPath)
const absolute = path.isAbsolute(expandedPath)
? path.resolve(expandedPath)
: path.resolve(process.cwd(), expandedPath)
const normalizedRequested = normalizePath(absolute)
// Check if path is within allowed directories
const isAllowed = vaultDirectories.some((dir) =>
normalizedRequested.startsWith(dir)
)
if (!isAllowed) {
throw new Error(
`Access denied - path outside allowed directories: ${absolute} not in ${vaultDirectories.join(
", "
)}`
)
}
// Handle symlinks by checking their real path
try {
const realPath = await fs.realpath(absolute)
const normalizedReal = normalizePath(realPath)
const isRealPathAllowed = vaultDirectories.some((dir) =>
normalizedReal.startsWith(dir)
)
if (!isRealPathAllowed) {
throw new Error(
"Access denied - symlink target outside allowed directories"
)
}
return realPath
} catch (error) {
// For new files that don't exist yet, verify parent directory
const parentDir = path.dirname(absolute)
try {
const realParentPath = await fs.realpath(parentDir)
const normalizedParent = normalizePath(realParentPath)
const isParentAllowed = vaultDirectories.some((dir) =>
normalizedParent.startsWith(dir)
)
if (!isParentAllowed) {
throw new Error(
"Access denied - parent directory outside allowed directories"
)
}
return absolute
} catch {
throw new Error(`Parent directory does not exist: ${parentDir}`)
}
}
}
// Schema definitions
const ReadNotesArgsSchema = z.object({
paths: z.array(z.string()),
})
const SearchNotesArgsSchema = z.object({
query: z.string(),
})
const ToolInputSchema = ToolSchema.shape.inputSchema
type ToolInput = z.infer<typeof ToolInputSchema>
// Server setup
const server = new Server(
{
name: "mcp-obsidian",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
)
/**
* Search for notes in the allowed directories that match the query.
* @param query - The query to search for.
* @returns An array of relative paths to the notes (from root) that match the query.
*/
async function searchNotes(query: string): Promise<string[]> {
const results: string[] = []
async function search(basePath: string, currentPath: string) {
const entries = await fs.readdir(currentPath, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(currentPath, entry.name)
try {
// Validate each path before processing
await validatePath(fullPath)
let matches = entry.name.toLowerCase().includes(query.toLowerCase())
try {
matches =
matches ||
new RegExp(query.replace(/[*]/g, ".*"), "i").test(entry.name)
} catch {
// Ignore invalid regex
}
if (entry.name.endsWith(".md") && matches) {
// Turn into relative path
results.push(fullPath.replace(basePath, ""))
}
if (entry.isDirectory()) {
await search(basePath, fullPath)
}
} catch (error) {
// Skip invalid paths during search
continue
}
}
}
await Promise.all(vaultDirectories.map((dir) => search(dir, dir)))
return results
}
// Tool handlers
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "read_notes",
description:
"Read the contents of multiple notes. Each note's content is returned with its " +
"path as a reference. Failed reads for individual notes won't stop " +
"the entire operation. Reading too many at once may result in an error.",
inputSchema: zodToJsonSchema(ReadNotesArgsSchema) as ToolInput,
},
{
name: "search_notes",
description:
"Searches for a note by its name. The search " +
"is case-insensitive and matches partial names. " +
"Queries can also be a valid regex. Returns paths of the notes " +
"that match the query.",
inputSchema: zodToJsonSchema(SearchNotesArgsSchema) as ToolInput,
},
],
}
})
server.setRequestHandler(CallToolRequestSchema, async (request) => {
try {
const { name, arguments: args } = request.params
switch (name) {
case "read_notes": {
const parsed = ReadNotesArgsSchema.safeParse(args)
if (!parsed.success) {
throw new Error(`Invalid arguments for read_notes: ${parsed.error}`)
}
const results = await Promise.all(
parsed.data.paths.map(async (filePath: string) => {
try {
const validPath = await validatePath(
path.join(vaultDirectories[0], filePath)
)
const content = await fs.readFile(validPath, "utf-8")
return `${filePath}:\n${content}\n`
} catch (error) {
const errorMessage =
error instanceof Error ? error.message : String(error)
return `${filePath}: Error - ${errorMessage}`
}
})
)
return {
content: [{ type: "text", text: results.join("\n---\n") }],
}
}
case "search_notes": {
const parsed = SearchNotesArgsSchema.safeParse(args)
if (!parsed.success) {
throw new Error(`Invalid arguments for search_notes: ${parsed.error}`)
}
const results = await searchNotes(parsed.data.query)
const limitedResults = results.slice(0, SEARCH_LIMIT)
return {
content: [
{
type: "text",
text:
(limitedResults.length > 0
? limitedResults.join("\n")
: "No matches found") +
(results.length > SEARCH_LIMIT
? `\n\n... ${
results.length - SEARCH_LIMIT
} more results not shown.`
: ""),
},
],
}
}
default:
throw new Error(`Unknown tool: ${name}`)
}
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error)
return {
content: [{ type: "text", text: `Error: ${errorMessage}` }],
isError: true,
}
}
})
// Start server
async function runServer() {
const transport = new StdioServerTransport()
await server.connect(transport)
console.error("MCP Obsidian Server running on stdio")
console.error("Allowed directories:", vaultDirectories)
}
runServer().catch((error) => {
console.error("Fatal error running server:", error)
process.exit(1)
})