import { z } from 'zod';
import { writeFile } from 'fs/promises';
import { existsSync } from 'fs';
import { PathResolver } from '../utils/path-resolver.js';
import { convertMdxToMarkdown } from '../utils/mdx-processor.js';
import { ToolResponse } from '../types/index.js';
/**
* Input schema for convert_mdx_to_md tool
*/
export const convertMdxInputSchema = z.object({
sourcePath: z.string().describe('Path to source MDX file relative to workspace root'),
outputPath: z.string().describe('Path for output MD file relative to workspace root')
});
/**
* Output schema for convert_mdx_to_md tool
*/
export const convertMdxOutputSchema = z.object({
success: z.boolean(),
sourcePath: z.string(),
outputPath: z.string(),
message: z.string()
});
/**
* Convert an MDX file to a Markdown file on disk
*
* @param input - Tool input with sourcePath and outputPath parameters
* @param pathResolver - PathResolver instance
* @returns Tool response with conversion result
*/
export async function convertMdxTool(
input: z.infer<typeof convertMdxInputSchema>,
pathResolver: PathResolver
): Promise<ToolResponse> {
try {
const { sourcePath, outputPath } = input;
// Resolve paths
const resolvedSourcePath = pathResolver.resolveWorkspacePath(sourcePath);
const resolvedOutputPath = pathResolver.resolveWorkspacePath(outputPath);
// Validate path safety
if (!pathResolver.isPathSafe(sourcePath)) {
return {
content: [{
type: 'text',
text: `Error: Source path is outside workspace root: ${sourcePath}`
}],
isError: true
};
}
if (!pathResolver.isPathSafe(outputPath)) {
return {
content: [{
type: 'text',
text: `Error: Output path is outside workspace root: ${outputPath}`
}],
isError: true
};
}
// Validate source file exists
if (!pathResolver.validateFilePath(sourcePath)) {
return {
content: [{
type: 'text',
text: `Error: Source file not found at path: ${sourcePath}`
}],
isError: true
};
}
// Check if output file already exists (optional safety check)
if (existsSync(resolvedOutputPath)) {
return {
content: [{
type: 'text',
text: `Warning: Output file already exists at path: ${outputPath}. Use a different output path or delete the existing file first.`
}],
isError: true
};
}
// Ensure output directory exists
await pathResolver.ensureDirectory(outputPath);
// Convert MDX to Markdown
const markdown = await convertMdxToMarkdown(resolvedSourcePath);
// Write to output file
await writeFile(resolvedOutputPath, markdown, 'utf-8');
const result = {
success: true,
sourcePath: resolvedSourcePath,
outputPath: resolvedOutputPath,
message: `Successfully converted ${sourcePath} to ${outputPath}`
};
return {
content: [{
type: 'text',
text: JSON.stringify(result, null, 2)
}]
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
return {
content: [{
type: 'text',
text: `Error converting MDX file: ${errorMessage}`
}],
isError: true
};
}
}