Skip to main content
Glama

check_files

Verify file paths and context size before sending to Grok. This dry-run tool checks file syntax, patterns, and limits to confirm resolution succeeds, preventing errors in ask_grok.

Instructions

Dry-run file resolution. Use this before ask_grok to verify files will resolve correctly and check context size. Uses the same validation as ask_grok — if check_files passes, ask_grok will too. File paths resolve relative to: /app

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
filesYesFiles to check. Same syntax as ask_grok: "path/to/file", "path/to/file:10-30", "src/**/*.ts", "large-file.ts:force"
max_filesNoOverride max file count (default 50)
max_file_sizeNoOverride max per-file size in KB (default 32)

Implementation Reference

  • src/index.ts:334-368 (registration)
    Registration of the 'check_files' tool on the MCP server via server.tool(), defining name, description, input schema (files, max_files, max_file_size), and the handler callback.
    server.tool(
      "check_files",
      `Dry-run file resolution. Use this before ask_grok to verify files will resolve correctly and check context size. Uses the same validation as ask_grok — if check_files passes, ask_grok will too. File paths resolve relative to: ${process.cwd()}`,
      {
        files: z
          .array(z.string())
          .describe('Files to check. Same syntax as ask_grok: "path/to/file", "path/to/file:10-30", "src/**/*.ts", "large-file.ts:force"'),
        max_files: z
          .number()
          .optional()
          .describe("Override max file count (default 50)"),
        max_file_size: z
          .number()
          .optional()
          .describe("Override max per-file size in KB (default 32)"),
      },
      async ({ files, max_files, max_file_size }) => {
        const result = resolveFiles(files, { maxFiles: max_files, maxFileSize: max_file_size });
        if (!result.ok) {
          return { isError: true, content: [{ type: "text" as const, text: result.error }] };
        }
    
        const sorted = [...result.files].sort((a, b) => b.bytes - a.bytes);
        const lines = [
          `${result.files.length} file(s), ${Math.round(result.totalBytes / 1024)} KB total (limit ${MAX_TOTAL_BYTES / 1024} KB)`,
          "",
          ...sorted.map((f) => {
            const kb = (f.bytes / 1024).toFixed(1);
            return `  ${kb} KB  ${f.path}${f.range}`;
          }),
        ];
    
        return { content: [{ type: "text" as const, text: lines.join("\n") }] };
      }
    );
  • Zod input schema for check_files: 'files' (array of strings, required), 'max_files' (optional number), 'max_file_size' (optional number in KB).
    {
      files: z
        .array(z.string())
        .describe('Files to check. Same syntax as ask_grok: "path/to/file", "path/to/file:10-30", "src/**/*.ts", "large-file.ts:force"'),
      max_files: z
        .number()
        .optional()
        .describe("Override max file count (default 50)"),
      max_file_size: z
        .number()
        .optional()
        .describe("Override max per-file size in KB (default 32)"),
    },
  • Handler function that calls resolveFiles() with the provided arguments, formats the result as a summary line (file count / total KB / limit) followed by a sorted list (largest first) showing each file's size and path+range, and returns it as text content.
    async ({ files, max_files, max_file_size }) => {
      const result = resolveFiles(files, { maxFiles: max_files, maxFileSize: max_file_size });
      if (!result.ok) {
        return { isError: true, content: [{ type: "text" as const, text: result.error }] };
      }
    
      const sorted = [...result.files].sort((a, b) => b.bytes - a.bytes);
      const lines = [
        `${result.files.length} file(s), ${Math.round(result.totalBytes / 1024)} KB total (limit ${MAX_TOTAL_BYTES / 1024} KB)`,
        "",
        ...sorted.map((f) => {
          const kb = (f.bytes / 1024).toFixed(1);
          return `  ${kb} KB  ${f.path}${f.range}`;
        }),
      ];
    
      return { content: [{ type: "text" as const, text: lines.join("\n") }] };
    }
  • The resolveFiles() helper that performs the actual file resolution logic: parses file args via parseFileArg(), reads files with readFileSync(), enforces max file count, per-file size limits, line range validation, and total byte cap (256 KB). Returns either ok with resolved files or ok:false with error messages.
    function resolveFiles(fileArgs: string[], opts?: ResolveOptions): ResolveResult {
      const maxFiles = opts?.maxFiles ?? DEFAULT_MAX_FILES;
      const maxSingleBytes = opts?.maxFileSize ? opts.maxFileSize * 1024 : DEFAULT_MAX_SINGLE_BYTES;
    
      const errors: string[] = [];
      const resolved: ResolvedFile[] = [];
      const specs = fileArgs.flatMap(parseFileArg);
    
      if (specs.length > maxFiles) {
        return { ok: false, error: `Too many files: ${specs.length} resolved (limit ${maxFiles}). This usually means a glob matched more than intended (e.g. node_modules). Use a more specific pattern.` };
      }
    
      let totalBytes = 0;
    
      for (const spec of specs) {
        try {
          const raw = readFileSync(spec.path, "utf-8");
    
          if (!spec.force && raw.length > maxSingleBytes && !spec.startLine && !spec.endLine) {
            const kb = Math.round(raw.length / 1024);
            errors.push(`${spec.path}: file is ${kb} KB (limit ${maxSingleBytes / 1024} KB per file). Use ":force" to override, or line ranges to include only the relevant part, e.g. "${spec.path}:1-100"`);
            continue;
          }
    
          const allLines = raw.split("\n");
          const totalLines = allLines.length;
          if (spec.startLine && spec.startLine > totalLines) {
            errors.push(`${spec.path}: line ${spec.startLine} is past end of file (${totalLines} lines)`);
            continue;
          }
          if (spec.endLine && spec.endLine > totalLines) {
            errors.push(`${spec.path}: line ${spec.endLine} is past end of file (${totalLines} lines)`);
            continue;
          }
          if (spec.startLine && spec.endLine && spec.startLine > spec.endLine) {
            errors.push(`${spec.path}: start line ${spec.startLine} is after end line ${spec.endLine}`);
            continue;
          }
          const start = spec.startLine ? spec.startLine - 1 : 0;
          const end = spec.endLine ? spec.endLine : totalLines;
          const sliced = allLines.slice(start, end);
          const numbered = sliced
            .map((line, i) => `${start + i + 1}\t${line}`)
            .join("\n");
    
          totalBytes += numbered.length;
          if (totalBytes > MAX_TOTAL_BYTES) {
            const kb = Math.round(totalBytes / 1024);
            errors.push(`Total file context is ${kb} KB (hard limit ${MAX_TOTAL_BYTES / 1024} KB). Include fewer files or use line ranges to narrow down.`);
            break;
          }
    
          const range =
            spec.startLine || spec.endLine
              ? `:${spec.startLine ?? 1}-${spec.endLine ?? totalLines}`
              : "";
          resolved.push({ path: spec.path, range, content: numbered, bytes: numbered.length });
        } catch (err) {
          errors.push(`${spec.path}: ${err instanceof Error ? err.message : String(err)}`);
        }
      }
    
      if (errors.length > 0) {
        return { ok: false, error: `File context error:\n${errors.join("\n")}\n\nFix and try again.` };
      }
    
      return { ok: true, files: resolved, totalBytes };
    }
  • The parseFileArg() helper that parses individual file argument strings, supporting patterns like 'path:10-30', 'path:10', glob patterns with **/*, and the :force suffix to bypass size limits.
    function parseFileArg(arg: string): FileSpec[] {
      // Strip :force suffix first
      let force = false;
      let input = arg;
      if (input.endsWith(":force")) {
        force = true;
        input = input.slice(0, -6);
      }
    
      // "path/to/file:10-30" or "path/to/file:10" or "path/to/file" or "src/**/*.ts"
      const match = input.match(/^(.+?):(\d+)(?:-(\d+))?$/);
      let pattern: string;
      let startLine: number | undefined;
      let endLine: number | undefined;
    
      if (match) {
        pattern = match[1];
        startLine = parseInt(match[2], 10);
        endLine = match[3] ? parseInt(match[3], 10) : startLine;
      } else {
        pattern = input;
      }
    
      const resolved = resolve(pattern);
    
      if (/[*?[\]]/.test(pattern)) {
        const paths = globSync(pattern).sort();
        if (paths.length === 0) {
          return [{ path: pattern, force }]; // will fail at read time with a clear error
        }
        return paths.map((p) => ({ path: resolve(p as string), startLine, endLine, force }));
      }
    
      return [{ path: resolved, startLine, endLine, force }];
    }
Behavior4/5

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

No annotations are provided, so the description carries full burden. It discloses the tool is a dry-run (non-destructive), verifies file resolution, checks context size, and states that file paths resolve relative to /app. It doesn't detail error behavior or rate limits, but for a simple check tool this is adequate.

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 at three sentences, with the primary purpose front-loaded. Every sentence adds essential information without redundancy.

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

Completeness4/5

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

Given the tool's simplicity, no output schema, and a single sibling, the description covers the core functionality and relationship well. It explains validation equivalence and file resolution. It does not describe the return format, but the overall completeness is sufficient for an agent to use the tool correctly.

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 input schema has 100% coverage with detailed descriptions for all three parameters. The description adds an important context note about file paths resolving relative to /app, which is not in the schema. However, this is environmental context rather than parameter semantics, so the 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 tool performs a 'dry-run file resolution' and explicitly differentiates it from its sibling 'ask_grok' by positioning it as a preparatory verification step. The verb 'check' and noun 'files' are specific.

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 guidance: 'Use this before ask_grok' and explains that if check_files passes, ask_grok will too. It also notes the same validation logic, giving clear context for when to use this tool versus the alternative.

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/PKWadsy/grok-mcp'

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