unprotect_document
Remove password protection from Word documents. Enter the filename and password to unlock and edit secure files with ease.
Instructions
Remove password protection from a Word document.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| filename | Yes | ||
| password | Yes |
Implementation Reference
- The core handler function implementing the unprotect_document tool logic using msoffcrypto to decrypt password-protected Word documents.async def unprotect_document(filename: str, password: str) -> str: """Remove password protection from a Word document. Args: filename: Path to the Word document password: Password that was used to protect the document """ filename = ensure_docx_extension(filename) if not os.path.exists(filename): return f"Document {filename} does not exist" # Check if file is writeable is_writeable, error_message = check_file_writeable(filename) if not is_writeable: return f"Cannot modify document: {error_message}" try: # Read the encrypted file content with open(filename, "rb") as infile: encrypted_data = infile.read() # Create an msoffcrypto file object from the encrypted data file = msoffcrypto.OfficeFile(io.BytesIO(encrypted_data)) file.load_key(password=password) # Set the password for decryption # Decrypt the data into an in-memory buffer decrypted_data_io = io.BytesIO() file.decrypt(outfile=decrypted_data_io) # Pass the buffer as the 'outfile' argument # Overwrite the original file with the decrypted data with open(filename, "wb") as outfile: outfile.write(decrypted_data_io.getvalue()) return f"Document {filename} decrypted successfully." except msoffcrypto.exceptions.InvalidKeyError: return f"Failed to decrypt document {filename}: Incorrect password." except msoffcrypto.exceptions.InvalidFormatError: return f"Failed to decrypt document {filename}: File is not encrypted or is not a supported Office format." except Exception as e: # Attempt to restore encrypted file content on failure try: if 'encrypted_data' in locals(): with open(filename, "wb") as outfile: outfile.write(encrypted_data) return f"Failed to decrypt document {filename}: {str(e)}. Encrypted file restored." else: return f"Failed to decrypt document {filename}: {str(e)}. Could not restore encrypted file." except Exception as restore_e: return f"Failed to decrypt document {filename}: {str(e)}. Also failed to restore encrypted file: {str(restore_e)}"
- word_document_server/main.py:779-782 (registration)MCP tool registration for 'unprotect_document' using FastMCP @mcp.tool() decorator. This wrapper delegates execution to the implementation in protection_tools.py.async def unprotect_document(filename: str, password: str): """Remove password protection from a Word document.""" return await protection_tools.unprotect_document(filename, password)