Skip to main content
Glama

merge

Combine multiple JSON files from the specified directory path into a single JSON file.

Instructions

Merge JSON files into a one JSON file

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
pathYes

Implementation Reference

  • src/index.ts:147-153 (registration)
    Tool 'merge' registered in ListToolsRequestSchema handler with name 'merge' and description 'Merge JSON files into a one JSON file'. Input schema uses PathArgSchema.
        {
          name: 'merge',
          description: 'Merge JSON files into a one JSON file',
          inputSchema: zodToJsonSchema(PathArgSchema) as ToolInput,
        },
      ],
    }
  • PathArgSchema defines the schema for the 'merge' tool: expects a single 'path' string argument.
    const PathArgSchema = z.object({
      path: z.string(),
    })
  • Handler for 'merge' tool: parses the path argument, validates the path, reads all JSON files in the directory via loadFlatJsons, flattens their contents, and writes the merged result to 'merged.json' in the same directory.
    case 'merge': {
      const parsed = PathArgSchema.safeParse(args)
      if (!parsed.success) {
        throw new Error(`Invalid arguments for merge: ${parsed.error}`)
      }
      const { path } = parsed.data
    
      const validPath = await validatePath(path)
      const content = await loadFlatJsons(validPath)
      const fileName = _path.join(validPath, 'merged.json')
    
      try {
        await fs.promises.writeFile(
          fileName,
          JSON.stringify(content, null, 2)
        )
        console.log(`Successfully wrote ${fileName}`)
      } catch (err) {
        console.error(`Error writing file ${fileName}:`, err)
      }
    
      return {
        content: [
          {
            type: 'text',
            text: `Successfully merged to ${fileName}`,
          },
        ],
      }
    }
  • Helper functions used by merge: getAllJsonNames, getMultipleJsonFilePath, readFileToJson, parseMultipleJson, and loadFlatJsons - these collectively read all .json files from a directory and return their flattened combined content.
    const getAllJsonNames = async (dir: string): Promise<string[]> =>
      getAllFileNames(dir, '.json')
    
    const getMultipleJsonFilePath = async (fileDir: string): Promise<string[]> => {
      const filePaths: string[] = []
      const fileNames = await getAllJsonNames(fileDir)
      for (let index = 0; index < fileNames.length; index++) {
        filePaths.push(`${fileDir}/${fileNames[index]}`)
      }
      return filePaths
    }
    
    const readFileToJson = async (fileName: string): Promise<any[]> => {
      try {
        const content = await fs.promises.readFile(fileName, 'utf-8')
        return JSON.parse(content)
      } catch (error) {
        throw new Error(`Error reading or parsing file ${fileName}: ${error}`)
      }
    }
    
    const parseMultipleJson = async (fileDir: string) => {
      const multipleJson: any = []
      const fileNames = await getMultipleJsonFilePath(fileDir)
      for (let index = 0; index < fileNames.length; index++) {
        multipleJson.push(readFileToJson(fileNames[index]))
      }
      return multipleJson
    }
    
    const loadFlatJsons = async (path: string) => {
      const promises = await parseMultipleJson(path)
      if (promises.length === 0) throw new Error(`No files in ${path}`)
      const jsons = await Promise.all(promises)
      return jsons.flat()
    }
  • validatePath helper used by merge to resolve and validate the provided directory path.
    const validatePath = async (requestedPath: string): Promise<string> => {
      const expandedPath = expandHome(requestedPath)
      const absolute = _path.isAbsolute(expandedPath)
        ? _path.resolve(expandedPath)
        : _path.resolve(process.cwd(), expandedPath)
    
      try {
        const realPath = await fs.promises.realpath(absolute)
        return realPath
      } catch (error) {
        const parentDir = _path.dirname(absolute)
        try {
          return absolute
        } catch {
          throw new Error(`Parent directory does not exist: ${parentDir}`)
        }
      }
    }
Behavior2/5

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

No annotations provided. The description only says 'merge', without disclosing critical behaviors like conflict resolution, merge strategy (shallow vs deep), output location, or whether it modifies input files.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single short sentence, which is concise but sacrifices clarity. It is front-loaded but lacks necessary detail.

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

Completeness2/5

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

Given one parameter, no output schema, and no annotations, the description is too incomplete. It does not explain merge behavior, input constraints, or output format, leaving significant gaps for an agent.

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

Parameters2/5

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

The input schema has 0% description coverage for the 'path' parameter, and the description does not explain what 'path' represents. It could be a file path or directory; the ambiguity reduces usefulness.

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 merges JSON files into one, with a verb 'merge' and resource 'JSON files'. It distinguishes from the sibling 'split' by being the opposite operation. However, it lacks specificity about what 'path' refers to (a single file? a directory?)

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

Usage Guidelines2/5

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

No guidance on when to use this tool versus alternatives. The sibling 'split' suggests a complementary tool, but no explicit when-to-use or when-not-to-use is given.

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/VadimNastoyashchy/json-mcp'

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