Skip to main content
Glama
nojiritakeshi

Obsidian Translation MCP Server

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

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query (searches in both title and content)
directoryNoDirectory to search in (relative to vault root, optional)
maxResultsNoMaximum number of results to return
includeContentNoWhether to include content excerpts in results

Implementation Reference

  • 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']
        }
      };
  • 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}`);
      }
    }
  • 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);
      }
    });
  • 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}`);
      }
    }
  • 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;
    }
  • SearchResult interface type definition with path, title, excerpt, and matches fields.
    export interface SearchResult {
      path: string;
      title: string;
      excerpt: string;
      matches: number;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations provided, so the description must fully disclose behavior. It only states 'Search for notes' without clarifying read-only nature, performance, or what happens with no results. The behavioral profile is insufficiently described.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single concise sentence with no wasted words. However, it could be slightly more informative without adding length, e.g., specifying 'full-text search' or 'includes content excerpts'.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no output schema, the description should hint at return format or scope. It does not mention that results include content excerpts (default true) or that maxResults limits output. The agent lacks context on what to expect from the response.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema details all four parameters with descriptions (100% coverage). The tool description adds no new information beyond what the schema already provides, so it meets the baseline but does not enhance understanding.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states it searches notes by content or title. However, it does not explicitly differentiate from the sibling 'search_obsidian_notes_by_tags', which is a distinct search method. The purpose is clear but could be more specific.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance on when to use this tool versus alternatives like 'search_obsidian_notes_by_tags'. The description does not mention when to search by content/title vs. tags, leaving the agent to infer without explicit instruction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/nojiritakeshi/obsidian-translate-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server