Skip to main content
Glama

diff

Compare text or data in various formats (JSON, YAML, XML, etc.) and generate readable diffs in text, JSON, or JSON patch formats for clear analysis.

Instructions

compare text or data and get a readable diff

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
stateYes

Implementation Reference

  • Registers the 'diff' MCP tool, including inline input schema and handler function.
    server.tool(
    	"diff",
    	"compare text or data and get a readable diff",
    	{
    		state: z.object({
    			left: inputDataSchema.describe("The left side of the diff."),
    			leftFormat: formatSchema
    				.optional()
    				.describe("format of left side of the diff"),
    			right: inputDataSchema.describe(
    				"The right side of the diff (to compare with the left side).",
    			),
    			rightFormat: formatSchema
    				.optional()
    				.describe("format of right side of the diff"),
    			outputFormat: z
    				.enum(["text", "json", "jsonpatch"])
    				.default("text")
    				.describe(
    					"The output format. " +
    						"text: (default) human readable text diff, " +
    						"json: a compact json diff (jsondiffpatch delta format), " +
    						"jsonpatch: json patch diff (RFC 6902)",
    				)
    				.optional(),
    		}),
    	},
    	({ state }) => {
    		try {
    			const jsondiffpatch = create({
    				textDiff: {
    					...(state.outputFormat === "jsonpatch"
    						? {
    								// jsonpatch doesn't support text diffs
    								minLength: Number.MAX_VALUE,
    							}
    						: {}),
    				},
    			});
    
    			const left = parseData(state.left, state.leftFormat);
    			const right = parseData(state.right, state.rightFormat);
    			const delta = jsondiffpatch.diff(left, right);
    			const output =
    				state.outputFormat === "json"
    					? delta
    					: state.outputFormat === "jsonpatch"
    						? jsonpatchFormatter.format(delta)
    						: consoleFormatter.format(delta, left);
    
    			const legend =
    				state.outputFormat === "text"
    					? `\n\nlegend:
     - lines starting with "+" indicate new property or item array
     - lines starting with "-" indicate removed property or item array
     - "value => newvalue" indicate property value changed
     - "x: ~> y indicate array item moved from index x to y
     - text diffs are lines that start "line,char" numbers, and have a line below
       with "+" under added chars, and "-" under removed chars.
     - you can use this exact representations when showing differences to the user
     \n`
    					: "";
    
    			return {
    				content: [
    					{
    						type: "text",
    						text:
    							(typeof output === "string"
    								? output
    								: JSON.stringify(output, null, 2)) + legend,
    					},
    				],
    			};
    		} catch (error) {
    			const message = error instanceof Error ? error.message : String(error);
    			return {
    				isError: true,
    				content: [
    					{
    						type: "text",
    						text: `error creating diff: ${message}`,
    					},
    				],
    			};
    		}
    	},
    );
  • Handler function that parses inputs, computes diff using jsondiffpatch.create().diff(), and formats output as text, JSON delta, or JSONPatch.
    ({ state }) => {
    	try {
    		const jsondiffpatch = create({
    			textDiff: {
    				...(state.outputFormat === "jsonpatch"
    					? {
    							// jsonpatch doesn't support text diffs
    							minLength: Number.MAX_VALUE,
    						}
    					: {}),
    			},
    		});
    
    		const left = parseData(state.left, state.leftFormat);
    		const right = parseData(state.right, state.rightFormat);
    		const delta = jsondiffpatch.diff(left, right);
    		const output =
    			state.outputFormat === "json"
    				? delta
    				: state.outputFormat === "jsonpatch"
    					? jsonpatchFormatter.format(delta)
    					: consoleFormatter.format(delta, left);
    
    		const legend =
    			state.outputFormat === "text"
    				? `\n\nlegend:
    - lines starting with "+" indicate new property or item array
    - lines starting with "-" indicate removed property or item array
    - "value => newvalue" indicate property value changed
    - "x: ~> y indicate array item moved from index x to y
    - text diffs are lines that start "line,char" numbers, and have a line below
      with "+" under added chars, and "-" under removed chars.
    - you can use this exact representations when showing differences to the user
    \n`
    				: "";
    
    		return {
    			content: [
    				{
    					type: "text",
    					text:
    						(typeof output === "string"
    							? output
    							: JSON.stringify(output, null, 2)) + legend,
    				},
    			],
    		};
    	} catch (error) {
    		const message = error instanceof Error ? error.message : String(error);
    		return {
    			isError: true,
    			content: [
    				{
    					type: "text",
    					text: `error creating diff: ${message}`,
    				},
    			],
    		};
    	}
    },
  • Input schema (Zod) for the 'diff' tool state, supporting various input formats and output options.
    state: z.object({
    	left: inputDataSchema.describe("The left side of the diff."),
    	leftFormat: formatSchema
    		.optional()
    		.describe("format of left side of the diff"),
    	right: inputDataSchema.describe(
    		"The right side of the diff (to compare with the left side).",
    	),
    	rightFormat: formatSchema
    		.optional()
    		.describe("format of right side of the diff"),
    	outputFormat: z
    		.enum(["text", "json", "jsonpatch"])
    		.default("text")
    		.describe(
    			"The output format. " +
    				"text: (default) human readable text diff, " +
    				"json: a compact json diff (jsondiffpatch delta format), " +
    				"jsonpatch: json patch diff (RFC 6902)",
    		)
    		.optional(),
    }),
  • Helper function to parse string inputs in formats like JSON/5, YAML, TOML, XML/HTML into JavaScript objects for diffing.
    const parseData = (
    	data: z.infer<typeof inputDataSchema>,
    	format: z.infer<typeof formatSchema> | undefined,
    ) => {
    	if (typeof data !== "string") {
    		// already parsed
    		return data;
    	}
    	if (!format || format === "text") {
    		return data;
    	}
    
    	if (format === "json") {
    		try {
    			return JSON.parse(data);
    		} catch {
    			// if json is invalid, try json5
    			return json5.parse(data);
    		}
    	}
    	if (format === "json5") {
    		return json5.parse(data);
    	}
    	if (format === "yaml") {
    		return yaml.load(data);
    	}
    	if (format === "xml") {
    		const parser = new XMLParser({
    			ignoreAttributes: false,
    			preserveOrder: true,
    		});
    		return parser.parse(data);
    	}
    	if (format === "html") {
    		const parser = new XMLParser({
    			ignoreAttributes: false,
    			preserveOrder: true,
    			unpairedTags: ["hr", "br", "link", "meta"],
    			stopNodes: ["*.pre", "*.script"],
    			processEntities: true,
    			htmlEntities: true,
    		});
    		return parser.parse(data);
    	}
    	if (format === "toml") {
    		return tomlParse(data);
    	}
    	format satisfies never;
    	throw new Error(`unsupported format: ${format}`);
    };
  • Zod schema for input data: string, object, or array.
    const inputDataSchema = z
    	.string()
    	.or(z.record(z.string(), z.unknown()))
    	.or(z.array(z.unknown()));
  • Zod schema for input format options.
    const formatSchema = z
    	.enum(["text", "json", "json5", "yaml", "toml", "xml", "html"])
    	.default("json5");
Behavior2/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 mentions the output is a 'readable diff', which gives some behavioral insight, but fails to disclose important traits like whether the operation is read-only, has side effects, requires specific permissions, or handles errors. For a tool that processes data, this is a significant gap in transparency.

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 and front-loaded: 'compare text or data and get a readable diff'. It uses minimal words to convey the core purpose without any waste or redundancy. Every sentence (though only one) earns its place effectively.

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 the complexity (nested objects, multiple data formats) and lack of annotations and output schema, the description is incomplete. It does not address parameter meanings, output details beyond 'readable diff', or behavioral aspects. For a tool with rich input options, this leaves too many gaps for effective use.

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

Parameters1/5

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

The description adds no meaning beyond the input schema. With 0% schema description coverage (parameters lack descriptions in the schema), the description does not compensate by explaining parameters like 'state', 'left', 'right', or format options. This leaves parameters undocumented, making it hard for an agent to use the tool correctly.

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: 'compare text or data and get a readable diff'. It specifies the verb ('compare') and resource ('text or data'), and indicates the output type ('readable diff'). However, without sibling tools, we cannot assess differentiation, and 'readable diff' is somewhat vague about the exact output format.

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?

The description provides no guidance on when to use this tool versus alternatives. It does not mention any prerequisites, constraints, or typical use cases. Since there are no sibling tools, this is less critical, but the description lacks any contextual usage information.

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/benjamine/jsondiffpatch'

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