Skip to main content
Glama
rawr-ai

Filesystem MCP Server

json_sample

Extract JSON data samples from specified arrays within files. Define path, array location, sample count, and method (first or random) to retrieve precise data segments efficiently.

Instructions

Sample JSON data from a JSON file. Requires maxBytes parameter (default 10KB). Returns a random sample of data from the JSON file. The path must be within allowed directories.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
arrayPathYesJSONPath expression to locate the target array (e.g., "$.items" or "$.data.records")
countYesNumber of elements to sample
maxBytesYesMaximum bytes to read from the file. Must be a positive integer. Handler default: 10KB.
methodNoSampling method - "first" for first N elements, "random" for random samplingfirst
pathYesPath to the JSON file containing the array

Implementation Reference

  • Core handler function for json_sample tool. Parses arguments, reads and validates JSON file path, extracts target array using JSONPath, samples specified number of elements (first N or random), and returns formatted JSON response.
    export async function handleJsonSample(
      args: unknown,
      allowedDirectories: string[],
      symlinksMap: Map<string, string>,
      noFollowSymlinks: boolean
    ) {
      const parsed = parseArgs(JsonSampleArgsSchema, args, 'json_sample');
    
      const validPath = await validatePath(parsed.path, allowedDirectories, symlinksMap, noFollowSymlinks);
      const jsonData = await readJsonFile(validPath, parsed.maxBytes);
    
      try {
        // Use JSONPath to locate the target array
        const targetArray = JSONPath({
          path: parsed.arrayPath,
          json: jsonData,
          wrap: false
        });
    
        if (!Array.isArray(targetArray)) {
          throw new Error(`Path "${parsed.arrayPath}" did not resolve to an array`);
        }
    
        if (targetArray.length === 0) {
          return {
            content: [{
              type: "text",
              text: JSON.stringify([], null, 2)
            }],
          };
        }
    
        let sampledData: any[];
        if (parsed.method === 'random') {
          sampledData = sampleSize(targetArray, Math.min(parsed.count, targetArray.length));
        } else {
          sampledData = take(targetArray, parsed.count);
        }
    
        return {
          content: [{
            type: "text",
            text: JSON.stringify(sampledData, null, 2)
          }],
        };
      } catch (error) {
        if (error instanceof Error) {
          throw new Error(`JSON sampling failed: ${error.message}`);
        }
        throw error;
      }
    }
  • TypeBox schema definition for json_sample input arguments: requires path to JSON file, JSONPath to array, count of samples; optional sampling method (first/random) and maxBytes limit.
    export const JsonSampleArgsSchema = Type.Object({
      path: Type.String({ description: 'Path to the JSON file containing the array' }),
      arrayPath: Type.String({ description: 'JSONPath expression to locate the target array (e.g., "$.items" or "$.data.records")' }),
      count: Type.Integer({ minimum: 1, description: 'Number of elements to sample' }),
      method: Type.Optional(
        Type.Union([Type.Literal('first'), Type.Literal('random')], {
          default: 'first',
          description: 'Sampling method - "first" for first N elements, "random" for random sampling'
        })
      ),
      maxBytes: Type.Integer({
        minimum: 1,
        description: 'Maximum bytes to read from the file. Must be a positive integer. Handler default: 10KB.'
      })
    });
    export type JsonSampleArgs = Static<typeof JsonSampleArgsSchema>;
  • index.ts:289-290 (registration)
    Registers the json_sample tool handler in the central toolHandlers object, passing server context (allowedDirectories, symlinksMap, noFollowSymlinks).
    json_sample: (a: unknown) =>
      handleJsonSample(a, allowedDirectories, symlinksMap, noFollowSymlinks),
  • index.ts:331-331 (registration)
    Declares json_sample in the allTools array with name and description, used for permission filtering and tool listing.
    { name: "json_sample", description: "Sample JSON data" },
  • Re-exports JsonSampleArgsSchema as toolSchemas.json_sample for use in main index.ts registration loop.
    json_sample: JsonSampleArgsSchema,
Behavior3/5

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

With no annotations provided, the description carries the full burden. It discloses key behavioral traits: it requires maxBytes parameter with a default (10KB), returns a random sample, and has path restrictions. However, it doesn't mention error handling, performance implications, or what happens with invalid arrayPath. It adds useful context but leaves gaps in behavioral understanding.

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 appropriately sized with three concise sentences. It's front-loaded with the core purpose, followed by parameter requirements and constraints. No wasted words, though it could be slightly more structured for clarity.

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?

For a 5-parameter tool with no annotations and no output schema, the description provides adequate but incomplete context. It covers the basic operation and key constraints but lacks details on return format, error cases, and how sampling interacts with the JSON structure. Given the complexity, it should do more to compensate for missing structured data.

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%, providing detailed documentation for all 5 parameters. The description adds minimal value beyond the schema, mentioning only maxBytes default and path restrictions. It doesn't explain parameter interactions or provide additional semantic context, so baseline 3 is appropriate.

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 specific action ('Sample JSON data'), resource ('from a JSON file'), and scope ('random sample'). It distinguishes from siblings like json_filter, json_query, and json_get_value by focusing on sampling rather than filtering, querying, or extracting specific values.

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

Usage Guidelines3/5

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

The description implies usage for sampling JSON data but doesn't explicitly state when to use this tool versus alternatives like json_filter or json_query. It mentions the path must be within allowed directories, which provides some context, but lacks explicit guidance on when to choose sampling over other JSON operations.

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/rawr-ai/mcp-filesystem'

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