๐ Persistent Terminal MCP Server
A powerful Model Context Protocol (MCP) server that enables persistent terminal session management, implemented in TypeScript and leveraging the node-pty library. Terminal commands continue to run even when the client disconnects, making it ideal for long - running tasks executed by AI assistants such as Claude, Cursor, and Cline.
YouTube video: https://youtu.be/nfLi1IZxhJs
Bilibili video: https://www.bilibili.com/video/BV14ksPzqEbM/
Video tutorial for configuring MCP on Windows: https://youtu.be/WYEKwTQCAnc
โจ Features
๐ฅ Persistent Terminal Sessions
- Long - running: Create, reuse, and manage long - running Shell sessions.
- Disconnection recovery: The terminal continues to run after the client disconnects, and operations can resume upon reconnection.
- Multi - session management: Manage multiple independent terminal sessions simultaneously.
- Automatic cleanup: Sessions that time out are automatically cleaned up to prevent resource leaks.
๐ง Intelligent Output Management
- Circular buffer: Configurable size (default 10,000 lines) for automatic memory management.
- Multiple read modes:
full: Complete output.
head: Read only the first N lines.
tail: Read only the last N lines.
head - tail: Read both the beginning and the end.
- Incremental reading: Use the
since parameter to read only new content.
- Token estimation: Automatically estimate the number of tokens in the output for easy AI context control.
๐จ Spinner Animation Compression
- Automatic detection: Identify common progress animation characters (such as โ โ โ นโ ธโ ผโ ดโ ฆโ งโ โ , โโโโ, etc.).
- Intelligent throttling: Reduce noisy output from commands like
npm install, yarn, and pnpm.
- Retain key information: Compress animations while retaining real logs.
- Flexible configuration: Control the on/off state via environment variables or parameters.
๐ Web Visual Management Interface
- Real - time terminal: Terminal rendering based on xterm.js, supporting full ANSI colors.
- WebSocket push: Terminal output is displayed in real - time without refreshing.
- Interactive operations: Send commands and view output directly in the browser.
- Multi - instance support: Automatic port allocation, supporting multiple AI clients simultaneously.
- VS Code style: Dark theme with a simple and elegant interface design.
๐ค Codex Automatic Bug Fixing
- Fully automated: Integrate the OpenAI Codex CLI to automatically fix code bugs.
- Document - driven: AI descriptions are saved as MD documents, and Codex reads and fixes them.
- Detailed report: Generate a complete fix report, including before - and - after comparisons.
- Intelligent waiting: Automatically detect the completion of Codex execution, with a default timeout of 10 minutes.
- History record: All bug descriptions and fix reports are permanently saved in the
docs/ directory.
๐ Multiple Integration Methods
- MCP protocol: Natively support clients such as Claude Desktop, Claude Code, Cursor, and Cline.
- REST API: Provide HTTP interfaces for easy integration in non - MCP scenarios.
- Strict compatibility: Fully comply with the MCP stdio protocol specification, with pure and pollution - free stdout.
๐ก๏ธ Stability Assurance
- Output stability detection: The
wait_for_output tool ensures complete output retrieval.
- Interactive application support: Perfectly support interactive programs such as vim and
npm create.
- ANSI escape sequence handling: Correctly handle terminal control characters.
- Error recovery: Automatic reconnection and exception handling mechanisms.
๐ Quick Start
โ
Quick Run (Recommended)
No installation required. Start directly using npx:
npx persistent-terminal-mcp
The REST version is also supported:
npx persistent-terminal-mcp-rest
๐ฆ Integrate into an Existing Project
npm install persistent-terminal-mcp
After installation, all core classes and types can be imported in the code:
import { PersistentTerminalMcpServer } from "persistent-terminal-mcp";
๐ Global Installation (Optional)
npm install --global persistent-terminal-mcp
persistent-terminal-mcp
๐งช Local Development
Suitable for scenarios where you want to modify the source code or conduct in - depth debugging:
npm install
npm run build
npm start
During development, you can also run the TypeScript source code directly:
npm run dev
npm run dev:rest
๐ Debug Mode
Enable debug logs (output to stderr, without interfering with MCP communication):
MCP_DEBUG=true persistent-terminal-mcp
๐ Example Scripts
npm run example:basic
npm run example:smart
npm run example:spinner
npm run example:webui
npm run test:tools
npm run test:fixes
โ๏ธ MCP Client Configuration
Claude Desktop
macOS / Linux
Configuration file location: ~/Library/Application Support/Claude/claude_desktop_config.json
Add the following content to the configuration file:
{
"mcpServers": {
"persistent-terminal": {
"command": "npx",
"args": ["-y", "persistent-terminal-mcp"],
"env": {
"MAX_BUFFER_SIZE": "10000",
"SESSION_TIMEOUT": "86400000",
"COMPACT_ANIMATIONS": "true",
"ANIMATION_THROTTLE_MS": "100"
}
}
}
}
Note:
- The
-y parameter automatically confirms the npx download prompt.
- If globally installed (
npm install -g persistent-terminal-mcp), change command to "persistent-terminal-mcp" and remove -y from args.
Windows
Configuration file location: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"persistent-terminal": {
"command": "cmd",
"args": ["/c", "npx", "-y", "persistent-terminal-mcp"],
"env": {
"MAX_BUFFER_SIZE": "10000",
"SESSION_TIMEOUT": "86400000",
"COMPACT_ANIMATIONS": "true",
"ANIMATION_THROTTLE_MS": "100"
}
}
}
}
Note:
- Windows requires
cmd /c to call npx.
- If globally installed, change
args to ["/c", "persistent-terminal-mcp"].
Claude Code
macOS / Linux
Use the command line to add quickly:
claude mcp add persistent-terminal \
--env MAX_BUFFER_SIZE=10000 \
--env SESSION_TIMEOUT=86400000 \
--env COMPACT_ANIMATIONS=true \
--env ANIMATION_THROTTLE_MS=100 \
-- npx -y persistent-terminal-mcp
Or edit the configuration file ~/.claude.json:
{
"mcpServers": {
"persistent-terminal": {
"command": "npx",
"args": ["-y", "persistent-terminal-mcp"],
"env": {
"MAX_BUFFER_SIZE": "10000",
"SESSION_TIMEOUT": "86400000",
"COMPACT_ANIMATIONS": "true",
"ANIMATION_THROTTLE_MS": "100"
}
}
}
}
Windows
โ ๏ธ Important Note for Windows Users
The claude mcp add command in Claude Code on Windows has parameter parsing issues.
๐ซ Not recommended to use the command - line method
Please refer to the dedicated configuration document:
๐ ใConfiguring persistent - terminal MCP on Windowsใ
This document provides two recommended solutions:
- โ
Project - level configuration (recommended): Create a
.mcp.json file in the project root directory.
- โ
Global configuration: Use a Python script to modify
~/.claude.json
Cursor / Cline
The configuration method is similar to that of Claude Desktop. Please refer to the MCP configuration documentation of each client.
Codex
macOS / Linux
Add the following configuration to the .codex/config.toml file:
[mcp_servers.persistent-terminal]
command = "npx"
args = ["-y", "persistent-terminal-mcp"]
[mcp_servers.persistent-terminal.env]
MAX_BUFFER_SIZE = "10000"
SESSION_TIMEOUT = "86400000"
COMPACT_ANIMATIONS = "true"
ANIMATION_THROTTLE_MS = "100"
Windows
Add the following configuration to the .codex/config.toml file:
[mcp_servers.persistent-terminal]
command = "cmd"
args = ["/c", "npx", "-y", "persistent-terminal-mcp"]
[mcp_servers.persistent-terminal.env]
MAX_BUFFER_SIZE = "10000"
SESSION_TIMEOUT = "86400000"
COMPACT_ANIMATIONS = "true"
ANIMATION_THROTTLE_MS = "100"
Note: Windows requires cmd /c to call npx.
Environment Variable Explanation
| Property |
Details |
Default Value |
MAX_BUFFER_SIZE |
Maximum number of buffer lines |
10000 |
SESSION_TIMEOUT |
Session timeout in milliseconds |
86400000 (24 hours) |
COMPACT_ANIMATIONS |
Whether to enable Spinner compression |
true |
ANIMATION_THROTTLE_MS |
Animation throttling time in milliseconds |
100 |
MCP_DEBUG |
Whether to enable debug logs |
false |
AUTO_START_REST_SERVER |
Automatically start the REST server when MCP starts |
false |
REST_HOST |
REST server listening address |
localhost |
REST_PORT |
REST server port |
3001 |
AUTO_START_TERMINAL_UI |
Automatically start the Web UI when REST starts |
true |
WEB_UI_HOST |
Web UI server listening address |
localhost |
AUTO_OPEN_BROWSER |
Whether to automatically open the browser to access the Web UI |
false |
WEB_UI_PORT |
Web UI server port |
3000 |
๐ Automatic Server Startup Configuration
Server automatic startup and network access configuration can be achieved through environment variables:
External Access Configuration
To enable external network access for the REST API and Web UI, set the following environment variables:
AUTO_START_REST_SERVER=true
REST_HOST=0.0.0.0
AUTO_START_TERMINAL_UI=true
WEB_UI_HOST=0.0.0.0
REST_PORT=3001
WEB_UI_PORT=3000
AUTO_OPEN_BROWSER=false
Expected Results
After setting the above environment variables, when starting the MCP server:
- โ
The REST API server automatically starts at
http://0.0.0.0:3001.
- โ
The Web UI automatically starts at
http://0.0.0.0:3000.
- โ
Both services can be accessed from the external network.
- โ
You can choose whether to automatically open the browser.
Client Configuration Example
Add environment variables to the MCP client configuration:
Claude Desktop Configuration:
{
"mcpServers": {
"persistent-terminal": {
"command": "npx",
"args": ["-y", "persistent-terminal-mcp"],
"env": {
"AUTO_START_REST_SERVER": "true",
"REST_HOST": "0.0.0.0",
"AUTO_START_TERMINAL_UI": "true",
"WEB_UI_HOST": "0.0.0.0",
"WEB_UI_PORT": "3000",
"AUTO_OPEN_BROWSER": "false",
"MAX_BUFFER_SIZE": "10000",
"SESSION_TIMEOUT": "86400000"
}
}
}
}
Claude Code Configuration:
claude mcp add persistent-terminal \
--env AUTO_START_REST_SERVER=true \
--env REST_HOST=0.0.0.0 \
--env AUTO_START_TERMINAL_UI=true \
--env WEB_UI_HOST=0.0.0.0 \
--env WEB_UI_PORT=3000 \
--env AUTO_OPEN_BROWSER=false \
-- npx -y persistent-terminal-mcp
๐งฑ Programmatic Use in TypeScript
import {
PersistentTerminalMcpServer,
TerminalManager,
RestApiServer,
} from "persistent-terminal-mcp";
const manager = new TerminalManager();
const rest = new RestApiServer(manager);
await rest.start(3001);
const mcpServer = new PersistentTerminalMcpServer();
const server = mcpServer.getServer();
await server.connect();
All core classes and types can be obtained from the root entry of the package. For details, refer to src/index.ts.
๐ ๏ธ MCP Tools Overview
| Tool |
Function |
Main Parameters |
create_terminal |
Create a persistent terminal session |
shell, cwd, env, cols, rows |
create_terminal_basic |
Simplified creation entry |
shell, cwd |
write_terminal |
Write commands to the terminal |
terminalId, input, appendNewline |
read_terminal |
Read buffered output |
terminalId, mode, since, stripSpinner |
wait_for_output |
Wait for output to stabilize |
terminalId, timeout, stableTime |
get_terminal_stats |
View statistical information |
terminalId |
list_terminals |
List all active terminals |
None |
kill_terminal |
Terminate a session |
terminalId, signal |
open_terminal_ui |
Open the Web management interface |
port, autoOpen |
fix_bug_with_codex ๐ |
Automatically fix bugs using Codex |
description, cwd, timeout |
Detailed Tool Explanation
create_terminal - Create a Terminal
Create a new persistent terminal session.
Parameters:
shell (optional): Shell type, such as /bin/bash or /bin/zsh.
cwd (optional): Working directory.
env (optional): Environment variable object.
cols (optional): Number of terminal columns, default 80.
rows (optional): Number of terminal rows, default 24.
Returns:
terminalId: Terminal ID.
status: Status.
pid: Process ID.
shell: Shell type.
cwd: Working directory.
write_terminal - Write Commands
Send commands or input to the terminal.
Parameters:
terminalId: Terminal ID.
input: Content to send.
appendNewline (optional): Whether to automatically append a newline, default true.
Tip: By default, a newline is automatically appended to execute commands. To send raw control characters (such as arrow keys), set appendNewline: false.
read_terminal - Read Output
Read the buffered output of the terminal, supporting multiple intelligent truncation modes.
Parameters:
terminalId: Terminal ID.
mode (optional): Read mode.
full: Complete output (default).
head: Read only the beginning.
tail: Read only the end.
head - tail: Read both the beginning and the end.
since (optional): Start reading from the Nth line (incremental reading).
maxLines (optional): Maximum number of lines, default 1000.
headLines (optional): Number of lines in head mode, default 50.
tailLines (optional): Number of lines in tail mode, default 50.
stripSpinner (optional): Whether to compress Spinner animations.
Returns:
output: Output content.
totalLines: Total number of lines.
lineRange: Actual returned line range.
estimatedTokens: Estimated number of tokens.
truncated: Whether truncated.
spinnerCompacted: Whether Spinner compression was performed.
wait_for_output - Wait for Output to Stabilize
Wait for the terminal output to stabilize before reading to ensure complete output retrieval.
Parameters:
terminalId: Terminal ID.
timeout (optional): Maximum waiting time in milliseconds, default 5000.
stableTime (optional): Stable time in milliseconds, default 500.
Use Cases:
- Ensure complete output retrieval after command execution.
- Wait for the startup of an interactive application to complete.
fix_bug_with_codex ๐ - Automatic Bug Fixing
Use the OpenAI Codex CLI to automatically analyze and fix bugs in the code.
Parameters:
description (required): Detailed bug description, must include:
- Problem symptoms (specific error behavior).
- Expected behavior (how it should work).
- Problem location (file path, line number, function name).
- Related code (problematic code snippet).
- Root cause (why the problem occurred).
- Fix suggestion (how to fix).
- Impact scope (what else is affected).
- Related files (all relevant file paths).
- Test cases (how to verify the fix).
- Context information (background information to help understand the problem).
cwd (optional): Working directory, default is the current directory.
timeout (optional): Timeout in milliseconds, default 600000 (10 minutes).
Returns:
terminalId: Terminal ID for executing Codex.
reportPath: Path to the fix report.
reportExists: Whether the report exists.
workingDir: Working directory.
executionTime: Execution time in seconds.
timedOut: Whether timed out.
output: Terminal output.
reportPreview: Report preview.
Workflow:
- The AI provides a detailed bug description.
- The tool saves the description to
docs/codex-bug-description-TIMESTAMP.md.
- Codex reads the document and analyzes the problem.
- Codex fixes the bug and generates a report
docs/codex-fix-TIMESTAMP.md.
- The AI reads the report and summarizes it for the user.
Important Notes:
- โ ๏ธ This tool has full system access (
danger - full - access).
- โ ๏ธ Codex can modify any file. It is recommended to use it in a Git repository.
- โ
Use only English descriptions (to avoid UTF - 8 encoding issues).
- โ
The more detailed the description, the higher the quality of the fix.
Example:
fix_bug_with_codex({
description: `Username validation bug in auth.js file.
PROBLEM:
- File: src/auth/login.ts, line 45
- Code: const usernameRegex = /^[a-zA-Z0-9]{3,20}$/
- Symptom: Username 'user_name' is rejected with 'Invalid username' error
- Expected: Should accept usernames with underscores and hyphens
ROOT CAUSE:
- Regex [a-zA-Z0-9] only allows letters and numbers
- Missing support for underscore and hyphen characters
SUGGESTED FIX:
- Change regex to: /^[a-zA-Z0-9_-]{3,20}$/
VERIFICATION:
- Run: npm test
- Expected: all tests pass`,
cwd: "/path/to/project",
timeout: 600000,
});
Detailed Documentation:
- Codex Bug Fix Tool Feature Documentation
- Codex Bug Fix Tool Test Report
๐ก Usage Tip: The Codex CLI requires OpenAI API access. If you are in China or encounter access issues, consider using the Codex CLI Mirror Service (ยฅ99/month, with a daily quota of $90) to make AI programming smoother.
open_terminal_ui - Open the Web Management Interface
Start a browser - based visual terminal management interface.
Parameters:
port (optional): Port number, default is to automatically find starting from 3002.
autoOpen (optional): Whether to automatically open the browser, default true.
Returns:
url: Web UI address.
port: Actual port used.
mode: Startup mode (new/existing).
autoOpened: Whether the browser was automatically opened.
fix_bug_with_codex ๐ - Automatic Bug Fixing
Call the OpenAI Codex CLI to automatically analyze and fix bugs in the code and generate a detailed fix report.
โ ๏ธ Important Note:
- This tool uses the full - permission mode (
--sandbox danger - full - access --ask - for - approval never).
- Codex can fully control the codebase. Use it with caution.
- It is recommended to back up the code or use version control before use.
Parameters:
description (required): Detailed bug description, must include:
- Problem symptoms (specific error behavior).
- Expected behavior (how it should work).
- Problem location (file path, line number).
- Related code snippet.
- Root cause (if known).
- Fix suggestion (if any).
- Impact scope (functions that may be affected).
- Related files (all relevant file paths).
- Test cases (how to verify the fix).
- Context information (background information).
cwd (optional): Working directory, default is the current directory.
timeout (optional): Timeout in milliseconds, default 600000 (10 minutes).
Returns:
terminalId: Terminal ID for executing Codex.
reportPath: Path to the fix report (docs/codex - fix - TIMESTAMP.md).
reportExists: Whether the report was successfully generated.
executionTime: Execution time.
output: Terminal output of Codex.
Workflow:
- The AI assistant collects detailed bug information.
- Call this tool, passing in the detailed description.
- Codex analyzes the problem and fixes the code.
- Codex generates a detailed report in the
docs/ directory.
- The AI assistant reads the report and reports the results to the user.
Report Content:
- Problem description.
- List of modified files.
- Specific modifications for each file (before - and - after comparison).
- Explanation of modification reasons.
- Test suggestions.
- Precautions.
Usage Example:
User: There is a bug in the login function, and username validation always fails.
AI Assistant:
1. [Check relevant files to understand the problem]
2. [Call fix_bug_with_codex]
{
"description": "There is a bug in the username validation of the login function. Specific details:
1. Problem symptoms: The username 'user_name' is always rejected.
2. Expected behavior: Usernames containing underscores should be accepted.
3. Problem location: Line 45 of src/auth/login.ts.
4. Related code: const usernameRegex = /^[a-zA-Z0-9]{3,20}$/
5. Root cause: The regular expression does not allow underscores.
..."
}
3. [Wait for Codex to complete]
4. [Read the report] view("docs/codex - fix - 2025 - 10 - 18T00 - 35 - 12.md")
5. [Report the fix results to the user]
Prerequisites:
- Codex CLI is installed:
npm install -g @openai/codex-cli.
- Codex authentication is configured.
- The
docs/ directory exists in the project.
Best Practices:
- Provide as detailed a bug description as possible (the more detailed the description, the higher the quality of the fix).
- Check relevant files and understand the problem before calling.
- Always run tests to verify after fixing.
- Check the generated report to understand specific modifications.
- Use version control for easy rollback.
๐ Web Management Interface
Features
- ๐ Terminal List: View the status, PID, Shell, working directory, and other information of all terminals.
- ๐ฅ๏ธ Real - time Terminal: Render terminal output using xterm.js, supporting ANSI colors.
- โก Real - time Update: WebSocket push, terminal output is displayed in real - time.
- โจ๏ธ Interactive Operations: Send commands directly in the browser.
- ๐จ VS Code Style: Dark theme with a simple and elegant design.
- ๐ Automatic Port: Supports multiple instances, automatically avoiding port conflicts.
Quick Use
In Claude or other MCP clients, say:
Please open the terminal management interface
Or run the test script directly:
npm run test:webui
Detailed usage instructions can be found in Web UI Usage Guide.
๐ REST API (Optional)
If an HTTP interface is required, start the REST version:
npx persistent-terminal-mcp-rest
The server listens on port 3001 by default (configurable). The endpoints correspond one - to - one with MCP tools:
| Endpoint |
Method |
Description |
/api/terminals |
POST |
Create a terminal |
/api/terminals |
GET |
List all terminals |
/api/terminals/:id |
GET |
Get terminal details |
/api/terminals/:id |
DELETE |
Terminate a terminal |
/api/terminals/:id/input |
POST |
Send a command |
/api/terminals/:id/output |
GET |
Read output |
/api/terminals/:id/stats |
GET |
Get statistical information |
๐ Project Structure
persistent-terminal-mcp/
โโโ src/ # TypeScript source code
โ โโโ index.ts # MCP server entry
โ โโโ mcp-server.ts # MCP server implementation
โ โโโ terminal-manager.ts # Terminal manager
โ โโโ output-buffer.ts # Output buffer
โ โโโ web-ui-manager.ts # Web UI manager
โ โโโ web-ui-server.ts # Web UI server
โ โโโ rest-server.ts # REST API server
โ โโโ types.ts # Type definitions
โ โโโ __tests__/ # Unit tests
โ โโโ examples/ # Example scripts
โโโ dist/ # Compiled JavaScript
โโโ public/ # Web UI static files
โโโ docs/ # Documentation
โ โโโ guides/ # Usage guides
โ โโโ reference/ # Technical references
โ โโโ clients/ # Client configurations
โ โโโ zh/ # Chinese documentation
โโโ tests/ # Test suites
โ โโโ integration/ # Integration tests
โโโ scripts/ # Auxiliary scripts
๐ Documentation Navigation
Quick Access
- ๐ Full Documentation Index
- ๐จ Fix Documentation Index
- ๐งช Integration Test Instructions
- ๐ Web UI Usage Guide
By Category
- Usage Guides: Usage Instructions | Troubleshooting | MCP Configuration
- Technical References: Technical Details | Tool Summary
- Fix Documentation: Stdio Fix | Cursor Fix | Terminal Fixes
- Client Configurations: Claude Desktop/Code
๐ Important Notes
Stdio Purity
This MCP server strictly adheres to the MCP protocol, ensuring that stdout only contains JSON - RPC messages, and all logs are output to stderr. This guarantees full compatibility with strict clients such as Cursor. See Stdio Fix Documentation for details.
Cursor Compatibility
Fully compatible with Cursor and other MCP clients that require strict JSON - RPC communication. See Quick Fix Guide for quick setup.
Terminal Interaction
Supports interactive applications (such as vim and npm create) and correctly handles ANSI escape sequences. See Terminal Fix Documentation for details.
Output Stability
Use the wait_for_output tool to ensure complete output retrieval after command execution, avoiding incomplete data reading.
๐งช Testing
Run Tests
npm test
npm run test:integration
npm run test:all
Integration Tests
npm run test:integration:stdio
npm run test:integration:cursor
npm run test:integration:terminal
๐ค Contribution Guide
Welcome to submit Issues or PRs! See CONTRIBUTING.md for detailed processes and code specifications.
Contribution Steps
- Fork this repository.
- Create a feature branch (
git checkout -b feature/AmazingFeature).
- Commit changes (
git commit -m 'Add some AmazingFeature').
- Push to the branch (
git push origin feature/AmazingFeature).
- Open a Pull Request.
๐ License
This project is released under the MIT License.
๐ Acknowledgments
๐ Support
- ๐ Read the documentation.
- ๐ Submit an Issue.
- ๐ฌ Participate in discussions.
Last Updated: 2025-10-22
Version: 1.0.2