Skip to main content
Glama
mgraczyk

JSON Query MCP

by mgraczyk

json_query_search_values

Search large JSON files for specific values without knowing their exact paths. Input a search term and file path to retrieve matching results, limited to a specified number.

Instructions

Search for values in a JSON file. Use when you do not know the path to a value in a large JSON file, but have some idea what the value 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 values

Implementation Reference

  • Core handler logic for the tool: recursively traverses JSON, collects string/number values with paths, computes similarity to query, returns top matches.
    static async searchValues(query: string, jsonFile: string, limit = 5): Promise<SearchResult[]> {
      const data = await this.readJsonFile(jsonFile);
      const valuePaths: { path: string; value: unknown }[] = [];
    
      const collectValues = (obj: unknown, path = '$'): void => {
        if (obj && typeof obj === 'object') {
          if (Array.isArray(obj)) {
            obj.forEach((item, index) => {
              const newPath = `${path}[${index.toString()}]`;
              if (typeof item === 'string' || typeof item === 'number') {
                valuePaths.push({ path: newPath, value: item });
              }
              collectValues(item, newPath);
            });
          } else {
            Object.entries(obj).forEach(([key, value]) => {
              const newPath = path === '$' ? `$.${key}` : `${path}.${key}`;
              if (typeof value === 'string' || typeof value === 'number') {
                valuePaths.push({ path: newPath, value });
              }
              collectValues(value, newPath);
            });
          }
        }
      };
    
      collectValues(data);
    
      const stringQuery = String(query).toLowerCase();
      const matches = valuePaths
        .filter((item) => typeof item.value === 'string' || typeof item.value === 'number')
        .map((item) => ({
          path: item.path,
          similarity: stringSimilarity.compareTwoStrings(
            stringQuery,
            String(item.value).toLowerCase(),
          ),
          value: item.value,
        }));
    
      return matches.sort((a, b) => b.similarity - a.similarity).slice(0, limit);
    }
  • src/server.ts:99-132 (registration)
    Registers the tool 'json_query_search_values' with description, Zod input schema, and wrapper handler that calls JsonUtils.searchValues.
    server.tool(
      'json_query_search_values',
      'Search for values in a JSON file. Use when you do not know the path to a value in a large JSON file, but have some idea what the value is.',
      {
        file_path: z.string().describe(PATH_ARG_DESCRIPTION),
        query: z.string().min(1).describe('Search term for finding matching values'),
        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.searchValues(query, resolvedPath, limit);
    
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(results, null, 2),
              },
            ],
          };
        } catch (error) {
          return getErrorResponse(error);
        }
      },
    );
  • Zod schema defining the input parameters for the tool: file_path (string), query (string), limit (number, optional default 5).
    {
      file_path: z.string().describe(PATH_ARG_DESCRIPTION),
      query: z.string().min(1).describe('Search term for finding matching values'),
      limit: z
        .number()
        .int()
        .min(1)
        .max(100)
        .optional()
        .default(5)
        .describe('Maximum number of results to return (default: 5)'),
    },
  • TypeScript interface defining the output structure for search results: path, similarity score, optional value.
    export interface SearchResult {
      path: string;
      similarity: number;
      value?: unknown;
    }
  • Helper method to read and parse JSON file from disk, used by searchValues.
    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');
        }
      }
    }
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