search_obsidian_notes
Search notes in your Obsidian vault by content or title to quickly find relevant information. Narrow results by directory and control the number returned.
Instructions
Search for notes in Obsidian vault by content or title
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| query | Yes | Search query (searches in both title and content) | |
| directory | No | Directory to search in (relative to vault root, optional) | |
| maxResults | No | Maximum number of results to return | |
| includeContent | No | Whether to include content excerpts in results |
Implementation Reference
- src/tools/search.ts:16-45 (schema)Tool schema definition for 'search_obsidian_notes'. Defines name, description, and inputSchema with parameters: query (required string), directory (optional string), maxResults (optional number, default 10), includeContent (optional boolean, default true).
static getSearchToolDefinition(): Tool { return { name: 'search_obsidian_notes', description: 'Search for notes in Obsidian vault by content or title', inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'Search query (searches in both title and content)' }, directory: { type: 'string', description: 'Directory to search in (relative to vault root, optional)', default: '' }, maxResults: { type: 'number', description: 'Maximum number of results to return', default: 10 }, includeContent: { type: 'boolean', description: 'Whether to include content excerpts in results', default: true } }, required: ['query'] } }; - src/tools/search.ts:88-129 (handler)Core handler method 'searchNotes' in SearchTool class. Accepts query, directory, maxResults, includeContent. Uses FileSystemHelper.searchFiles() to find matching .md files, parses frontmatter via gray-matter, extracts title, counts matches, creates excerpts, and returns sorted SearchResult[].
async searchNotes( query: string, directory: string = '', maxResults: number = 10, includeContent: boolean = true ): Promise<SearchResult[]> { try { const files = await this.fileSystem.searchFiles(query, directory); const results: SearchResult[] = []; for (const filePath of files.slice(0, maxResults)) { try { const rawContent = await this.fileSystem.readFile(filePath); const { data: frontmatter, content } = matter(rawContent); const title = frontmatter.title || filePath.split('/').pop()?.replace('.md', '') || 'Untitled'; // 検索語に一致する部分を抽出 const excerpt = includeContent ? this.extractExcerpt(content, query) : ''; // 一致数をカウント const titleMatches = (title.toLowerCase().match(new RegExp(query.toLowerCase(), 'g')) || []).length; const contentMatches = (content.toLowerCase().match(new RegExp(query.toLowerCase(), 'g')) || []).length; results.push({ path: filePath, title, excerpt, matches: titleMatches + contentMatches }); } catch (error) { // 個別のファイル読み込みエラーは無視 console.warn(`Failed to read file ${filePath}:`, error); } } // 一致数でソート return results.sort((a, b) => b.matches - a.matches); } catch (error) { throw new Error(`Search failed: ${error}`); } } - src/index.ts:256-285 (handler)MCP request handler (handleSearchNotes) in ObsidianMCPServer that dispatches to SearchTool.searchNotes(). Validates 'query' param, delegates to the handler, and formats results as a text response.
private async handleSearchNotes(args: any) { const { query, directory, maxResults, includeContent } = args; if (!query) { throw new McpError(ErrorCode.InvalidParams, 'Query is required'); } const results = await this.searchTool.searchNotes( query, directory, maxResults, includeContent ); const resultsText = results.map(result => `📁 ${result.path}\\n` + `📝 ${result.title}\\n` + `🎯 一致数: ${result.matches}\\n` + `📄 抜粋: ${result.excerpt}\\n` ).join('\\n---\\n\\n'); return { content: [ { type: 'text', text: `🔍 検索結果 (${results.length}件):\\n\\n${resultsText}` } ] }; } - src/index.ts:89-100 (registration)Tool registration in ListToolsRequestSchema handler. 'SearchTool.getSearchToolDefinition()' is called to register the tool schema with the MCP server.
this.server.setRequestHandler(ListToolsRequestSchema, async () => { return { tools: [ TranslateTool.getToolDefinition(), NotesTool.getCreateNoteToolDefinition(), NotesTool.getReadNoteToolDefinition(), NotesTool.getUpdateNoteToolDefinition(), SearchTool.getSearchToolDefinition(), SearchTool.getSearchByTagsToolDefinition(), ], }; }); - src/index.ts:103-143 (registration)Tool dispatch in CallToolRequestSchema switch statement. When name === 'search_obsidian_notes', it calls this.handleSearchNotes(args).
this.server.setRequestHandler(CallToolRequestSchema, async (request) => { const { name, arguments: args } = request.params; try { switch (name) { case 'translate_obsidian_note': return await this.handleTranslateNote(args); case 'create_obsidian_note': return await this.handleCreateNote(args); case 'read_obsidian_note': return await this.handleReadNote(args); case 'update_obsidian_note': return await this.handleUpdateNote(args); case 'search_obsidian_notes': return await this.handleSearchNotes(args); case 'search_obsidian_notes_by_tags': return await this.handleSearchNotesByTags(args); default: throw new McpError( ErrorCode.MethodNotFound, `Unknown tool: ${name}` ); } } catch (error) { if (error instanceof McpError) { throw error; } // カスタムエラーコードの処理 const errorMessage = error instanceof Error ? error.message : String(error); const errorCode = this.mapErrorCode(errorMessage); throw new McpError(errorCode, errorMessage); } }); - src/utils/file-system.ts:139-162 (helper)FileSystemHelper.searchFiles() - utility that recursively finds all .md files, reads each file, and returns relative paths of files containing the search term (case-insensitive).
async searchFiles(searchTerm: string, directory: string = ''): Promise<string[]> { try { const dirPath = this.getAbsolutePath(directory); const files = await this.getAllMarkdownFiles(dirPath); const results: string[] = []; for (const file of files) { try { const content = await fs.readFile(file, 'utf-8'); if (content.toLowerCase().includes(searchTerm.toLowerCase())) { // 相対パスに変換 const relativePath = file.replace(this.vaultPath, '').replace(/^\//, ''); results.push(relativePath); } } catch { // ファイル読み込みエラーは無視 } } return results; } catch (error) { throw new Error(`Search failed: ${error}`); } } - src/utils/file-system.ts:169-191 (helper)FileSystemHelper.getAllMarkdownFiles() - recursively traverses directories (skipping hidden dirs) to find all .md files.
private async getAllMarkdownFiles(directory: string): Promise<string[]> { const files: string[] = []; try { const items = await fs.readdir(directory, { withFileTypes: true }); for (const item of items) { const itemPath = join(directory, item.name); if (item.isDirectory() && !item.name.startsWith('.')) { // 隠しディレクトリ以外を再帰的に検索 const subFiles = await this.getAllMarkdownFiles(itemPath); files.push(...subFiles); } else if (item.isFile() && item.name.endsWith('.md')) { files.push(itemPath); } } } catch { // ディレクトリアクセスエラーは無視 } return files; } - src/types/index.ts:53-58 (schema)SearchResult interface type definition with path, title, excerpt, and matches fields.
export interface SearchResult { path: string; title: string; excerpt: string; matches: number; }