This comprehensive guide covers all aspects of using UCW (Universal Command Wrapper).
- Quick Start
- CLI Interface
- Library Interface
- Examples
- API Reference
- Advanced Usage
- Troubleshooting
- Appendices
# Generate wrapper in memory (JSON output)
python cli.py wrap echo
# Generate wrapper and save to file
python cli.py wrap echo --output my_cli.py
# Parse command specification
python cli.py parse echo
# Execute command
python cli.py execute echo --args "hello" "world"from __init__ import UniversalCommandWrapper
# Initialize UCW
ucw = UniversalCommandWrapper()
# Parse and wrap a command
spec = ucw.parse_command("echo")
wrapper = ucw.build_wrapper(spec)
# Execute the command with arguments
result = wrapper.run("hello", "world")
print(result.stdout)python cli.py wrap <command> [options]Options:
--output,-o: Output file path for generated wrapper--update,-u: Update existing file instead of creating new one--platform: Target platform (windows,posix,linux,auto)--timeout-help: Timeout for help commands in seconds (default: 10)--timeout-exec: Timeout for command execution in seconds (default: 30)
Examples:
# Basic wrapper generation
python cli.py wrap cp
# Generate CLI file
python cli.py wrap tar --output cli.py
# Update existing CLI file
python cli.py wrap find --update cli.pypython cli.py parse <command> [options]Options:
--platform: Target platform (windows,posix,linux,auto)--timeout-help: Timeout for help commands in seconds (default: 10)
Examples:
# Parse command help
python cli.py parse grep
# Parse with specific platform
python cli.py parse dir --platform windowspython cli.py execute <command> [options]Options:
--args: Positional arguments--options: JSON string of options/flags--platform: Target platform (windows,posix,linux,auto)--timeout-help: Timeout for help commands in seconds (default: 10)--timeout-exec: Timeout for command execution in seconds (default: 30)
Examples:
# Execute with arguments
python cli.py execute echo --args "hello" "world"
# Execute with options
python cli.py execute ls --options '{"--all": true, "-l": true}'python cli.py wrap echo
# Output: {"status": "success", "command": "echo", ...}python cli.py --standalone wrap echo
python cli.py --human wrap echo
# Output: Human-readable textfrom __init__ import UniversalCommandWrapper
# Initialize with platform detection
ucw = UniversalCommandWrapper()
# Parse a command
spec = ucw.parse_command("grep")
print(f"Command: {spec.name}")
print(f"Options: {len(spec.options)}")
print(f"Positional args: {len(spec.positional_args)}")
# Build wrapper
wrapper = ucw.build_wrapper(spec)
# Execute with arguments
result = wrapper.run("pattern", "file.txt")When commands have parsed options, you can use kwargs to pass them:
# Parse a command with options
spec = ucw.parse_command("tar")
wrapper = ucw.build_wrapper(spec)
# Use kwargs for boolean flags (normalized from flag names)
result = wrapper.run(verbose=True, create=True)
# Use kwargs for value options
result = wrapper.run(file="archive.tar", directory="/path")
# Mix positional args and kwargs
result = wrapper.run("source.txt", "dest.txt", verbose=True)Note: Kwargs keys are normalized from flag names:
--verbosebecomesverbose=True-vbecomesv=True--output-filebecomesoutput_file="value"
# Platform-specific initialization
ucw_windows = UniversalCommandWrapper(platform_name="windows")
ucw_posix = UniversalCommandWrapper(platform_name="posix")
# Parse multiple commands
commands = ["cp", "mv", "grep", "find"]
specs = {}
for cmd in commands:
specs[cmd] = ucw.parse_command(cmd)
# Generate CLI files
for cmd, spec in specs.items():
wrapper = ucw.build_wrapper(spec)
file_path = ucw.write_wrapper(cmd, output=f"{cmd}_cli.py")
print(f"Generated {file_path}")# Configure timeouts
ucw = UniversalCommandWrapper(
timeout_help=15, # Help command timeout
timeout_exec=45 # Execution timeout
)
# Environment variables
import os
os.environ['UCW_TIMEOUT_HELP'] = '20'
os.environ['UCW_TIMEOUT_EXEC'] = '60'
ucw = UniversalCommandWrapper() # Uses env varsfrom __init__ import UniversalCommandWrapper
ucw = UniversalCommandWrapper()
# Wrap cp command
cp_spec = ucw.parse_command("cp")
cp_wrapper = ucw.build_wrapper(cp_spec)
# Copy file
result = cp_wrapper.run("source.txt", "dest.txt")
print(f"Copy result: {result.success}")
# Wrap mv command
mv_spec = ucw.parse_command("mv")
mv_wrapper = ucw.build_wrapper(mv_spec)
# Move file
result = mv_wrapper.run("old_name.txt", "new_name.txt")# Wrap grep command
grep_spec = ucw.parse_command("grep")
grep_wrapper = ucw.build_wrapper(grep_spec)
# Search for text
result = grep_wrapper.run("error", "logfile.txt")
print(f"Found {len(result.stdout.splitlines())} matches")# Wrap ls command
ls_spec = ucw.parse_command("ls")
ls_wrapper = ucw.build_wrapper(ls_spec)
# List directory contents
result = ls_wrapper.run()
print("Directory contents:")
print(result.stdout)# Generate MCP plugin for tar command
tar_spec = ucw.parse_command("tar")
tar_wrapper = ucw.build_wrapper(tar_spec)
# Create plugin file
plugin_path = ucw.write_wrapper("tar", output="tar_plugin.py")
print(f"Generated MCP plugin: {plugin_path}")
# The generated file can be used as an MCP pluginMain class for command analysis and wrapper generation.
class UniversalCommandWrapper:
def __init__(self, platform_name: Optional[str] = None,
timeout_help: Optional[int] = None,
timeout_exec: Optional[int] = None)
def parse_command(self, command_name: str) -> CommandSpec
def build_wrapper(self, spec: CommandSpec) -> CommandWrapper
def write_wrapper(self, command_name: str, output: Optional[str] = None, update: bool = False) -> Union[CommandWrapper, str]Represents a parsed command specification.
@dataclass
class CommandSpec:
name: str
usage: str
options: List[OptionSpec]
positional_args: List[PositionalArgSpec]
description: str
examples: List[str]Represents a command option/flag.
@dataclass
class OptionSpec:
flag: str
takes_value: bool
description: Optional[str]
type_hint: Optional[str]
required: bool
default: Optional[str]Represents a positional argument.
@dataclass
class PositionalArgSpec:
name: str
required: bool
variadic: bool
description: Optional[str]
type_hint: Optional[str]Callable wrapper for executing commands.
class CommandWrapper:
def __init__(self, command_name: str, spec: CommandSpec, timeout: int = 30)
def run(self, *args, **kwargs) -> ExecutionResultRepresents the result of command execution.
@dataclass
class ExecutionResult:
command: str
stdout: str
stderr: str
return_code: int
elapsed: float
success: boolAbstract base class for command parsers.
Parser for Windows command help text (command /?).
Parser for POSIX command help text (command --help, man command).
from parser.base import BaseParser
from models import CommandSpec, OptionSpec
class CustomParser(BaseParser):
def _get_help_command(self, command_name: str) -> List[str]:
return [command_name, "--custom-help"]
def _parse_help_text(self, command_name: str, help_text: str) -> CommandSpec:
# Custom parsing logic
return CommandSpec(
name=command_name,
usage=f"{command_name} [options]",
options=[],
positional_args=[],
description="Custom parsed command",
examples=[]
)
def _is_option_line(self, line: str) -> bool:
return "--" in line
def _parse_option_line(self, line: str) -> OptionSpec:
# Custom option parsing
return None
def _try_alternative_help(self, command_name: str) -> str:
return f"Alternative help for {command_name}"from __init__ import UniversalCommandWrapper
ucw = UniversalCommandWrapper()
try:
spec = ucw.parse_command("nonexistent_command")
wrapper = ucw.build_wrapper(spec)
result = wrapper.run()
if not result.success:
print(f"Command failed: {result.stderr}")
except Exception as e:
print(f"Error: {e}")import json
from __init__ import UniversalCommandWrapper
ucw = UniversalCommandWrapper()
# Process multiple commands
commands = ["echo", "ls", "cp", "mv", "grep"]
results = {}
for cmd in commands:
try:
spec = ucw.parse_command(cmd)
wrapper = ucw.build_wrapper(spec)
result = wrapper.run()
results[cmd] = {
"success": result.success,
"options_count": len(spec.options),
"args_count": len(spec.positional_args)
}
except Exception as e:
results[cmd] = {"error": str(e)}
print(json.dumps(results, indent=2))# Error: Command not found
python cli.py wrap nonexistent_commandSolution: Use commands that exist on your system.
# Error: Permission denied
python cli.py wrap sudoSolution: UCW runs commands with current user privileges.
# Force specific platform
ucw = UniversalCommandWrapper(platform_name="windows")
ucw = UniversalCommandWrapper(platform_name="posix")# Increase timeouts
ucw = UniversalCommandWrapper(timeout_help=30, timeout_exec=60)import logging
logging.basicConfig(level=logging.DEBUG)
# UCW will show detailed debug information
ucw = UniversalCommandWrapper()
spec = ucw.parse_command("echo")- Issues: GitHub Issues
- Discussions: GitHub Discussions
- Documentation: GitHub Wiki
For detailed information on developing plugins for UCW and MCP integration, see the comprehensive Plugin Development Guide. This guide covers:
- Plugin architecture and directory structure
- Creating your first plugin
- Advanced plugin development techniques
- Testing and deployment strategies
- Integration with MCP servers
- Best practices and troubleshooting
The original project vision and goals are documented in the Project Idea. This document outlines:
- The core concept and motivation behind UCW
- Target use cases and applications
- Design principles and architectural decisions
- Future roadmap and expansion plans
- Community and ecosystem considerations
These documents provide additional context for users who want to understand the broader vision and contribute to UCW's plugin ecosystem.