Skip to main content
Glama
whyjp

Encoding MCP Server

convert_file_encoding

Convert file encoding to prevent character issues in Windows builds. Supports UTF-8, CP949, EUC-KR, ASCII encodings with optional backup.

Instructions

Convert file to specified encoding. Automatic backup support.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_nameYesFile name to convert (e.g., hello.cpp, test.h)
directory_pathYesAbsolute path of directory containing the file
target_encodingNoTarget encodingutf-8-bom
backupNoWhether to backup original file

Implementation Reference

  • Core handler function that executes the file encoding conversion: validates inputs, detects current encoding, optionally creates backup, reads file content, rewrites with target encoding, handles errors and provides detailed result message.
    def convert_file_encoding(file_path: str, target_encoding: str, backup: bool = False) -> str:
        """
        Convert file encoding.
        
        Args:
            file_path: File path
            target_encoding: Target encoding
            backup: Whether to create backup
            
        Returns:
            str: Result message
        """
        try:
            # Check if file exists
            if not os.path.exists(file_path):
                return f"File not found: {file_path}"
            
            # Validate encoding
            if not validate_encoding(target_encoding):
                supported = ", ".join(SUPPORTED_ENCODINGS.keys())
                return f"Unsupported encoding: {target_encoding}. Supported: {supported}"
            
            # Detect current encoding (using separate module)
            from .encoding_detector import detect_file_encoding
            
            current_info = detect_file_encoding(file_path)
            if "error" in current_info:
                return f"Failed to detect file encoding: {current_info['error']}"
            
            current_encoding = current_info['encoding']
            
            # Already in target encoding
            if current_encoding == target_encoding:
                return f"File is already in {target_encoding} encoding: {file_path}"
            
            # Create backup
            backup_path = None
            if backup:
                backup_path = file_path + ".backup"
                try:
                    shutil.copy2(file_path, backup_path)
                except Exception as e:
                    return f"Backup creation failed: {str(e)}"
            
            # Read file content
            content, read_result = read_file_with_encoding(file_path, current_encoding)
            if not content and "successfully" not in read_result.lower():
                return f"File read failed: {read_result}"
            
            # Save with new encoding
            write_result = write_file_with_content(file_path, content, target_encoding)
            if "successfully" not in write_result.lower():
                # Restore backup on failure
                if backup_path and os.path.exists(backup_path):
                    shutil.copy2(backup_path, file_path)
                return f"File write failed: {write_result}"
            
            backup_msg = f"\nBackup file: {backup_path}" if backup_path else "\nNo backup"
            current_info_obj = get_encoding_info(current_encoding)
            target_info_obj = get_encoding_info(target_encoding)
            
            current_name = current_info_obj['name'] if current_info_obj else current_encoding
            target_name = target_info_obj['name'] if target_info_obj else target_encoding
            
            return f"File encoding conversion completed!\nConversion: {current_name} → {target_name}{backup_msg}"
            
        except Exception as e:
            return f"Error during file conversion: {str(e)}"
  • JSON schema definition for the tool input parameters including file_name, directory_path, target_encoding (enum), and optional backup boolean.
    Tool(
        name="convert_file_encoding",
        description="Convert file to specified encoding. Automatic backup support.",
        inputSchema={
            "type": "object",
            "properties": {
                "file_name": {
                    "type": "string",
                    "description": "File name to convert (e.g., hello.cpp, test.h)"
                },
                "directory_path": {
                    "type": "string",
                    "description": "Absolute path of directory containing the file"
                },
                "target_encoding": {
                    "type": "string",
                    "description": "Target encoding",
                    "enum": ["utf-8-bom", "utf-8", "cp949", "euc-kr", "ascii"],
                    "default": "utf-8-bom"
                },
                "backup": {
                    "type": "boolean",
                    "description": "Whether to backup original file",
                    "default": False
                }
            },
            "required": ["file_name", "directory_path"]
        }
    ),
  • MCP server tool dispatcher: extracts arguments, constructs full file path, invokes the convert_file_encoding handler, formats response with icon and result message.
    elif name == "convert_file_encoding":
        file_name = arguments.get("file_name", "")
        directory_path = arguments.get("directory_path", "")
        target_encoding = arguments.get("target_encoding", "utf-8-bom")
        backup = arguments.get("backup", False)
        
        # Combine file name and directory path
        file_path = os.path.join(directory_path, file_name)
        
        result = convert_file_encoding(file_path, target_encoding, backup)
        
        # Select icon based on result
        if "completed" in result.lower() or "complete" in result.lower():
            icon = "✅"
        elif "failed" in result.lower() or "error" in result.lower():
            icon = "❌"
        else:
            icon = "ℹ️"
        
        return [
            types.TextContent(
                type="text",
                text=f"{icon} Encoding conversion\n\n{result}"
            )
        ]
  • Server decorator and function that lists all available tools, including the convert_file_encoding tool registration via Tool object.
    @app.list_tools()
    async def list_tools():
        """Return list of available tools."""
        return [
            Tool(
                name="create_empty_file",
                description="Create an empty file with specified encoding. Creates only an empty file so Agent can fill in content.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "file_name": {
                            "type": "string",
                            "description": "File name to create (e.g., hello.cpp, test.h)"
                        },
                        "directory_path": {
                            "type": "string", 
                            "description": "Absolute path of directory to create file in"
                        },
                        "encoding": {
                            "type": "string",
                            "description": "File encoding",
                            "enum": ["utf-8-bom", "utf-8", "cp949", "euc-kr", "ascii"],
                            "default": "utf-8-bom"
                        }
                    },
                    "required": ["file_name", "directory_path"]
                }
            ),
            Tool(
                name="detect_file_encoding",
                description="Accurately detect file encoding using professional libraries.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "file_name": {
                            "type": "string",
                            "description": "File name to check (e.g., hello.cpp, test.h)"
                        },
                        "directory_path": {
                            "type": "string",
                            "description": "Absolute path of directory containing the file"
                        },
                        "max_bytes": {
                            "type": "integer",
                            "description": "Maximum bytes to analyze (default: 8192)",
                            "default": 8192,
                            "minimum": 512,
                            "maximum": 65536
                        }
                    },
                    "required": ["file_name", "directory_path"]
                }
            ),
            Tool(
                name="convert_file_encoding",
                description="Convert file to specified encoding. Automatic backup support.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "file_name": {
                            "type": "string",
                            "description": "File name to convert (e.g., hello.cpp, test.h)"
                        },
                        "directory_path": {
                            "type": "string",
                            "description": "Absolute path of directory containing the file"
                        },
                        "target_encoding": {
                            "type": "string",
                            "description": "Target encoding",
                            "enum": ["utf-8-bom", "utf-8", "cp949", "euc-kr", "ascii"],
                            "default": "utf-8-bom"
                        },
                        "backup": {
                            "type": "boolean",
                            "description": "Whether to backup original file",
                            "default": False
                        }
                    },
                    "required": ["file_name", "directory_path"]
                }
            ),
            Tool(
                name="get_system_info",
                description="Check Encoding MCP system information. Shows available libraries and supported encodings.",
                inputSchema={
                    "type": "object",
                    "properties": {},
                    "required": []
                }
            )
        ]
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'automatic backup support,' which adds some context about safety features, but fails to describe critical behaviors such as whether the conversion is destructive (overwrites the original file), what happens on errors, or any rate limits or permissions required. This leaves significant gaps in understanding the tool's operation.

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 very concise with two short sentences that efficiently convey the core functionality and a key feature. It is front-loaded with the main purpose, and every sentence adds value without redundancy. A slight improvement could be made by integrating usage context, but it's well-structured and to the point.

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 tool's complexity (file conversion with potential data loss), lack of annotations, and no output schema, the description is insufficient. It doesn't explain return values, error handling, or the implications of encoding changes, which are critical for safe usage. The description should provide more context to compensate for the 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%, so the input schema already documents all parameters thoroughly. The description adds minimal value beyond the schema by implying the tool handles file encoding conversion and backup, but it doesn't provide additional semantic context (e.g., how encodings affect file content or backup details). This meets the baseline for high schema coverage.

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 with a specific verb ('convert') and resource ('file'), specifying the action of changing file encoding. It distinguishes from siblings like 'create_empty_file' or 'detect_file_encoding' by focusing on conversion rather than creation or detection. However, it doesn't explicitly differentiate from all siblings (e.g., 'get_system_info'), keeping it from a perfect score.

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 like 'detect_file_encoding' or other encoding-related operations. It mentions 'automatic backup support' as a feature but doesn't specify scenarios where this tool is preferred or when it should be avoided, leaving usage context implied at best.

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/whyjp/encoding_mcp'

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