Skip to main content
Glama
disnet
by disnet

search_notes_sql

Execute SQL SELECT queries to search and retrieve notes from your Flint Note vault, enabling precise data extraction from notes and metadata tables.

Instructions

Direct SQL search against notes database for maximum flexibility. Only SELECT queries allowed.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSQL SELECT query. Tables: notes (id, title, content, type, filename, path, created, updated, size), note_metadata (note_id, key, value, value_type)
paramsNoOptional parameters for parameterized queries
limitNoMaximum number of results
timeoutNoQuery timeout in milliseconds
vault_idNoOptional vault ID to operate on. If not provided, uses the current active vault.
fieldsNoOptional array of field names to include in response. Supports dot notation for nested fields (e.g. "metadata.tags") and wildcard patterns (e.g. "metadata.*"). If not specified, all fields are returned.

Implementation Reference

  • MCP tool handler: validates input, resolves vault context, executes search via HybridSearchManager, applies field filtering, returns JSON-formatted results.
    handleSearchNotesSQL = async (args: SearchNotesSqlArgs) => {
      // Validate arguments
      validateToolArgs('search_notes_sql', args);
    
      const { hybridSearchManager } = await this.resolveVaultContext(args.vault_id);
    
      const results = await hybridSearchManager.searchNotesSQL(args);
    
      // Apply field filtering if specified
      const filteredResults = filterSearchResults(results, args.fields);
    
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(filteredResults, null, 2)
          }
        ]
      };
    };
  • Registers the tool handler in the MCP server's CallToolRequestSchema switch statement, mapping 'search_notes_sql' calls to SearchHandlers.handleSearchNotesSQL.
    case 'search_notes_sql':
      return await this.searchHandlers.handleSearchNotesSQL(
        args as unknown as SearchNotesSqlArgs
      );
  • Tool schema definition including name, description, and detailed inputSchema for parameters like query, params, limit, etc.
    {
      name: 'search_notes_sql',
      description:
        'Direct SQL search against notes database for maximum flexibility. Only SELECT queries allowed.',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description:
              'SQL SELECT query. Tables: notes (id, title, content, type, filename, path, created, updated, size), note_metadata (note_id, key, value, value_type)'
          },
          params: {
            type: 'array',
            items: {
              oneOf: [
                { type: 'string' },
                { type: 'number' },
                { type: 'boolean' },
                { type: 'null' }
              ]
            },
            description: 'Optional parameters for the SQL query'
          },
          limit: {
            type: 'number',
            description: 'Maximum number of results to return'
          },
          timeout: {
            type: 'number',
            description: 'Query timeout in milliseconds',
            default: 5000
          },
          vault_id: {
            type: 'string',
            description:
              'Optional vault ID to search in. If not provided, uses the current active vault.'
          },
          fields: {
            type: 'array',
            items: {
              type: 'string'
            },
            description:
              'Optional list of fields to include in response (id, title, content, type, filename, path, created, updated, size, metadata)'
          }
        },
        required: ['query']
      }
    },
  • Core SQL execution logic in HybridSearchManager: validates query safety, executes SELECT with params and limits, handles aggregation vs regular queries, converts results to standardized SearchResult format.
    async searchNotesSQL(options: SqlSearchOptions): Promise<SearchResponse> {
      const startTime = Date.now();
      const connection = await this.getReadOnlyConnection();
    
      // Validate SQL query for safety
      this.validateSQLQuery(options.query);
    
      try {
        const limit = options.limit ?? 1000;
        const timeout = options.timeout ?? 30000;
    
        // Set query timeout
        await connection.run(`PRAGMA busy_timeout = ${timeout}`);
    
        // Execute query with limit
        let sql = options.query.trim();
        if (!sql.toLowerCase().includes('limit')) {
          sql += ` LIMIT ${limit}`;
        }
    
        const rows = await connection.all<SearchRow | Record<string, unknown>>(
          sql,
          options.params || []
        );
    
        // Detect if this is an aggregation query or custom SQL
        const isAggregationQuery = this.isAggregationQuery(sql);
    
        let results: SearchResult[];
        if (isAggregationQuery) {
          // For aggregation queries, return raw results with custom columns preserved
          results = rows.map(row => ({
            ...row, // Preserve all custom aggregation columns first
            id: String(row.id || ''),
            title: String(row.title || ''),
            type: String(row.type || ''),
            tags: [],
            score: 1.0,
            snippet: '',
            lastUpdated: String(row.updated || ''),
            filename: String(row.filename || ''),
            path: String(row.path || ''),
            created: String(row.created || ''),
            modified: String(row.updated || ''),
            size: Number(row.size ?? 0),
            metadata: {
              title: String(row.title || ''),
              type: String(row.type || ''),
              created: String(row.created || ''),
              updated: String(row.updated || ''),
              filename: String(row.filename || '')
            }
          }));
        } else {
          // For regular note queries, convert to SearchResult format
          results = await this.convertRowsToResults(rows as SearchRow[], connection);
        }
    
        const queryTime = Date.now() - startTime;
    
        return {
          results,
          total: results.length,
          has_more: results.length >= limit,
          query_time_ms: queryTime
        };
      } catch (error) {
        throw new Error(
          `SQL search failed: ${error instanceof Error ? error.message : 'Unknown error'}`
        );
      }
    }
  • TypeScript interface defining the input arguments for the search_notes_sql tool.
    export interface SearchNotesSqlArgs {
      query: string;
      params?: (string | number | boolean | null)[];
      limit?: number;
      timeout?: number;
      vault_id?: string;
      fields?: string[];
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key behavioral traits: it's a read-only operation ('Only SELECT queries allowed'), operates on a notes database, and offers maximum flexibility. However, it doesn't mention potential risks like SQL injection, performance impacts, or error handling, which could be useful context for an AI agent.

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

Conciseness5/5

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

The description is extremely concise and front-loaded, consisting of just two sentences that efficiently convey the tool's purpose and key constraint. Every word earns its place, with no wasted text or redundancy, making it easy for an AI agent to parse quickly.

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

Completeness3/5

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

Given the tool's complexity (SQL-based search with 6 parameters) and no annotations or output schema, the description is somewhat complete but has gaps. It covers the purpose and constraint well, but lacks details on return format, error cases, or performance considerations. For a flexible SQL tool, more context on results structure or limitations would be helpful.

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?

Schema description coverage is 100%, so the schema already documents all 6 parameters thoroughly. The description adds no additional parameter semantics beyond what's in the schema (e.g., it doesn't explain SQL syntax or table relationships further). This meets the baseline of 3 when the schema does the heavy lifting, but doesn't compensate with extra insights.

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

Purpose5/5

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

The description clearly states the tool's purpose with specific verb ('Direct SQL search') and resource ('against notes database'), distinguishing it from sibling tools like 'search_notes' or 'search_notes_advanced' by emphasizing maximum flexibility through SQL. It explicitly mentions 'Only SELECT queries allowed', which further clarifies its scope compared to other note manipulation tools.

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

Usage Guidelines5/5

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

The description provides explicit usage guidelines by stating 'Only SELECT queries allowed', which tells the agent when to use this tool (for flexible SQL queries) and when not to (for non-SELECT operations). It implies alternatives like 'search_notes' or 'search_notes_advanced' for simpler searches, as this tool is for maximum flexibility with SQL.

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/disnet/flint-note'

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