Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
e8c365f
refactor: move runners to dedicated pkg/runner package
inercia Feb 3, 2026
a04b799
refactor: remove agent functionality
inercia Feb 3, 2026
9574575
feat: add shell completion command
inercia Feb 3, 2026
4490786
chore: update dependencies and go version
inercia Feb 3, 2026
957dff3
refactor: update imports after runner extraction
inercia Feb 3, 2026
3b4aa3d
docs: add documentation index and environment variables reference
inercia Feb 3, 2026
e340560
docs: add container deployment guide
inercia Feb 3, 2026
3f91473
docs: remove agent documentation
inercia Feb 3, 2026
2f204f8
docs: update documentation for refactored codebase
inercia Feb 3, 2026
b23ba22
chore: update license year and readme
inercia Feb 3, 2026
6e01df0
chore: add VS Code workspace file
inercia Feb 3, 2026
c6da923
chore: add Augment AI rules and configuration
inercia Feb 3, 2026
bb11476
fix: remove .code-workspace
inercia Feb 3, 2026
1ebf260
fix(security): prevent MCP clients from overriding runner options
inercia Feb 3, 2026
31c171a
fix: remove unused MCPShellAgentConfigEnv constant
inercia Feb 3, 2026
45a28fa
fix: rename ResolveMultipleConfigPath to ResolveMultipleConfigPaths
inercia Feb 3, 2026
e620370
test: restore missing runner tests
inercia Feb 3, 2026
8ca12b6
fix: use sh instead of bash for Docker Alpine container tests
inercia Feb 3, 2026
61d5b08
fix: quote environment variables in Docker runner to handle spaces
inercia Feb 3, 2026
0b4cb26
fix: use shell-safe quoting for Docker environment variables
inercia Feb 3, 2026
77dccdd
fix: quote environment variable values in Docker script to handle spaces
inercia Feb 3, 2026
ebebdd0
fix: trim command whitespace in Docker script to avoid trailing newli…
inercia Feb 3, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
259 changes: 259 additions & 0 deletions .augment/rules/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
---
type: "always_apply"
---

# Architecture and Design Patterns for MCPShell

## Project Structure

### Directory Organization
```
mcpshell/
├── cmd/ # Command-line interface implementation
│ ├── root.go # Root command and global flags
│ ├── mcp.go # MCP server command
│ ├── exe.go # Direct tool execution command
│ ├── validate.go # Configuration validation command
│ └── daemon.go # Daemon mode command
├── pkg/ # Core application packages
│ ├── server/ # MCP server implementation
│ ├── command/ # Command execution and runners
│ ├── config/ # Configuration loading and validation
│ ├── common/ # Shared utilities and types
│ └── utils/ # Helper functions
├── docs/ # Documentation
├── examples/ # Example configurations
├── tests/ # Integration and E2E tests
├── build/ # Build output directory
└── main.go # Application entry point
```

### Package Responsibilities

#### `cmd/` Package
- Command-line interface implementation using Cobra
- Command definitions and flag parsing
- User interaction and output formatting
- Delegates business logic to `pkg/` packages

#### `pkg/server/` Package
- MCP server lifecycle management
- Tool registration and discovery
- Request handling and routing
- Integration with MCP protocol library

#### `pkg/command/` Package
- Command handler creation and execution
- Runner implementations (exec, firejail, sandbox-exec, docker)
- Template processing and parameter substitution
- Constraint evaluation and validation

#### `pkg/config/` Package
- YAML configuration loading and parsing
- Configuration validation
- Tool definition structures
- Configuration merging for multiple files

#### `pkg/common/` Package
- Shared types and interfaces
- Logging infrastructure
- Constraint compilation and evaluation (CEL)
- Template utilities
- Panic recovery
- Prerequisite checking

#### `pkg/utils/` Package
- Helper functions for file operations
- Path resolution and normalization
- Home directory detection
- Tool file discovery

## Design Patterns

### Dependency Injection
- Pass dependencies (logger, config) as parameters to constructors
- Use constructor functions (New*) for complex types
- Avoid global state except for the global logger
- Example:
```go
func New(cfg Config, logger *common.Logger) *Server {
return &Server{
config: cfg,
logger: logger,
}
}
```

### Interface-Based Design
- Define interfaces for pluggable components (Runner, ModelProvider)
- Use interfaces to enable testing with mocks
- Keep interfaces small and focused (Interface Segregation Principle)
- Example:
```go
type Runner interface {
Run(ctx context.Context, shell string, command string, env []string, params map[string]interface{}, tmpfile bool) (string, error)
CheckImplicitRequirements() error
}
```

### Factory Pattern
- Use factory functions for creating handlers and runners
- Factory functions handle initialization and validation
- Example:
```go
func NewCommandHandler(tool config.Tool, shell string, logger *common.Logger) (*CommandHandler, error)
```

### Strategy Pattern
- Multiple runner implementations (ExecRunner, FirejailRunner, SandboxRunner, DockerRunner)
- Runner selection based on requirements and availability
- Fallback to default runner when specific runner unavailable

### Builder Pattern
- Configuration structs with optional fields
- Use functional options for complex initialization when needed
- Example:
```go
type Config struct {
ConfigFile string
Shell string
Logger *common.Logger
Version string
Descriptions []string
DescriptionFiles []string
DescriptionOverride bool
}
```

## Architectural Principles

### Separation of Concerns
- Clear separation between CLI, business logic, and infrastructure
- Each package has a single, well-defined responsibility
- Avoid circular dependencies between packages

### Error Handling
- Errors are wrapped with context at each layer
- Use `fmt.Errorf` with `%w` for error wrapping
- Log errors at the point where they can be handled
- Return errors to callers for decision-making

### Logging Strategy
- Structured logging with levels (Debug, Info, Warn, Error)
- Logger passed as dependency, not accessed globally (except via GetLogger)
- Debug logging for detailed diagnostics
- Info logging for important events
- Error logging for failures

### Context Propagation
- Pass `context.Context` as first parameter for I/O operations
- Use context for cancellation and timeouts
- Respect context cancellation in long-running operations

### Configuration Management
- YAML-based configuration files
- Support for multiple configuration files with merging
- Validation at load time
- Default values for optional settings

## Security Architecture

### Defense in Depth
- Multiple layers of security (constraints, runners, validation)
- Fail-safe defaults (deny by default)
- Explicit whitelisting over blacklisting

### Constraint System
- CEL-based constraint evaluation
- Constraints compiled at startup for early error detection
- Constraint failures block command execution
- Detailed logging of constraint evaluation

### Runner Isolation
- Sandboxed execution environments (firejail, sandbox-exec, docker)
- Minimal permissions by default
- Network isolation when possible
- Filesystem restrictions

### Input Validation
- Type checking for all parameters
- Constraint validation before execution
- Template validation at load time
- Path normalization and validation

## Testing Architecture

### Test Organization
- Unit tests in same package as source code (`*_test.go`)
- Integration tests in `tests/` directory
- Shell scripts for E2E testing
- Test utilities in `tests/common/`

### Test Patterns
- Table-driven tests for multiple scenarios
- Test logger that discards output
- Mock implementations of interfaces
- Separate test fixtures and data

### Test Coverage
- Unit tests for business logic
- Integration tests for command execution
- E2E tests for full workflows
- Security tests for constraint validation

## Extension Points

### Adding New Runners
1. Implement the `Runner` interface
2. Add runner-specific options and requirements
3. Register runner in runner factory
4. Add tests for new runner
5. Document runner capabilities and limitations

### Adding New Commands
1. Create command file in `cmd/` package
2. Define command structure with Cobra
3. Implement command logic
4. Add command to root command in `init()`
5. Add tests and documentation

### Adding New Model Providers
1. Implement the `ModelProvider` interface
2. Add provider-specific configuration
3. Register provider in model factory
4. Add tests for provider integration
5. Document provider setup and usage

## Performance Considerations

### Constraint Compilation
- Constraints compiled once at startup
- Compiled constraints reused for all executions
- Reduces overhead for repeated tool calls

### Template Caching
- Templates parsed once during handler creation
- Reused for all executions of the same tool
- Reduces parsing overhead

### Concurrent Execution
- Tools can be executed concurrently
- Context-based cancellation for timeouts
- Proper cleanup of resources

## Scalability Considerations

### Multiple Configuration Files
- Support for loading multiple configuration files
- Configuration merging for combining tool sets
- Efficient tool registration and lookup

### Large Tool Sets
- Efficient tool registration
- Fast tool lookup by name
- Minimal memory overhead per tool

### Long-Running Operations
- Context-based timeouts
- Graceful cancellation
- Resource cleanup on timeout or cancellation
66 changes: 66 additions & 0 deletions .augment/rules/configuration.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Configuration Standards for MCPShell

## YAML Structure
```yaml
mcp:
description: "What this tool collection does"
run:
shell: bash
tools:
- name: "tool_name"
description: "What the tool does"
run:
command: "echo {{ .param }}"
params:
param:
type: string
description: "Parameter description"
required: true
```

## Required Fields
- MCP server: `description`
- Each tool: `name`, `description`, `run.command`
- Each parameter: `description`

## Tool Naming
- Lowercase with underscores: `disk_usage`, `file_reader`
- Descriptive and concise

## Parameters
- Types: `string`, `number`, `integer`, `boolean`
- Mark as `required: true` or provide `default` values
- Write detailed descriptions for LLM understanding

## Constraints
- **ALWAYS** include constraints for user input
- Add inline comments explaining each constraint
- Common patterns: command injection prevention, path traversal, length limits, whitelisting

## Templates
- Go template syntax: `{{ .param_name }}`
- Quote variables: `"{{ .param }}"`
- Supports Sprig functions

## Runners
- Order by preference (most restrictive first)
- Include fallback (usually `exec`)
- Disable networking when not needed: `allow_networking: false`
- Specify OS requirements for platform-specific runners

## Environment Variables
- **ONLY** pass explicitly whitelisted variables
- Document why each is needed

## Timeouts
- **ALWAYS** specify timeout for commands that may hang
- Format: `"30s"`, `"5m"`, `"1h30m"`

## Validation
- Use `mcpshell validate --tools <file>`
- Run `make validate-examples` in CI/CD

## Agent Mode

For AI agent functionality (LLM connectivity, RAG support), see the
[Don](https://github.com/inercia/don) project which uses MCPShell's tool configuration.
27 changes: 27 additions & 0 deletions .augment/rules/documentation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Documentation Standards for MCPShell

## Code Documentation
- **ALWAYS** include package-level documentation: `// Package <name> <description>.`
- Document all exported functions, types, and important fields
- Start comments with the name of what's being documented
- Use complete sentences with proper punctuation

## Configuration Documentation
- Document all options in `docs/config.md`
- Document environment variables in `docs/config-env.md`
- Provide well-commented examples in `examples/`
- Include security rationale for constraints
- Show both simple and advanced patterns
- Cross-link related documentation (config, env vars, usage guides)

## Security Documentation
- Maintain comprehensive `docs/security.md`
- Include prominent security warnings
- Explain risks of LLM command execution
- Provide secure configuration examples

## Markdown Standards
- Use ATX-style headers (`#`, `##`, `###`)
- Specify language for code blocks (`yaml`, `go`, `bash`)
- Use descriptive link text
- Use relative links for internal docs
28 changes: 28 additions & 0 deletions .augment/rules/go.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# Go Coding Standards for MCPShell

## Package Documentation
- **ALWAYS** include package-level documentation: `// Package <name> <description>.`
- Explain package purpose and responsibilities

## Error Handling & Logging
- Wrap errors with `fmt.Errorf` and `%w`: `fmt.Errorf("failed to compile constraint '%s': %w", expr, err)`
- Error messages: lowercase, no punctuation
- **ALWAYS** use `common.Logger` (never `fmt.Println` or `log.Println`)
- Logger passed as parameter to functions
- Levels: Debug (diagnostics), Info (events), Warn (non-critical), Error (failures)

## Panic Recovery
- Use `defer common.RecoverPanic()` at entry points and goroutines

## Project-Specific Patterns
- YAML config with tags: `yaml:"field_name,omitempty"`
- Templates: Go `text/template` + Sprig functions, variables as `{{ .param_name }}`
- Context: First parameter for I/O operations, use `context.WithTimeout`
- Constructors: Provide `New*` functions for complex types
- Type assertions: Check success, handle failures gracefully

## Code Quality
- Run `make format` before commits (runs `go fmt ./...` and `go mod tidy`)
- Pass `golangci-lint` checks
- Godoc-style comments for exported APIs
- Never manually edit `go.mod`
Loading
Loading