Skip to main content
Glama

Query Base

query_base
Read-onlyIdempotent

Execute filters from a .base file to retrieve matching note paths, optionally overlaying a named view's filters and sorting.

Instructions

Run a Base file's filters against the vault and return matching note paths. Optionally pick a named view to apply that view's filters and ordering on top of the base-level filters. Supported filter syntax (subset of Obsidian's full DSL): function calls taggedWith(file, "tag"), file.hasTag("tag"), file.inFolder("path"); comparisons key == "val", key != x, key contains x, >=, <=, >, <; combinators and:, or:, not:. Unsupported clauses are reported as warnings and treated as match-all.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYesVault-relative path to the .base file.
viewNoOptional view name (or view type) to apply on top of the base-level filters.
limitNoMaximum number of matching notes to return (1-1000, default: 100).
includeFrontmatterNoIf true, include each row's frontmatter in the output.

Implementation Reference

  • Core implementation of the query_base tool logic. Applies Base document filters (and optionally view-level filters) to an array of pre-built rows, sorts by view order, and returns matching rows plus warnings.
    export function queryBase(
      rows: readonly BaseRow[],
      base: BaseDocument,
      viewName?: string,
    ): QueryResult {
      const ctx: EvaluationContext = { warnings: [] };
      const baseFilter = flattenFilter(base.filters as BaseFilter | BaseFilter[] | undefined);
      let viewFilter: BaseFilter | undefined;
      let order: string[] | undefined;
    
      if (viewName && Array.isArray(base.views)) {
        const view = base.views.find((v) => v.name === viewName || v.type === viewName);
        if (!view) {
          ctx.warnings.push(`View not found: "${viewName}"; using base-level filters only.`);
        } else {
          viewFilter = flattenFilter(view.filters as BaseFilter | BaseFilter[] | undefined);
          order = Array.isArray(view.order) ? view.order : undefined;
        }
      }
    
      const matches = rows.filter((row) =>
        evaluateFilter(row, baseFilter, ctx) && evaluateFilter(row, viewFilter, ctx),
      );
    
      if (order && order.length > 0) {
        matches.sort((a, b) => {
          for (const key of order!) {
            const va = readProperty(a, key);
            const vb = readProperty(b, key);
            if (va === vb) continue;
            if (va === undefined || va === null) return 1;
            if (vb === undefined || vb === null) return -1;
            if (typeof va === "number" && typeof vb === "number") return va - vb;
            return String(va).localeCompare(String(vb));
          }
          return 0;
        });
      }
    
      return { rows: matches, warnings: ctx.warnings };
    }
  • Registration of the 'query_base' tool on the MCP server, including its input schema (path, view, limit, includeFrontmatter) and the async handler that reads the base file, parses it, loads all notes, builds rows, and calls the queryBase library function.
    server.registerTool(
      "query_base",
      {
        title: "Query Base",
        description:
          "Run a Base file's filters against the vault and return matching note paths. Optionally pick a named view to apply that view's filters and ordering on top of the base-level filters. Supported filter syntax (subset of Obsidian's full DSL): function calls `taggedWith(file, \"tag\")`, `file.hasTag(\"tag\")`, `file.inFolder(\"path\")`; comparisons `key == \"val\"`, `key != x`, `key contains x`, `>=`, `<=`, `>`, `<`; combinators `and:`, `or:`, `not:`. Unsupported clauses are reported as warnings and treated as match-all.",
        annotations: {
          readOnlyHint: true,
          idempotentHint: true,
          openWorldHint: false,
        },
        inputSchema: {
          path: z
            .string()
            .min(1)
            .describe("Vault-relative path to the .base file."),
          view: z
            .string()
            .optional()
            .describe("Optional view name (or view type) to apply on top of the base-level filters."),
          limit: z
            .number()
            .int()
            .min(1)
            .max(1000)
            .optional()
            .default(100)
            .describe("Maximum number of matching notes to return (1-1000, default: 100)."),
          includeFrontmatter: z
            .boolean()
            .optional()
            .default(false)
            .describe("If true, include each row's frontmatter in the output."),
        },
      },
      async ({ path: basePath, view, limit, includeFrontmatter }) => {
        try {
          const raw = await readBaseFile(vaultPath, basePath);
          const { doc, warnings } = parseBaseFile(raw);
          const notes = await listNotes(vaultPath);
          const rows = await mapConcurrent(notes, 16, async (notePath) => {
            const content = await readNote(vaultPath, notePath);
            return buildRow(notePath, content);
          });
          const validRows = rows.filter((r): r is NonNullable<typeof r> => r !== undefined);
          const result = queryBase(validRows, doc, view);
          const allWarnings = [...warnings, ...result.warnings];
          const truncated = result.rows.slice(0, limit);
    
          const lines: string[] = [];
          lines.push(`Base: ${basePath}${view ? ` (view: ${view})` : ""}`);
          lines.push(
            `Matched ${result.rows.length} note(s)${result.rows.length > limit ? ` (showing first ${limit})` : ""}`,
          );
          if (allWarnings.length > 0) {
            lines.push("");
            lines.push("Warnings:");
            for (const w of allWarnings) lines.push(`  - ${w}`);
          }
          lines.push("");
          for (const row of truncated) {
            lines.push(`- ${row.path}`);
            if (includeFrontmatter && Object.keys(row.frontmatter).length > 0) {
              for (const [k, v] of Object.entries(row.frontmatter)) {
                lines.push(`    ${k}: ${JSON.stringify(v)}`);
              }
            }
          }
          return textResult(lines.join("\n"));
        } catch (err) {
          log.error("query_base failed", { tool: "query_base", err: err as Error });
          return errorResult(`Error querying base: ${sanitizeError(err)}`);
        }
      },
    );
  • Input schema for query_base: path (required string), view (optional string), limit (optional number 1-1000, default 100), includeFrontmatter (optional boolean, default false).
    inputSchema: {
      path: z
        .string()
        .min(1)
        .describe("Vault-relative path to the .base file."),
      view: z
        .string()
        .optional()
        .describe("Optional view name (or view type) to apply on top of the base-level filters."),
      limit: z
        .number()
        .int()
        .min(1)
        .max(1000)
        .optional()
        .default(100)
        .describe("Maximum number of matching notes to return (1-1000, default: 100)."),
      includeFrontmatter: z
        .boolean()
        .optional()
        .default(false)
        .describe("If true, include each row's frontmatter in the output."),
    },
  • Helper that builds a BaseRow from a note's path and content, extracting frontmatter and tags for use by query_base.
    export function buildRow(path: string, content: string): BaseRow {
      const { data } = parseFrontmatter(content);
      return {
        path,
        frontmatter: data,
        tags: extractTags(content),
      };
    }
  • Helper that normalizes a filter (arrays become 'and' combinators) for use by the query_base handler.
    function flattenFilter(filter: BaseFilter | BaseFilter[] | undefined): BaseFilter | undefined {
      if (filter === undefined) return undefined;
      if (Array.isArray(filter)) return { and: filter };
      return filter;
    }
Behavior5/5

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

Annotations already declare readOnlyHint and idempotentHint true, indicating safety. The description adds valuable behavioral details: supported filter syntax, handling of unsupported clauses as warnings, and that the tool returns only paths. No contradictions.

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 concise, with the main purpose stated first, followed by optional usage and filter syntax details. Every sentence is necessary and well-structured.

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

Completeness5/5

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

Given the lack of an output schema, the description adequately specifies that the tool returns note paths. It covers purpose, parameters, constraints, and behavior, making it fully complete for an agent to invoke correctly.

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

Parameters4/5

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

Schema coverage is 100% with descriptions for each parameter. The description further explains filter syntax and the role of views, adding semantic context beyond the schema.

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 runs a Base file's filters and returns matching note paths. It uses a specific verb and resource, and differentiates from sibling tools like read_base and search_notes by focusing on filtered queries.

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

Usage Guidelines4/5

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

The description explains the optional view parameter and its purpose. It does not explicitly list when not to use the tool, but the context is clear enough for an agent to distinguish from related tools.

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/rps321321/obsidian-mcp-pro'

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