🐺 Initial commit - Lupul Augmentat MCP Server

- MCP server cu stdio transport pentru performanță maximă
- Tool-uri pentru file operations, HTTP requests, system commands
- Suport NATS pentru comunicare inter-module
- Configurare nginx cu API key auth și SSL
- Arhitectură modulară și extensibilă

🤖 Generated with Claude Code
This commit is contained in:
Claude (Lupul Augmentat)
2025-10-09 06:24:58 +02:00
commit 475f89af74
59 changed files with 12827 additions and 0 deletions

182
docs/tools/README.md Normal file
View File

@@ -0,0 +1,182 @@
# MCP Server Built-in Tools
The MCP server comes with a comprehensive set of built-in tools for common operations. All tools include security features, permission controls, and consistent error handling.
## Available Tools
### 📁 File Operations
Tools for reading, writing, and listing files with security controls.
- [**FileReadTool**](./file-operations.md#filereadtool) - Read file contents
- [**FileWriteTool**](./file-operations.md#filewritetool) - Write content to files
- [**FileListTool**](./file-operations.md#filelisttool) - List directory contents
### 💻 System Operations
Execute system commands with security restrictions.
- [**SystemCommandTool**](./system-command.md) - Execute whitelisted system commands
### 🌐 Network Operations
Make HTTP requests to external services.
- [**HttpRequestTool**](./http-request.md) - Make HTTP/HTTPS requests
## Permission Model
Each tool requires specific permissions to execute:
| Tool | Required Permission | Description |
|------|-------------------|-------------|
| FileReadTool | `file:read` | Read access to files |
| FileWriteTool | `file:write` | Write access to files |
| FileListTool | `file:read` | Read access to directories |
| SystemCommandTool | `system:exec` | Execute system commands |
| HttpRequestTool | `network:http` | Make HTTP requests |
## Security Features
All built-in tools implement comprehensive security controls:
### 🛡️ Path Security
- **Directory traversal prevention** - Blocks `..` and absolute paths outside allowed directories
- **Restricted directories** - Cannot access system directories like `/etc`, `/sys`, `/proc`
- **Allowed paths** - Only current working directory and system temp directory
### 🔒 Input Validation
- **Schema validation** - All inputs validated with Zod schemas
- **Command whitelisting** - Only safe system commands allowed
- **Shell injection prevention** - Blocks shell operators in arguments
- **URL validation** - Validates and blocks private IP ranges
### ⏱️ Resource Limits
- **Timeouts** - All operations have configurable timeouts
- **Size limits** - File operations limited to 10MB
- **Output limits** - Command output limited to 1MB
## Error Handling
All tools follow consistent error handling patterns:
```javascript
try {
const result = await mcp.callTool('tool_name', params);
// Handle success
} catch (error) {
// Errors include:
// - Permission denied
// - Invalid input
// - Resource not found
// - Timeout exceeded
// - Operation failed
}
```
## Usage Examples
### Reading a Configuration File
```javascript
const config = await mcp.callTool('file_read', {
path: './config.json'
});
const parsedConfig = JSON.parse(config.content);
```
### Writing Log Data
```javascript
await mcp.callTool('file_write', {
path: './logs/app.log',
content: `[${new Date().toISOString()}] Application started\n`,
mode: 'append'
});
```
### Listing Project Files
```javascript
const files = await mcp.callTool('file_list', {
path: './src',
recursive: true,
pattern: '*.js'
});
```
### Running System Commands
```javascript
const result = await mcp.callTool('system_command', {
command: 'grep',
args: ['-r', 'TODO', '.'],
cwd: './src'
});
```
### Making API Requests
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://api.github.com/user',
headers: {
'Authorization': 'token YOUR_TOKEN'
}
});
```
## Best Practices
1. **Always handle errors** - Tools can fail for various reasons
2. **Use appropriate timeouts** - Don't let operations hang
3. **Validate inputs** - Even though tools validate, check your data
4. **Check permissions** - Ensure required permissions are granted
5. **Use relative paths** - More portable than absolute paths
6. **Respect rate limits** - Especially for HTTP requests
7. **Log operations** - Track what tools are doing
## Extending with Custom Tools
While built-in tools cover common use cases, you can create custom tools for specific needs. See the [Module Development Guide](../modules/development.md) for details on creating custom tools.
## Tool Lifecycle
1. **Input validation** - Schema validation with Zod
2. **Permission check** - Verify required permissions
3. **Pre-execution hooks** - Custom validation/preparation
4. **Execution** - Actual tool operation
5. **Output formatting** - Consistent response format
6. **Error handling** - Structured error responses
## Performance Considerations
- File operations are synchronous within the tool
- HTTP requests use native fetch API
- System commands spawn child processes
- All operations subject to timeout limits
- Large file operations may impact performance
## Troubleshooting
### Permission Denied
```
Error: Permission denied: file:read required
```
Ensure the tool has required permissions in the auth context.
### Invalid Path
```
Error: Invalid path: directory traversal not allowed
```
Use paths within the current directory or temp directory.
### Command Not Allowed
```
Error: Command not allowed: rm
```
Only whitelisted commands can be executed.
### Timeout Exceeded
```
Error: Request timeout after 30000ms
```
Increase timeout or optimize the operation.
## Version History
- **v0.1.0** - Initial release with basic file, system, and HTTP tools
- **v0.2.0** - Added security controls and permission system
- **v0.3.0** - Enhanced error handling and validation

View File

@@ -0,0 +1,165 @@
# File Operations Tools
The MCP server provides several built-in tools for file system operations with comprehensive security controls.
## FileReadTool
Reads the contents of a file with security restrictions.
### Input Schema
```typescript
{
path: string; // File path (relative or absolute)
encoding?: 'utf8' | 'binary'; // Default: 'utf8'
}
```
### Output Schema
```typescript
{
content: string; // File contents
size: number; // File size in bytes
path: string; // Absolute file path
}
```
### Security Features
- Prevents directory traversal attacks
- Only allows access to files within current working directory or system temp directory
- File size limit: 10MB
- Requires `file:read` permission
### Example Usage
```javascript
const result = await mcp.callTool('file_read', {
path: './config.json',
encoding: 'utf8'
});
console.log(result.content);
```
## FileWriteTool
Writes content to a file with security restrictions.
### Input Schema
```typescript
{
path: string; // File path (relative or absolute)
content: string; // Content to write
encoding?: 'utf8' | 'binary' | 'base64'; // Default: 'utf8'
mode?: 'overwrite' | 'append'; // Default: 'overwrite'
}
```
### Output Schema
```typescript
{
path: string; // Absolute file path
size: number; // File size after write
mode: string; // Write mode used
}
```
### Security Features
- Prevents directory traversal attacks
- Only allows writing within current working directory or system temp directory
- Blocks writing to system directories (/etc, /sys, /proc, /dev)
- Requires `file:write` permission
- Automatically creates parent directories if needed
### Example Usage
```javascript
// Write text file
await mcp.callTool('file_write', {
path: './output.txt',
content: 'Hello, World!'
});
// Write binary file
await mcp.callTool('file_write', {
path: './image.png',
content: 'iVBORw0KGgoAAAANS...', // base64 encoded
encoding: 'base64'
});
// Append to file
await mcp.callTool('file_write', {
path: './log.txt',
content: 'New log entry\n',
mode: 'append'
});
```
## FileListTool
Lists files and directories with filtering options.
### Input Schema
```typescript
{
path: string; // Directory path
recursive?: boolean; // Recurse into subdirectories
pattern?: string; // Glob pattern filter (e.g., '*.txt')
includeHidden?: boolean; // Include hidden files (starting with .)
}
```
### Output Schema
```typescript
{
path: string; // Directory path
entries: Array<{
path: string; // Full path
type: 'file' | 'directory' | 'symlink' | 'other';
name: string; // File/directory name
size: number; // Size in bytes
modified: string; // ISO date string
}>;
totalSize: number; // Total size of all files
}
```
### Security Features
- Prevents directory traversal attacks
- Only allows listing within current working directory or system temp directory
- Requires `file:read` permission
- Skips inaccessible items instead of failing
### Example Usage
```javascript
// List directory contents
const result = await mcp.callTool('file_list', {
path: './src'
});
// List recursively with pattern
const jsFiles = await mcp.callTool('file_list', {
path: './src',
recursive: true,
pattern: '*.js'
});
// Include hidden files
const allFiles = await mcp.callTool('file_list', {
path: './',
includeHidden: true
});
```
## Error Handling
All file operation tools follow consistent error handling:
- **File not found**: Returns clear error message with the path
- **Permission denied**: Returns error when lacking required permissions
- **Invalid paths**: Blocks directory traversal and system paths
- **Size limits**: Enforces reasonable limits to prevent abuse
## Best Practices
1. **Always use relative paths** when possible for better portability
2. **Check permissions** before attempting operations
3. **Handle errors gracefully** - file operations can fail for many reasons
4. **Use appropriate encodings** - utf8 for text, base64 for binary data
5. **Be mindful of file sizes** - large files can impact performance

273
docs/tools/http-request.md Normal file
View File

@@ -0,0 +1,273 @@
# HTTP Request Tool
Make HTTP/HTTPS requests with comprehensive options and security controls.
## Overview
The HttpRequestTool enables making HTTP requests to external services with support for various methods, headers, authentication, and response handling.
## Input Schema
```typescript
{
url: string; // Target URL (required)
method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS';
headers?: Record<string, string>; // Request headers
body?: string | object; // Request body
timeout?: number; // Timeout in ms (default: 30000)
followRedirects?: boolean; // Follow redirects (default: true)
}
```
## Output Schema
```typescript
{
status: number; // HTTP status code
statusText: string; // Status message
headers: Record<string, string>; // Response headers
body: any; // Response body (parsed based on content-type)
duration: number; // Request duration in ms
}
```
## Features
### Supported Methods
- **GET** - Retrieve data
- **POST** - Submit data
- **PUT** - Update resource
- **DELETE** - Remove resource
- **PATCH** - Partial update
- **HEAD** - Headers only
- **OPTIONS** - Check allowed methods
### Automatic Content Handling
- JSON responses are automatically parsed
- Text responses returned as strings
- Binary data returned as base64 encoded strings
- Content-Type header automatically set for JSON bodies
### Security Features
- Blocks requests to private IP ranges (localhost, internal networks)
- Validates URLs before making requests
- Timeout protection against hanging requests
- Requires `network:http` permission
## Example Usage
### Simple GET Request
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://api.example.com/users'
});
console.log(response.body); // Parsed JSON
```
### POST with JSON Body
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://api.example.com/users',
method: 'POST',
body: {
name: 'John Doe',
email: 'john@example.com'
}
});
```
### Custom Headers
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://api.example.com/data',
headers: {
'Authorization': 'Bearer token123',
'X-API-Key': 'myapikey'
}
});
```
### Form Data
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://api.example.com/form',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: 'name=John&email=john@example.com'
});
```
### With Timeout
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://slow-api.example.com/data',
timeout: 5000 // 5 seconds
});
```
### Disable Redirect Following
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://example.com/redirect',
followRedirects: false
});
// Check response.status for 301/302
```
## Response Handling
### JSON Response
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://api.example.com/json'
});
// response.body is already parsed object
console.log(response.body.data);
```
### Text Response
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://example.com/text.txt'
});
// response.body is string
console.log(response.body);
```
### Binary Response
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://example.com/image.png'
});
// response.body is base64 encoded string
const buffer = Buffer.from(response.body, 'base64');
```
### Status Checking
```javascript
const response = await mcp.callTool('http_request', {
url: 'https://api.example.com/resource'
});
if (response.status >= 200 && response.status < 300) {
// Success
} else if (response.status === 404) {
// Not found
} else if (response.status >= 500) {
// Server error
}
```
## Error Handling
### Network Errors
```javascript
try {
const response = await mcp.callTool('http_request', {
url: 'https://nonexistent.example.com'
});
} catch (error) {
// Error: HTTP request failed: ...
}
```
### Timeout Errors
```javascript
try {
const response = await mcp.callTool('http_request', {
url: 'https://slow.example.com',
timeout: 1000
});
} catch (error) {
// Error: Request timeout after 1000ms
}
```
### Invalid URLs
```javascript
try {
const response = await mcp.callTool('http_request', {
url: 'not-a-url'
});
} catch (error) {
// Error: Invalid URL
}
```
### Blocked Internal IPs
```javascript
try {
const response = await mcp.callTool('http_request', {
url: 'http://192.168.1.1/admin'
});
} catch (error) {
// Error: Requests to private IP ranges are not allowed
}
```
## Best Practices
1. **Always set appropriate timeouts** for external requests
2. **Handle all status codes** - don't assume 200 OK
3. **Use HTTPS** when possible for security
4. **Set User-Agent** header to identify your application
5. **Implement retry logic** for transient failures
6. **Respect rate limits** of external APIs
7. **Validate response data** before using it
## Common Patterns
### API Authentication
```javascript
// Bearer Token
const response = await mcp.callTool('http_request', {
url: 'https://api.example.com/protected',
headers: {
'Authorization': 'Bearer your-token-here'
}
});
// API Key
const response = await mcp.callTool('http_request', {
url: 'https://api.example.com/data',
headers: {
'X-API-Key': 'your-api-key'
}
});
// Basic Auth
const credentials = Buffer.from('username:password').toString('base64');
const response = await mcp.callTool('http_request', {
url: 'https://api.example.com/secure',
headers: {
'Authorization': `Basic ${credentials}`
}
});
```
### Pagination
```javascript
let allData = [];
let page = 1;
let hasMore = true;
while (hasMore) {
const response = await mcp.callTool('http_request', {
url: `https://api.example.com/items?page=${page}&limit=100`
});
allData = allData.concat(response.body.items);
hasMore = response.body.hasNextPage;
page++;
}
```
## Limitations
- Cannot access localhost or private networks
- Maximum timeout of 5 minutes
- No support for streaming responses
- No built-in retry mechanism
- No connection pooling or keep-alive

View File

@@ -0,0 +1,186 @@
# System Command Tool
Execute system commands with comprehensive security controls and output handling.
## Overview
The SystemCommandTool allows controlled execution of whitelisted system commands with proper security boundaries, timeout handling, and output management.
## Input Schema
```typescript
{
command: string; // Command to execute (must be whitelisted)
args?: string[]; // Command arguments
cwd?: string; // Working directory
env?: Record<string, string>; // Environment variables
timeout?: number; // Timeout in ms (100-300000, default: 30000)
stdin?: string; // Input to send to stdin
}
```
## Output Schema
```typescript
{
stdout: string; // Standard output
stderr: string; // Standard error output
exitCode: number; // Process exit code
duration: number; // Execution time in ms
}
```
## Whitelisted Commands
Only the following commands are allowed for security:
- `ls` - List directory contents
- `cat` - Display file contents
- `grep` - Search text patterns
- `find` - Find files and directories
- `echo` - Print text
- `pwd` - Print working directory
- `whoami` - Show current user
- `date` - Show current date/time
- `env` - Show environment variables
- `which` - Find command location
- `wc` - Word/line/character count
- `head` - Show first lines
- `tail` - Show last lines
- `sort` - Sort lines
- `uniq` - Remove duplicate lines
- `curl` - HTTP requests
- `ping` - Network connectivity test
- `dig` - DNS lookup
- `ps` - Process list
- `df` - Disk usage
- `du` - Directory size
- `uptime` - System uptime
## Security Features
### Command Validation
- Only whitelisted commands can be executed
- Shell operators (`|`, `&`, `;`, `>`, `<`, etc.) are blocked in arguments
- Prevents command injection attacks
### Resource Limits
- Configurable timeout (max 5 minutes)
- Output size limited to 1MB per stream
- Process is killed if limits exceeded
### Permission Control
- Requires `system:exec` permission
- Inherits process environment with modifications
## Example Usage
### Basic Command
```javascript
const result = await mcp.callTool('system_command', {
command: 'ls',
args: ['-la', '/tmp']
});
console.log(result.stdout);
```
### With Working Directory
```javascript
const result = await mcp.callTool('system_command', {
command: 'grep',
args: ['-r', 'TODO', '.'],
cwd: '/home/user/project'
});
```
### With Environment Variables
```javascript
const result = await mcp.callTool('system_command', {
command: 'echo',
args: ['$MY_VAR'],
env: {
MY_VAR: 'Hello from environment!'
}
});
```
### With Timeout
```javascript
const result = await mcp.callTool('system_command', {
command: 'find',
args: ['/', '-name', '*.log'],
timeout: 5000 // 5 seconds
});
```
### With stdin Input
```javascript
const result = await mcp.callTool('system_command', {
command: 'grep',
args: ['error'],
stdin: 'line 1\nerror on line 2\nline 3'
});
```
## Error Handling
### Command Not Allowed
```javascript
// This will throw an error
await mcp.callTool('system_command', {
command: 'rm' // Not in whitelist
});
// Error: Command not allowed: rm
```
### Shell Injection Prevention
```javascript
// This will throw an error
await mcp.callTool('system_command', {
command: 'ls',
args: ['; rm -rf /'] // Shell operators blocked
});
// Error: Shell characters not allowed in arguments
```
### Timeout Handling
```javascript
try {
await mcp.callTool('system_command', {
command: 'find',
args: ['/'],
timeout: 1000 // 1 second
});
} catch (error) {
// Error: Command timed out after 1000ms
}
```
### Non-Zero Exit Codes
Non-zero exit codes don't throw errors but are returned in the result:
```javascript
const result = await mcp.callTool('system_command', {
command: 'grep',
args: ['nonexistent', 'file.txt']
});
// result.exitCode will be 1 or 2
// result.stderr will contain the error message
```
## Best Practices
1. **Use specific commands** instead of shell scripts
2. **Set appropriate timeouts** for long-running commands
3. **Check exit codes** to handle command failures
4. **Limit output size** by using head/tail when appropriate
5. **Avoid user input** in command arguments without validation
6. **Use working directory** instead of cd commands
7. **Monitor stderr** for warnings and errors
## Limitations
- No shell features (pipes, redirects, wildcards)
- No interactive commands
- No sudo or privileged operations
- Output limited to 1MB per stream
- Maximum timeout of 5 minutes