Skip to main content
Glama
mgraczyk

JSON Query MCP

by mgraczyk

json_query_search_keys

Search for specific keys within a JSON file without knowing their exact path. Ideal for navigating large JSON data to locate relevant information quickly and efficiently.

Instructions

Search for keys in a JSON file. Use when you do not know the path to a key in a large JSON file, but have some idea what the key is.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYesAbsolute path to the JSON file.
limitNoMaximum number of results to return (default: 5)
queryYesSearch term for finding matching keys

Implementation Reference

  • Core handler function that implements the logic for searching JSON keys: recursively traverses the JSON structure to collect all key paths, computes string similarity scores with the query, sorts by similarity descending, and returns top results up to the limit.
    static async searchKeys(query: string, jsonFile: string, limit = 5): Promise<SearchResult[]> {
      const data = await this.readJsonFile(jsonFile);
      const keyPaths: { path: string; key: string }[] = [];
    
      const collectKeys = (obj: unknown, path = '$'): void => {
        if (obj && typeof obj === 'object') {
          if (Array.isArray(obj)) {
            obj.forEach((item, index) => {
              collectKeys(item, `${path}[${index.toString()}]`);
            });
          } else {
            Object.entries(obj).forEach(([key, value]) => {
              const newPath = path === '$' ? `$.${key}` : `${path}.${key}`;
              keyPaths.push({ path: newPath, key });
              collectKeys(value, newPath);
            });
          }
        }
      };
    
      collectKeys(data);
    
      const matches = keyPaths.map((item) => ({
        path: item.path,
        similarity: stringSimilarity.compareTwoStrings(query.toLowerCase(), item.key.toLowerCase()),
      }));
    
      return matches.sort((a, b) => b.similarity - a.similarity).slice(0, limit);
    }
  • src/server.ts:63-96 (registration)
    Registers the 'json_query_search_keys' tool on the MCP server, providing description, input schema with Zod validation, and a thin async handler that resolves the file path, calls the core searchKeys implementation, formats output as JSON text, and handles errors.
    server.tool(
      'json_query_search_keys',
      'Search for keys in a JSON file. Use when you do not know the path to a key in a large JSON file, but have some idea what the key is.',
      {
        file_path: z.string().describe(PATH_ARG_DESCRIPTION),
        query: z.string().min(1).describe('Search term for finding matching keys'),
        limit: z
          .number()
          .int()
          .min(1)
          .max(100)
          .optional()
          .default(5)
          .describe('Maximum number of results to return (default: 5)'),
      },
      async ({ file_path, query, limit }) => {
        try {
          const resolvedPath = path.resolve(file_path);
    
          const results = await JsonUtils.searchKeys(query, resolvedPath, limit);
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(results, null, 2),
              },
            ],
          };
        } catch (error) {
          return getErrorResponse(error);
        }
      },
    );
  • Zod schema defining input parameters for the tool: file_path (string), query (non-empty string), limit (optional integer 1-100, default 5).
    {
      file_path: z.string().describe(PATH_ARG_DESCRIPTION),
      query: z.string().min(1).describe('Search term for finding matching keys'),
      limit: z
        .number()
        .int()
        .min(1)
        .max(100)
        .optional()
        .default(5)
        .describe('Maximum number of results to return (default: 5)'),
    },
  • TypeScript interface defining the structure of search results returned by the tool, used by the handler.
    export interface SearchResult {
      path: string;
      similarity: number;
      value?: unknown;
    }
  • Helper utility method to read and parse a JSON file from disk, used by the search functions.
    private static async readJsonFile(filePath: string): Promise<unknown> {
      try {
        const content = await fs.readFile(filePath, 'utf-8');
        return JSON.parse(content);
      } catch (error) {
        if (error instanceof Error) {
          throw new Error(`Failed to read or parse JSON file: ${error}`);
        } else {
          throw new Error('Failed to read or parse JSON file');
        }
      }
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the tool searches for keys in large JSON files, which implies read-only behavior, but doesn't specify whether it's safe (e.g., non-destructive), what permissions are needed, or how results are returned (e.g., format, pagination). For a tool with zero annotation coverage, this leaves significant gaps in understanding its operational traits.

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 appropriately sized and front-loaded: it states the core purpose in the first sentence and adds usage context in the second. Every sentence earns its place by clarifying when to use the tool, with no wasted words or redundancy.

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 moderate complexity (3 parameters, no output schema, no annotations), the description is adequate but incomplete. It covers purpose and usage well, but lacks details on behavioral aspects (e.g., safety, permissions) and output format. Without annotations or output schema, more context would help agents understand the full operational scope.

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 schema description coverage is 100%, so the input schema already documents all parameters (file_path, limit, query) with descriptions. The description adds minimal value beyond the schema by implying the search is for keys in large files, but doesn't provide additional syntax, format details, or constraints. This meets the baseline of 3 when schema coverage is high.

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 the tool's purpose: 'Search for keys in a JSON file.' It specifies the verb ('search'), resource ('keys in a JSON file'), and context ('when you do not know the path'). However, it doesn't explicitly distinguish this from sibling tools like 'json_query_search_values' (which searches values rather than keys), leaving some ambiguity about sibling differentiation.

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 provides clear context for when to use this tool: 'Use when you do not know the path to a key in a large JSON file, but have some idea what the key is.' This gives practical guidance on the scenario it addresses. However, it doesn't mention when not to use it or explicitly name alternatives (e.g., 'json_query_jsonpath' for known paths), so it lacks full exclusion criteria.

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

Related 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/mgraczyk/json-query-mcp'

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