| Crates.io | kodegen_tools_terminal |
| lib.rs | kodegen_tools_terminal |
| version | 0.10.10 |
| created_at | 2025-11-03 17:26:31.198055+00 |
| updated_at | 2026-01-02 15:09:55.543161+00 |
| description | KODEGEN.แดษช: Memory-efficient, Blazing-Fast, MCP tools for code generation agents. |
| homepage | https://kodegen.ai |
| repository | https://github.com/cyrup-ai/kodegen-tools-terminal |
| max_upload_size | |
| id | 1915022 |
| size | 4,392,554 |
High-performance terminal management library and MCP (Model Context Protocol) server for code generation agents. Part of the KODEGEN.แดษช ecosystem.
Add to your Cargo.toml:
[dependencies]
kodegen_tools_terminal = "0.1"
Or run:
cargo add kodegen_tools_terminal
use kodegen_tools_terminal::{TerminalManager, CommandManager};
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Create terminal manager
let manager = Arc::new(TerminalManager::new());
// Start background cleanup task
manager.clone().start_cleanup_task();
// Execute a command
let result = manager.execute_command(
"echo 'Hello, World!'",
Some(100), // 100ms initial delay
None // default shell
).await?;
println!("PID: {}", result.pid);
println!("Output: {}", result.output);
// Get paginated output
if let Some(output) = manager.get_output(result.pid, 0, 100).await {
for line in output.lines {
println!("{}", line);
}
}
Ok(())
}
Run the HTTP/SSE server:
cargo run --bin kodegen-terminal
The server exposes 5 MCP tools for terminal management (see MCP Tools below).
start_terminal_commandExecute shell commands with full terminal emulation. Supports long-running commands, output streaming, and session management.
Primary use cases:
Arguments:
{
"command": "python3 -i",
"initial_delay_ms": 100, // Window for fast commands to complete (default: 100ms)
"shell": "/bin/bash" // optional
}
Returns (always returns PID + output + status):
{
"pid": 1000,
"output": "Python 3.x.x\n>>> ", // Captured during initial_delay_ms
"still_running": false, // true if command still executing
"ready_for_input": true
}
Return behavior:
still_running: falsestill_running: true โ use read_terminal_output(pid) to pollread_terminal_outputRead paginated output from a running session.
Arguments:
{
"pid": 1000,
"offset": 0, // negative for tail behavior
"length": 100 // max lines to return
}
Returns:
{
"pid": 1000,
"lines": ["line1", "line2", "..."],
"total_lines": 250,
"lines_returned": 100,
"is_complete": false,
"has_more": true
}
send_terminal_inputSend input to an interactive session.
Arguments:
{
"pid": 1000,
"input": "print('hello')",
"append_newline": true // default: true
}
stop_terminal_commandTerminate a running session.
Arguments:
{
"pid": 1000
}
list_terminal_commandsList all active terminal sessions.
Returns:
{
"sessions": [
{
"pid": 1000,
"still_running": false,
"runtime": 5420 // milliseconds
}
]
}
use kodegen_tools_terminal::TerminalManager;
use std::sync::Arc;
use tokio::time::{sleep, Duration};
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let manager = Arc::new(TerminalManager::new());
manager.clone().start_cleanup_task();
// Start Python REPL
let result = manager.execute_command("python3 -i", Some(500), None).await?;
let pid = result.pid;
// Send Python code
manager.send_input(pid, "x = 42", true).await?;
sleep(Duration::from_millis(100)).await;
manager.send_input(pid, "print(x * 2)", true).await?;
sleep(Duration::from_millis(100)).await;
// Read output
if let Some(output) = manager.get_output(pid, -20, 20).await {
for line in output.lines {
println!("{}", line);
}
}
// Cleanup
manager.force_terminate(pid).await?;
Ok(())
}
The terminal includes a comprehensive context-aware validation system that blocks dangerous operations while allowing safe commands. Validation happens automatically before command execution.
Terminal::execute_command()
โ
ValidationEngine::validate()
โ
[Rule Lookup]
โ
[Analyzers]
โ โ
FlagAnalyzer PathAnalyzer
โ
[ValidationDecision]
The validation engine comes with hardcoded security rules covering five categories:
Never allowed due to security risks:
sudo, su, doasreboot, shutdown, halt, poweroffPattern-based restrictions for data-modifying commands:
rm, rmdir (blocks -rf, -fr, system paths)dd, shred, wipemkfs.*, fdisk, partedAccess control modification:
chmod, chown, chgrpchattr, setfaclConfiguration changes:
iptables, ufw, firewall-cmdsystemctl, servicemount, umountSoftware installation:
apt, yum, dnf, pacmannpm, pip, gem, cargoValidation is automatic - no explicit calls needed:
use kodegen_tools_terminal::pty::terminal::Terminal;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
// Create terminal (ValidationEngine initialized automatically)
let terminal = Terminal::builder().build().await?;
// Safe commands are allowed
let result = terminal.execute_command(
request_id,
"ls -la".to_string(),
5000
).await?;
// Dangerous commands are blocked
let result = terminal.execute_command(
request_id,
"rm -rf /".to_string(),
5000
).await?;
// Returns error with educational message about using MCP tools
Ok(())
}
Add custom validation rules programmatically:
use kodegen_tools_terminal::validation::{ValidationEngine, CommandRule, ViolationType};
use std::borrow::Cow;
// Access the terminal's validation engine
let engine = &terminal.validation_engine;
// Add custom rule with builder pattern
let rule = CommandRule::builder("mycmd")
.default_allow(true)
.block_pattern(
Cow::Borrowed(r"--dangerous-flag"),
ViolationType::DangerousFlag,
"This flag is dangerous"
)
.restricted_path("/sensitive/data")
.build();
engine.add_rule(rule);
// Add always-blocked command
engine.add_rule(CommandRule::always_blocked("forbidden-cmd"));
Commands are either allowed or blocked:
use kodegen_tools_terminal::validation::{ValidationDecision, ViolationType};
match engine.validate("rm -rf /") {
ValidationDecision::Allow => {
// Command is safe to execute
}
ValidationDecision::Block { reason, violation_type } => {
// Command blocked with explanation
match violation_type {
ViolationType::AlwaysBlocked => { /* Never allowed */ }
ViolationType::DangerousFlag => { /* Dangerous flag detected */ }
ViolationType::RestrictedPath => { /* Restricted path access */ }
}
}
}
Some Unix commands are intercepted before validation to guide users toward MCP tools:
find โ Use fs_search tool (10-100x faster)grep โ Use fs_search tool with content searchmv โ Use fs_move_file toolchmod, chown โ Not needed (MCP tools handle permissions)ln โ Use fs_move_file or fs_write_filekill, killall, pkill โ Use process_kill toolThese intercepts provide friendly educational messages with examples.
This library uses pseudo-terminals (PTY) instead of standard pipes:
Automatic detection of REPL prompts:
>>> , ... $ , # > , node> In [N]: When detected, sets ready_for_input: true in response.
# Build
cargo build
# Run tests
cargo test
# Run example
cargo run --example terminal_demo
# Run MCP server
cargo run --bin kodegen-terminal
# Build release
cargo build --release
See examples/terminal_demo.rs for comprehensive usage examples including:
Core dependencies:
tokio - Async runtimeportable-pty - Cross-platform PTYvt100 - VT100 terminal emulatorrmcp - MCP SDKContributions welcome! Please ensure:
cargo testDual-licensed under Apache 2.0 OR MIT. See LICENSE.md for details.
KODEGEN.แดษช - Memory-efficient, Blazing-Fast, MCP tools for code generation agents.