# create_session MCP Tool API Documentation
## Overview
The `create_session` MCP tool creates secure development sessions tied to specific codebases with comprehensive filesystem boundaries, Git integration, and encrypted state storage. This tool is the foundation for establishing isolated environments where agents can safely operate within defined security contexts.
## Tool Signature
```python
async def create_session(
root_path: str,
session_name: str,
security_level: str = "HIGH",
ctx: Optional[Context] = None
) -> Dict[str, Any]
```
## Parameters
### Required Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `root_path` | `str` | Absolute path to the codebase root directory. Must exist and be accessible. |
| `session_name` | `str` | Human-readable session name. Must be unique across all sessions. Length limited to 100 characters. |
### Optional Parameters
| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `security_level` | `str` | `"HIGH"` | Security enforcement level. Valid values: `"LOW"`, `"MEDIUM"`, `"HIGH"`, `"MAXIMUM"` |
| `ctx` | `Optional[Context]` | `None` | FastMCP context for progress reporting and logging |
## Security Levels
The security level determines the enforcement strictness for the session:
### HIGH (Default)
- **Filesystem Boundaries**: Strict path validation with chroot-like isolation
- **Process Limits**: Standard resource limits (100MB files, 10K total files)
- **Network Access**: Disabled by default
- **Shell Access**: Restricted to allowed executables only
- **Audit Level**: Comprehensive logging with integrity protection
### MEDIUM
- **Filesystem Boundaries**: Standard validation with session root restrictions
- **Process Limits**: Relaxed limits (200MB files, 20K total files)
- **Network Access**: Limited access for development tools
- **Shell Access**: Basic executable whitelist
- **Audit Level**: Standard logging
### LOW
- **Filesystem Boundaries**: Basic validation
- **Process Limits**: Minimal restrictions
- **Network Access**: Standard development access
- **Shell Access**: Extended executable access
- **Audit Level**: Basic logging
### MAXIMUM
- **Filesystem Boundaries**: Paranoid validation with maximum isolation
- **Process Limits**: Very strict limits (50MB files, 5K total files)
- **Network Access**: Completely disabled
- **Shell Access**: Minimal whitelist (claude, python, git only)
- **Audit Level**: Maximum logging with cryptographic integrity
## Return Value
The tool returns a comprehensive dictionary with session creation details:
### Success Response
```json
{
"success": true,
"session_id": "ses_1234567890abcdef",
"session_name": "my_project_session",
"root_path": "/absolute/path/to/project",
"git_integrated": true,
"task_monitoring_enabled": true,
"security_fingerprint": "sha256:abcd1234...",
"security_level": "HIGH",
"max_agents": 8,
"execution_duration_ms": 2547.3,
"warnings": [],
"message": "Session 'my_project_session' created successfully"
}
```
### Success Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `success` | `bool` | Always `true` for successful operations |
| `session_id` | `str` | Unique session identifier in format `ses_<uuid>` |
| `session_name` | `str` | Sanitized session name |
| `root_path` | `str` | Resolved absolute path to session root |
| `git_integrated` | `bool` | Whether Git repository was detected and integrated |
| `task_monitoring_enabled` | `bool` | Whether task file monitoring is active |
| `security_fingerprint` | `str` | Cryptographic fingerprint of security context |
| `security_level` | `str` | Applied security level |
| `max_agents` | `int` | Maximum number of agents allowed in this session |
| `execution_duration_ms` | `float` | Tool execution time in milliseconds |
| `warnings` | `List[str]` | Non-fatal warnings encountered during creation |
| `message` | `str` | Human-readable success message |
### Error Response
```json
{
"success": false,
"error": "Root path does not exist: /invalid/path",
"error_type": "PATH_NOT_FOUND"
}
```
### Error Response Fields
| Field | Type | Description |
|-------|------|-------------|
| `success` | `bool` | Always `false` for failed operations |
| `error` | `str` | Human-readable error message |
| `error_type` | `str` | Categorized error type for programmatic handling |
## Error Types
### Validation Errors (`VALIDATION_ERROR`)
- Empty or invalid session names
- Invalid security level values
- Malformed root paths
### Path Errors
- `PATH_NOT_FOUND`: Root path does not exist
- `INVALID_PATH`: Root path is not a directory or not accessible
### Capacity Errors (`CAPACITY_ERROR`)
- `DUPLICATE_SESSION`: Session name already exists
- Maximum session limit reached
### Internal Errors
- `SESSION_CREATION_ERROR`: SessionManager returned failure
- `INTERNAL_ERROR`: Session creation process failed
- `UNEXPECTED_ERROR`: Unhandled exception occurred
## Usage Examples
### Basic Session Creation
```python
# Create a basic session with default security
result = await tools.create_session(
root_path="/Users/developer/my_project",
session_name="main_development"
)
if result["success"]:
print(f"Session created: {result['session_id']}")
print(f"Git integrated: {result['git_integrated']}")
else:
print(f"Failed: {result['error']}")
```
### High-Security Session
```python
# Create a maximum security session for sensitive work
result = await tools.create_session(
root_path="/Users/developer/secure_project",
session_name="security_audit",
security_level="MAXIMUM"
)
```
### Session with Progress Monitoring
```python
# Use FastMCP context for progress tracking
async def create_monitored_session(ctx: Context):
result = await tools.create_session(
root_path="/Users/developer/large_project",
session_name="monitored_session",
security_level="HIGH",
ctx=ctx
)
return result
```
### Error Handling
```python
try:
result = await tools.create_session(
root_path="/invalid/path",
session_name="test_session"
)
if not result["success"]:
error_type = result["error_type"]
if error_type == "PATH_NOT_FOUND":
print("Please verify the project path exists")
elif error_type == "DUPLICATE_SESSION":
print("Session name already in use")
elif error_type == "CAPACITY_ERROR":
print("Maximum sessions reached")
else:
print(f"Unexpected error: {result['error']}")
except Exception as e:
print(f"Tool invocation failed: {e}")
```
## Session Features
### Git Integration
When a Git repository is detected in the root path:
- **Automatic Analysis**: Repository structure and metadata analyzed
- **Branch Tracking**: Current branch and commit information captured
- **Change Detection**: Uncommitted changes identified for safety
- **Project Context**: Repository context available to all session agents
### Task File Monitoring
Automatic monitoring of development workflow files:
- **TODO.md**: Project task management dashboard
- **TASK_*.md**: Individual task specifications
- **Real-time Updates**: File modification detection
- **Agent Integration**: Task assignments tracked per agent
### Security Boundaries
Comprehensive security enforcement:
- **Filesystem Isolation**: All agent operations confined to session root
- **Path Validation**: Prevention of directory traversal attacks
- **Resource Limits**: Configurable limits on file sizes and counts
- **Process Control**: Restricted executable access
- **Audit Logging**: Complete operation tracking
### State Persistence
Encrypted session state storage:
- **Session Configuration**: Security settings and boundaries
- **Agent Registry**: All agents belonging to the session
- **Resource Tracking**: Current resource usage and allocations
- **Recovery Support**: State restoration after system restarts
## Performance Considerations
### Execution Time
- **Target**: < 5 seconds for typical session creation
- **Factors**: Git repository size, filesystem scan time, security validation
- **Optimization**: Efficient path validation and parallel Git analysis
### Resource Usage
- **Memory**: Minimal overhead for session metadata (~1-5MB)
- **Disk**: Session state storage (~100KB-1MB depending on complexity)
- **CPU**: Brief spike during Git analysis and security setup
### Scalability
- **Session Limit**: Configurable maximum (default: 10 concurrent sessions)
- **Agent Limit**: 8 agents per session (configurable)
- **Monitoring**: Real-time resource tracking and health checks
## Integration Points
### SessionManager Integration
The tool delegates to `SessionManager.create_session()` for:
- Session state creation and persistence
- Git repository analysis and integration
- Security context establishment
- Task file monitoring setup
### Security Framework Integration
Integrates with the comprehensive security system:
- Input sanitization and validation
- Security contract enforcement
- Audit logging and monitoring
- Boundary enforcement
### FastMCP Integration
Full FastMCP framework integration:
- Automatic schema generation
- Progress reporting support
- Error handling standardization
- Tool registration and discovery
## Best Practices
### Session Naming
- Use descriptive, project-specific names
- Avoid special characters and spaces
- Keep names under 50 characters for readability
- Consider including project version or branch information
### Security Level Selection
- **HIGH**: Default for most development work
- **MAXIMUM**: For security-sensitive projects
- **MEDIUM**: For legacy projects with broader access needs
- **LOW**: Only for trusted environments with minimal restrictions
### Path Management
- Always use absolute paths for `root_path`
- Ensure the path exists and is accessible before creation
- Verify sufficient disk space for session operations
- Consider Git repository size for performance
### Error Recovery
- Implement retry logic for temporary failures
- Check error types for appropriate user messaging
- Log failures for debugging and monitoring
- Provide clear guidance for error resolution
## Security Considerations
### Input Validation
- All inputs undergo comprehensive sanitization
- Path validation prevents directory traversal
- Session names filtered for injection attacks
- Security levels validated against allowed values
### Access Control
- Session creation requires appropriate permissions
- All operations logged with security context
- Resource limits enforced per security level
- Audit trail maintained for compliance
### Data Protection
- Session state encrypted at rest
- Secure deletion of sensitive information
- Git credentials and tokens protected
- Network access controlled per security level
## Troubleshooting
### Common Issues
#### "Root path does not exist"
```bash
# Verify path exists
ls -la /your/project/path
# Check permissions
stat /your/project/path
```
#### "Session name already exists"
```python
# List existing sessions
status = await tools.get_session_status()
for session in status["sessions"]:
print(f"Existing: {session['session_name']}")
```
#### "Maximum session limit reached"
```python
# Check current session count
status = await tools.get_session_status()
print(f"Sessions: {status['global_metrics']['total_sessions']}")
# Delete unused sessions
await tools.delete_session("unused_session_id")
```
### Performance Issues
#### Slow Git Integration
- Large repositories may take longer to analyze
- Consider using `.gitignore` to exclude large binary files
- Monitor execution time with progress reporting
#### High Memory Usage
- Reduce security level if appropriate
- Check for large files in project directory
- Monitor resource usage with session status tools
## Related Tools
### Session Management
- [`get_session_status`](./get_session_status.md) - Monitor session health and metrics
- [`delete_session`](./delete_session.md) - Remove sessions with cleanup
### Agent Management
- [`create_agent`](./create_agent.md) - Create agents within sessions
- [`delete_agent`](./delete_agent.md) - Remove agents from sessions
- [`send_message_to_agent`](./send_message_to_agent.md) - Communicate with agents
### Monitoring
- [`clear_agent_conversation`](./clear_agent_conversation.md) - Reset agent conversations
- [`start_new_agent_conversation`](./start_new_agent_conversation.md) - Begin fresh conversations
## Version History
| Version | Date | Changes |
|---------|------|---------|
| 1.0.0 | 2025-06-26 | Initial implementation with full ADDER+ integration |
## Support
For issues, feature requests, or questions about the `create_session` tool:
1. Check the troubleshooting section above
2. Review the integration test suite in `tests/interfaces/test_create_session.py`
3. Consult the security framework documentation
4. Report issues through the project's issue tracking system
---
**Note**: This tool is part of the Agent Orchestration Platform's comprehensive MCP toolkit. All operations are logged and monitored for security and compliance purposes.