MCP CLI features a unified command system that works consistently across all operational modes: Chat mode, Interactive mode, CLI mode, and Command mode. This document describes the command architecture, patterns, and usage.
The command system is built on a unified architecture defined in src/mcp_cli/commands/base.py:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ UnifiedCommand (Base Class) โ
โ - Single implementation works in all modes โ
โ - Consistent behavior and validation โ
โ - Mode-specific formatting support โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโ
โ โ โ
โโโโโโโโโผโโโโโโโ โโโโโโโผโโโโโโโ โโโโโโโผโโโโโโโ
โ Chat Mode โ โ Interactiveโ โ CLI Mode โ
โ /command โ โ command โ โ mcp-cli cmdโ
โโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโ โโโโโโโโโโโโโโ
Every command is built from these components:
- Command Definition (
src/mcp_cli/commands/definitions/) - Defines command metadata - Command Action (
src/mcp_cli/commands/actions/) - Implements command logic - Command Models (
src/mcp_cli/commands/models/) - Pydantic models for parameters and responses - Command Registry (
src/mcp_cli/commands/registry.py) - Central command registration
Commands can support one or more operational modes:
class CommandMode(Flag):
CHAT = auto() # Chat mode (/command)
CLI = auto() # CLI mode (mcp-cli command)
INTERACTIVE = auto() # Interactive mode (command)
ALL = CHAT | CLI | INTERACTIVEMCP CLI follows a consistent singular/plural pattern for related commands:
| Command Type | Purpose | Example | Result |
|---|---|---|---|
| Singular | Show current status | /model |
Shows current model with tips |
| Plural | List all available | /models |
Lists all models in a table |
| Singular + Name | Direct action | /model gpt-4o |
Switches to gpt-4o |
| Singular + Subcommand | Specific action | /model refresh |
Refreshes model discovery |
Examples:
# Models
/model # Show current model status
/models # List all available models
/model gpt-4o # Switch to gpt-4o directly
/model refresh # Refresh model discovery
# Providers
/provider # Show current provider status
/providers # List all available providers
/provider ollama # Switch to Ollama provider
/provider set openai api_key KEY # Configure provider
# Themes
/theme # Show current theme with preview
/themes # List all available themes
/theme dark # Switch to dark theme
# Servers
/server echo # Show details about echo server
/servers # List all connected MCP servers
/servers ping # Ping all serversSome commands have subcommands organized into groups:
# Tools command group
/tools # List available tools (default: list)
/tools list # List tools explicitly
/tools call # Interactive tool execution
/tools --all # Detailed tool information
# Server command group
/server # List servers (default)
/server list # List servers explicitly
/server add <name> # Add a new server
/server remove <name> # Remove a server
/server ping <name> # Ping specific server
# Token command group
/token # List tokens (default)
/token list # List tokens explicitly
/token set <name> # Store a token
/token get <name> # Get token details
/token delete <name> # Delete a tokenShow Current Provider:
/provider # Show current configuration (default: ollama)List All Providers:
/providers # List all providersSwitch Provider:
/provider ollama # Switch to Ollama
/provider openai # Switch to OpenAI (requires API key)
/provider anthropic # Switch to Anthropic (requires API key)
/provider openai gpt-4o # Switch to OpenAI with specific modelProvider Configuration:
/provider set openai api_key sk-... # Configure API key
/provider set ollama api_base http://localhost:11434 # Configure endpoint
/provider config # Show detailed configuration
/provider diagnostic # Test provider connectivityCustom Provider Management:
/provider custom # List custom providers
/provider add localai http://localhost:8080/v1 gpt-4 # Add custom provider
/provider remove localai # Remove custom providerShow Current Model:
/model # Show current model (default: gpt-oss)List Available Models:
/models # List models for current provider
/models openai # List models for specific providerSwitch Model:
/model llama3.3 # Switch to different Ollama model
/model gpt-4o # Switch to GPT-4 (if using OpenAI)
/model claude-3-5-sonnet-20241022 # Switch to Claude 3.5 (if using Anthropic)Model Discovery:
/model refresh # Refresh available modelsList Tools:
/tools # List available tools
/tools --all # Show detailed tool information
/tools --raw # Show raw JSON definitionsExecute Tools:
/tools call # Interactive tool executionTool History:
/toolhistory # Show tool execution history
/th -n 5 # Last 5 tool calls
/th 3 # Details for call #3
/th --json # Full history as JSONList Servers:
/server # List all configured servers
/servers # List servers (alias)
/servers list # List servers explicitly
/servers list all # Include disabled serversAdd Servers:
Runtime server additions persist in ~/.mcp-cli/preferences.json:
# STDIO servers
/server add sqlite stdio uvx mcp-server-sqlite --db-path test.db
/server add playwright stdio npx @playwright/mcp@latest
/server add time stdio uvx mcp-server-time
/server add fs stdio npx @modelcontextprotocol/server-filesystem /path/to/dir
# HTTP/SSE servers with authentication
/server add github --transport http --header "Authorization: Bearer ghp_token" -- https://api.github.com/mcp
/server add myapi --transport http --env API_KEY=secret -- https://api.example.com/mcp
/server add events --transport sse -- https://events.example.com/sseManage Servers:
/server enable <name> # Enable a disabled server
/server disable <name> # Disable without removing
/server remove <name> # Remove user-added server
/server ping <name> # Test server connectivity
/server <name> # Show server configuration detailsServer Details:
/server echo # Show details about echo server
/servers ping # Ping all serversList Tokens:
/token # List all tokens (default)
/token list # List all tokens explicitly
/token list --oauth # Only OAuth tokens
/token list --api-keys # Only API keys
/token list --bearer # Only bearer tokensStore Tokens:
/token set my-server --type bearer # Interactive prompt (secure)
/token set openai --type api-key --provider openai # API key
/token set my-api --type bearer --value "token123" # With value (less secure)Get Token Info:
/token get my-server # Get metadata
/token get openai --namespace api-key # Get from specific namespace
/token get notion --oauth # Get OAuth tokenDelete Tokens:
/token delete my-server # Delete bearer token
/token delete openai --namespace api-key # Delete from namespace
/token delete notion --oauth # Delete OAuth token
/token clear # Clear all tokens (with confirmation)
/token clear --force # Clear without confirmationStorage Backends:
/token backends # List available backendsSee TOKEN_MANAGEMENT.md for comprehensive token documentation.
View History:
/conversation # Show conversation history
/ch -n 10 # Last 10 messages
/ch 5 # Details for message #5
/ch --json # Full history as JSONSave & Clear:
/save conversation.json # Save conversation to file
/compact # Summarize conversation
/clear # Clear conversation history
/cls # Clear screen onlyTheme Management:
/theme # Interactive theme selector with preview
/theme dark # Switch to dark theme
/theme monokai # Switch to monokai theme
/themes # List all available themesAvailable Themes:
- default
- dark
- light
- minimal
- terminal
- monokai
- dracula
- solarized
Themes are persisted across sessions in user preferences.
Display Settings:
/verbose # Toggle verbose/compact display (Default: Enabled)
/confirm # Toggle tool call confirmation (Default: Enabled)System Commands:
/help # Show all commands
/help tools # Help for specific command
/interrupt # Stop running operations
/exit # Exit chat modeTo create a new command, implement the UnifiedCommand interface:
# src/mcp_cli/commands/definitions/mycommand.py
from mcp_cli.commands.base import UnifiedCommand, CommandMode, CommandResult
class MyCommand(UnifiedCommand):
@property
def name(self) -> str:
return "mycommand"
@property
def aliases(self) -> List[str]:
return ["mc"] # Optional aliases
@property
def description(self) -> str:
return "My custom command"
@property
def modes(self) -> CommandMode:
return CommandMode.ALL # Support all modes
async def execute(self, **kwargs) -> CommandResult:
# Implementation
return CommandResult(success=True, output="Done!")Define parameters for type-safe argument handling:
from mcp_cli.commands.base import CommandParameter
@property
def parameters(self) -> List[CommandParameter]:
return [
CommandParameter(
name="server_name",
type=str,
required=True,
help="Name of the server"
),
CommandParameter(
name="verbose",
type=bool,
default=False,
is_flag=True,
help="Enable verbose output"
)
]Use Pydantic models for structured parameters:
# src/mcp_cli/commands/models/mycommand.py
from pydantic import BaseModel
class MyCommandParams(BaseModel):
server_name: str
verbose: bool = False
class MyCommandResponse(BaseModel):
success: bool
message: strImplement the action logic separately for better organization:
# src/mcp_cli/commands/actions/mycommand.py
from mcp_cli.commands.models.mycommand import MyCommandParams, MyCommandResponse
async def my_command_action(params: MyCommandParams) -> MyCommandResponse:
# Implementation logic
return MyCommandResponse(success=True, message="Complete")Register commands in the central registry:
# src/mcp_cli/commands/__init__.py
from mcp_cli.commands.registry import registry
from mcp_cli.commands.definitions.mycommand import MyCommand
def register_commands():
registry.register(MyCommand())Commands in chat mode use the / prefix:
# Start chat mode
mcp-cli --server sqlite
# Use commands
> /provider openai
> /model gpt-4o
> /tools list
> /server add myserver stdio node server.jsCommands in interactive mode don't require the / prefix:
# Start interactive mode
mcp-cli interactive --server sqlite
# Use commands
> provider openai
> model gpt-4o
> tools list
> serversCommands in CLI mode use the standard CLI syntax:
# Direct CLI commands
mcp-cli provider list
mcp-cli model set gpt-4o
mcp-cli tools --server sqlite
mcp-cli servers list
# With global options
mcp-cli --provider openai --server sqlite toolsUnix-friendly automation mode:
# Tool execution
mcp-cli cmd --server sqlite --tool list_tables --raw
# Text processing
echo "data" | mcp-cli cmd --server sqlite --input - --output result.txt
# Pipeline usage
mcp-cli cmd --tool read_query --tool-args '{"query": "SELECT * FROM users"}' | jq .Users can guess commands based on consistent patterns:
- Singular shows current state
- Plural lists all options
- Direct actions without unnecessary subcommands
Tips and indicators guide users to related commands:
๐ก Tip: Use: /model <name> to switch | /models to list all | /model refresh to discover
Quick actions available without deep menu navigation:
/theme dark # Direct action
/provider openai # Direct switch
/model gpt-4o # Direct selectionSame patterns across all command groups:
- All listing commands use tables
- All status commands use panels
- All commands have help text
Uses theme colors, not hardcoded values:
from chuk_term.ui import output
output.success("Operation complete") # Uses theme's success color
output.error("Failed") # Uses theme's error color
output.info("Information") # Uses theme's info colorTyping just / shows a menu of all available commands:
Available Commands:
clear โธ - Clear conversation or screen
conversation - Show conversation history
exit - Exit the application
help - Show help information
model โธ - Show current model or switch models
models - List all available models
provider โธ - Show current provider or switch providers
providers - List all available providers
server โธ - Manage MCP servers
servers - List all connected servers
theme โธ - Show or change UI theme
themes - List all available themes
token โธ - Manage authentication tokens
tools โธ - List and manage tools
Indicators:
โธ- Command has subcommands available- No indicator - Direct command with no subcommands
Status commands use panels for clear presentation:
โญโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฎ
โ โน Current provider: openai โ
โ โน Current model : gpt-4o-mini โ
โ โน Status : โ
Ready โ
โ โน Features : ๐ก ๐ง ๐๏ธ โ
โฐโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโฏ
List commands use formatted tables:
โโโโโโโโโโโโฌโโโโโโโโโโโโฌโโโโโโโโโโโโโโโ
โ Provider โ Status โ Models โ
โโโโโโโโโโโโผโโโโโโโโโโโโผโโโโโโโโโโโโโโโค
โ openai โ โ
Ready โ 15 models โ
โ ollama โ โ
Ready โ 51 models โ
โโโโโโโโโโโโดโโโโโโโโโโโโดโโโโโโโโโโโโโโโ
Commands automatically validate parameters before execution:
def validate_parameters(self, **kwargs) -> Optional[str]:
for param in self.parameters:
if param.required and param.name not in kwargs:
return f"Missing required parameter: {param.name}"
if param.name in kwargs and param.choices:
if kwargs[param.name] not in param.choices:
return f"Invalid choice for {param.name}"
return NoneCommands can format output differently for each mode:
def format_output(self, result: CommandResult, mode: CommandMode) -> str:
if mode == CommandMode.CLI:
# Machine-readable format
return json.dumps(result.data)
else:
# Human-readable format
return result.outputCommands can specify if they need active context:
@property
def requires_context(self) -> bool:
return True # Needs tool_manager, llm_client, etc.Hidden Commands
Commands can be hidden from help menus:
@property
def hidden(self) -> bool:
return True # Won't appear in /helpCommands use consistent error handling patterns:
async def execute(self, **kwargs) -> CommandResult:
try:
# Execute action
result = await my_action(params)
return CommandResult(success=True, data=result)
except ValueError as e:
return CommandResult(success=False, error=f"Invalid parameter: {e}")
except Exception as e:
return CommandResult(success=False, error=f"Command failed: {e}")Common error patterns:
- Missing parameters: Validated before execution
- Invalid choices: Checked against allowed values
- Context errors: Graceful handling of missing context
- Action failures: Proper error messages with hints
- Keep it Simple: Commands should do one thing well
- Use Defaults: Sensible defaults for optional parameters
- Provide Help: Clear descriptions and examples
- Be Consistent: Follow established patterns
- Think User-First: Design for how users will actually use it
- Separate Concerns: Definition โ Model โ Action
- Use Type Hints: Leverage Pydantic for validation
- Handle Errors: Graceful error messages
- Test All Modes: Ensure command works in all supported modes
- Document: Update command help and this guide
- Fast Defaults: Most common action is the default
- Clear Feedback: Users know what happened
- Helpful Tips: Guide users to related commands
- Visual Clarity: Use tables, panels, and colors appropriately
- Keyboard Friendly: Tab completion and shortcuts
Planned command system improvements:
- Command aliases configuration (user-defined)
- Command history and replay
- Command composition and piping
- Custom command plugins
- Command macros and scripts
- Tab completion improvements
- Command fuzzy search
- Interactive command builder
- Command export/import
- Command templates
- COMMAND_PATTERNS.md - Detailed pattern documentation
- TOKEN_MANAGEMENT.md - Token command reference
- OAUTH.md - OAuth authentication
- README.md - Main documentation