persistent-terminal-mcp 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CHANGELOG.md +278 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +259 -0
  4. package/README.md +608 -0
  5. package/dist/examples/basic-usage.d.ts +3 -0
  6. package/dist/examples/basic-usage.d.ts.map +1 -0
  7. package/dist/examples/basic-usage.js +116 -0
  8. package/dist/examples/basic-usage.js.map +1 -0
  9. package/dist/examples/codex-bug-fix-demo.d.ts +3 -0
  10. package/dist/examples/codex-bug-fix-demo.d.ts.map +1 -0
  11. package/dist/examples/codex-bug-fix-demo.js +134 -0
  12. package/dist/examples/codex-bug-fix-demo.js.map +1 -0
  13. package/dist/examples/interactive-demo.d.ts +3 -0
  14. package/dist/examples/interactive-demo.d.ts.map +1 -0
  15. package/dist/examples/interactive-demo.js +235 -0
  16. package/dist/examples/interactive-demo.js.map +1 -0
  17. package/dist/examples/rest-api-demo.d.ts +7 -0
  18. package/dist/examples/rest-api-demo.d.ts.map +1 -0
  19. package/dist/examples/rest-api-demo.js +160 -0
  20. package/dist/examples/rest-api-demo.js.map +1 -0
  21. package/dist/examples/smart-reading-demo.d.ts +3 -0
  22. package/dist/examples/smart-reading-demo.d.ts.map +1 -0
  23. package/dist/examples/smart-reading-demo.js +153 -0
  24. package/dist/examples/smart-reading-demo.js.map +1 -0
  25. package/dist/examples/test-all-9-tools.d.ts +8 -0
  26. package/dist/examples/test-all-9-tools.d.ts.map +1 -0
  27. package/dist/examples/test-all-9-tools.js +162 -0
  28. package/dist/examples/test-all-9-tools.js.map +1 -0
  29. package/dist/examples/test-all-tools.d.ts +3 -0
  30. package/dist/examples/test-all-tools.d.ts.map +1 -0
  31. package/dist/examples/test-all-tools.js +150 -0
  32. package/dist/examples/test-all-tools.js.map +1 -0
  33. package/dist/examples/test-fixes.d.ts +9 -0
  34. package/dist/examples/test-fixes.d.ts.map +1 -0
  35. package/dist/examples/test-fixes.js +168 -0
  36. package/dist/examples/test-fixes.js.map +1 -0
  37. package/dist/examples/test-spinner-compaction.d.ts +8 -0
  38. package/dist/examples/test-spinner-compaction.d.ts.map +1 -0
  39. package/dist/examples/test-spinner-compaction.js +155 -0
  40. package/dist/examples/test-spinner-compaction.js.map +1 -0
  41. package/dist/examples/test-web-ui.d.ts +12 -0
  42. package/dist/examples/test-web-ui.d.ts.map +1 -0
  43. package/dist/examples/test-web-ui.js +90 -0
  44. package/dist/examples/test-web-ui.js.map +1 -0
  45. package/dist/index.d.ts +8 -0
  46. package/dist/index.d.ts.map +1 -0
  47. package/dist/index.js +81 -0
  48. package/dist/index.js.map +1 -0
  49. package/dist/mcp-server.d.ts +49 -0
  50. package/dist/mcp-server.d.ts.map +1 -0
  51. package/dist/mcp-server.js +1056 -0
  52. package/dist/mcp-server.js.map +1 -0
  53. package/dist/output-buffer.d.ts +134 -0
  54. package/dist/output-buffer.d.ts.map +1 -0
  55. package/dist/output-buffer.js +553 -0
  56. package/dist/output-buffer.js.map +1 -0
  57. package/dist/rest-api.d.ts +33 -0
  58. package/dist/rest-api.d.ts.map +1 -0
  59. package/dist/rest-api.js +325 -0
  60. package/dist/rest-api.js.map +1 -0
  61. package/dist/rest-server.d.ts +3 -0
  62. package/dist/rest-server.d.ts.map +1 -0
  63. package/dist/rest-server.js +72 -0
  64. package/dist/rest-server.js.map +1 -0
  65. package/dist/terminal-manager.d.ts +93 -0
  66. package/dist/terminal-manager.d.ts.map +1 -0
  67. package/dist/terminal-manager.js +702 -0
  68. package/dist/terminal-manager.js.map +1 -0
  69. package/dist/types.d.ts +201 -0
  70. package/dist/types.d.ts.map +1 -0
  71. package/dist/types.js +5 -0
  72. package/dist/types.js.map +1 -0
  73. package/dist/web-ui-manager.d.ts +38 -0
  74. package/dist/web-ui-manager.d.ts.map +1 -0
  75. package/dist/web-ui-manager.js +130 -0
  76. package/dist/web-ui-manager.js.map +1 -0
  77. package/dist/web-ui-server.d.ts +42 -0
  78. package/dist/web-ui-server.d.ts.map +1 -0
  79. package/dist/web-ui-server.js +324 -0
  80. package/dist/web-ui-server.js.map +1 -0
  81. package/package.json +129 -0
  82. package/public/app.js +265 -0
  83. package/public/index.html +63 -0
  84. package/public/styles.css +383 -0
  85. package/public/terminal.html +56 -0
  86. package/public/terminal.js +244 -0
  87. package/public/test.html +97 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,278 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [Unreleased]
9
+
10
+ - _Nothing yet._
11
+
12
+ ## [1.0.2] - 2025-10-18
13
+
14
+ ### Added
15
+ - **🌐 Web UI 管理界面**: 基于浏览器的可视化终端管理界面
16
+ - 使用 xterm.js 渲染终端输出,支持完整 ANSI 颜色
17
+ - WebSocket 实时推送,终端输出实时显示
18
+ - 直接在浏览器中发送命令、查看输出
19
+ - 自动端口分配,支持多实例运行
20
+ - VS Code 风格的暗色主题界面
21
+ - 新增 `open_terminal_ui` MCP 工具
22
+ - 新增 `WebUIManager` 和 `WebUIServer` 模块
23
+ - 新增 Web UI 静态文件(public/)
24
+ - 新增 Web UI 使用指南文档
25
+ - **📚 文档更新**: 全面更新中文 README,包含所有新功能说明
26
+
27
+ ### Changed
28
+ - 更新 README.zh-CN.md,采用更清晰的结构和更详细的功能说明
29
+ - 优化文档导航,添加更多 emoji 图标提升可读性
30
+ - npm 包装清理:新增二进制入口(`persistent-terminal-mcp`、`persistent-terminal-mcp-rest`),
31
+ 导出完整类型定义,限制发布文件为 `dist/` 与核心静态资源,并更新文档以推荐 `npx`
32
+ 启动方式
33
+
34
+ ### Fixed
35
+
36
+ #### 🔴 Critical: Terminal command execution and interaction issues
37
+ - **Problem 1: Commands not executing properly**
38
+ - Commands sent to terminal were not being executed
39
+ - No command echo visible in output
40
+ - Terminal line count increased but content was invisible
41
+ - **Problem 2: Interactive input handling unstable**
42
+ - Control characters (arrow keys, enter) not working reliably
43
+ - Interface not updating in interactive applications
44
+ - Required multiple key presses for single action
45
+ - **Problem 3: Output reading not real-time**
46
+ - Reading stale output instead of latest
47
+ - Required multiple reads to get current state
48
+ - No way to detect if command is still running
49
+ - **Solution**:
50
+ - Fixed PTY configuration: Changed from `xterm-color` to `xterm-256color`
51
+ - Added proper environment variables: `TERM`, `LANG`, `PAGER`
52
+ - Improved write logic with drain event handling
53
+ - Added `setImmediate` for immediate data processing
54
+ - Added `waitForOutputStable()` method to detect output completion
55
+ - Added `wait_for_output` MCP tool for waiting until output stabilizes
56
+ - **Impact**: Full support for interactive applications (vim, npm create, etc.)
57
+ - **Testing**: All 6 tests pass in `test-terminal-fixes.mjs`
58
+ - **Documentation**: See [TERMINAL_FIXES.md](TERMINAL_FIXES.md) for detailed analysis
59
+
60
+ #### 🔴 Critical: Stdio channel pollution causing Cursor compatibility issues
61
+ - **Problem**: Console logging was polluting stdout, causing JSON parsing errors in Cursor and other strict MCP clients
62
+ - Error: `Unexpected token 'T', "Terminal c"... is not valid JSON`
63
+ - Cursor would freeze after a few commands
64
+ - MCP protocol requires stdout to contain only JSON-RPC messages
65
+ - **Solution**: All logging now uses `process.stderr.write()` instead of `console.log/error`
66
+ - Debug logs controlled by `MCP_DEBUG` environment variable
67
+ - All logs output to stderr, keeping stdout pure for JSON-RPC
68
+ - **Impact**: Full compatibility with Cursor and other strict MCP clients
69
+ - **Backward Compatible**: Yes - no API changes, only logging behavior
70
+ - **Files Modified**:
71
+ - `src/index.ts` - Fixed log function and error handlers
72
+ - `src/mcp-server.ts` - Fixed event handlers and shutdown logging
73
+ - `src/terminal-manager.ts` - Fixed cleanup and shutdown logging
74
+ - **Testing**: Added comprehensive stdio purity tests
75
+ - `test-mcp-stdio.mjs` - Validates stdout contains only JSON-RPC
76
+ - `test-cursor-scenario.mjs` - Simulates real Cursor usage scenarios
77
+ - **Documentation**: See [STDIO_FIX.md](STDIO_FIX.md) for detailed analysis
78
+
79
+ ### Added
80
+ - **Spinner Animation Compaction**: Automatically detects and throttles progress animations
81
+ - Identifies common spinner characters (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏, ◐◓◑◒, etc.)
82
+ - Reduces noise from `npm install`, `yarn`, `pnpm` and similar commands
83
+ - Configurable via `COMPACT_ANIMATIONS` and `ANIMATION_THROTTLE_MS` environment variables
84
+ - Enabled by default with 100ms throttle
85
+ - Can be toggled per-read via `stripSpinner` parameter
86
+ - See [Spinner Compaction Guide](docs/guides/spinner-compaction.md) for details
87
+ - **`wait_for_output` MCP tool**: Wait for terminal output to stabilize before reading
88
+ - Parameters: `terminalId`, `timeout` (default: 5000ms), `stableTime` (default: 500ms)
89
+ - Useful for ensuring complete output capture after running commands
90
+ - Helps with interactive applications and long-running commands
91
+ - **`waitForOutputStable()` method**: Programmatic API for waiting for output stability
92
+ - **`isTerminalBusy()` method**: Check if terminal is currently processing output
93
+ - `create_terminal_basic` MCP tool to support clients that can only send simple
94
+ string arguments
95
+ - Open-source collateral: MIT `LICENSE` and `CONTRIBUTING.md`
96
+ - Comprehensive test suite for spinner detection (12 new tests)
97
+ - Comprehensive test suite for terminal fixes (6 new tests)
98
+ - Example script: `npm run example:spinner`
99
+ - Test script: `test-terminal-fixes.mjs`
100
+ - `MCP_DEBUG` environment variable for controlling debug output
101
+
102
+ ### Changed
103
+ - **PTY Configuration**: Changed terminal type from `xterm-color` to `xterm-256color`
104
+ - **Environment Variables**: Now sets `TERM`, `LANG`, and `PAGER` for better compatibility
105
+ - **Write Logic**: Improved with drain event handling and immediate processing
106
+ - **Read Logic**: Added `setImmediate` to ensure latest data is captured
107
+ - **Output Capture**: Using `setImmediate` in `onData` handler for immediate processing
108
+ - `OutputBuffer` constructor now accepts `compactAnimations` and `animationThrottleMs` options
109
+ - `TerminalManagerConfig` extended with animation compaction settings
110
+ - `read_terminal` MCP tool now supports optional `stripSpinner` parameter
111
+ - Consolidated documentation under [`docs/`](docs/README.md) with clearer
112
+ filenames and an index
113
+ - Refreshed `README.md` with quick-start instructions and the expanded tool set
114
+ - All logging now uses stderr to comply with MCP stdio protocol requirements
115
+
116
+ ## [1.0.1] - 2025-10-03
117
+
118
+ ### Fixed
119
+
120
+ #### 🔴 Critical: Commands not executing automatically
121
+ - **Problem**: Commands sent to terminal were displayed but not executed
122
+ - **Solution**: `write_terminal` now automatically adds newline character if not present
123
+ - **Impact**: Users can now send `"pwd"` instead of `"pwd\n"`
124
+ - **Backward Compatible**: Yes - existing code with `\n` still works
125
+
126
+ #### 🟡 Medium: Terminated terminals still in list
127
+ - **Problem**: After `kill_terminal`, terminals remained in `list_terminals` with status "terminated"
128
+ - **Solution**: Terminals are now completely removed from all internal maps after termination
129
+ - **Impact**: Better memory management and cleaner terminal list
130
+ - **Backward Compatible**: Yes - no API changes
131
+
132
+ ### Changed
133
+
134
+ - Updated `write_terminal` tool description to mention automatic newline addition
135
+ - Updated parameter descriptions to clarify newline behavior
136
+
137
+ ### Added
138
+
139
+ - New test script: `npm run test:fixes` to verify bug fixes
140
+ - Comprehensive test coverage for command execution and terminal cleanup
141
+
142
+ ### Documentation
143
+
144
+ - Added `docs/reference/bug-fixes.md` - Detailed technical report of fixes
145
+ - Added `docs/reference/test-response.md` - Response to AI testing teams
146
+ - Updated `docs/guides/usage.md` - Simplified command sending examples
147
+
148
+ ---
149
+
150
+ ## [1.0.0] - 2025-10-03
151
+
152
+ ### Added
153
+
154
+ #### Core Features
155
+ - **Persistent Terminal Sessions**: Create and manage long-running terminal sessions
156
+ - **Output Buffering**: Circular buffer with configurable size (default 10,000 lines)
157
+ - **Smart Output Reading**: Multiple modes (full, head, tail, head-tail)
158
+ - **Incremental Reading**: Read only new output using `since` parameter
159
+ - **Session Management**: Automatic cleanup of timed-out sessions
160
+
161
+ #### MCP Tools (6 total)
162
+ 1. `create_terminal` - Create new persistent terminal sessions
163
+ 2. `write_terminal` - Send input to terminal sessions
164
+ 3. `read_terminal` - Read output with smart truncation
165
+ 4. `get_terminal_stats` - Get detailed statistics (lines, bytes, tokens)
166
+ 5. `list_terminals` - List all active terminal sessions
167
+ 6. `kill_terminal` - Terminate terminal sessions
168
+
169
+ #### MCP Resources (3 total)
170
+ 1. `terminal://list` - List of all terminals
171
+ 2. `terminal://{id}/output` - Terminal output
172
+ 3. `terminal://{id}/info` - Terminal information
173
+
174
+ #### MCP Prompts (2 total)
175
+ 1. `debug-terminal` - Debug terminal issues
176
+ 2. `monitor-terminal` - Monitor terminal output
177
+
178
+ #### REST API
179
+ - Alternative HTTP interface for non-MCP clients
180
+ - All MCP tools available as REST endpoints
181
+ - CORS enabled for web clients
182
+
183
+ #### Examples
184
+ - `basic-usage.ts` - Basic terminal operations
185
+ - `rest-api-demo.ts` - REST API usage
186
+ - `interactive-demo.ts` - Interactive terminal demo
187
+ - `smart-reading-demo.ts` - Smart reading features
188
+ - `test-all-tools.ts` - Comprehensive tool testing
189
+
190
+ #### Documentation
191
+ - `README.md` - Project overview and quick start
192
+ - `docs/meta/project-status.md` - Project status and roadmap
193
+ - `docs/guides/usage.md` - Guide for AI assistants
194
+ - `docs/guides/troubleshooting.md` - Troubleshooting guide
195
+ - `docs/clients/claude-code-setup.md` - Claude Code configuration
196
+ - `docs/guides/mcp-config.md` - MCP configuration guide
197
+ - `docs/reference/tools-summary.md` - Quick reference for all tools
198
+
199
+ #### Configuration
200
+ - Environment variables support (`MAX_BUFFER_SIZE`, `SESSION_TIMEOUT`)
201
+ - Example configuration files for Claude Desktop and Claude Code
202
+ - TOML configuration format support
203
+
204
+ ### Technical Details
205
+
206
+ #### Architecture
207
+ - TypeScript with strict mode
208
+ - ES Modules (ESM)
209
+ - Event-driven design using EventEmitter
210
+ - Zod schema validation
211
+ - node-pty for PTY management
212
+
213
+ #### Testing
214
+ - Jest test framework
215
+ - Unit tests for core functionality
216
+ - Integration tests for MCP tools
217
+ - Example scripts for manual testing
218
+
219
+ #### Build System
220
+ - TypeScript compiler (tsc)
221
+ - tsx for development
222
+ - npm scripts for common tasks
223
+
224
+ ---
225
+
226
+ ## Version History
227
+
228
+ - **1.0.1** (2025-10-03) - Bug fixes for command execution and terminal cleanup
229
+ - **1.0.0** (2025-10-03) - Initial release with full MCP support
230
+
231
+ ---
232
+
233
+ ## Upgrade Guide
234
+
235
+ ### From 1.0.0 to 1.0.1
236
+
237
+ No breaking changes. Simply update and rebuild:
238
+
239
+ ```bash
240
+ git pull
241
+ npm run build
242
+ ```
243
+
244
+ If using Claude Code or Claude Desktop, restart the application after rebuilding.
245
+
246
+ ### Benefits of Upgrading
247
+
248
+ 1. **Better UX**: No need to manually add `\n` to commands
249
+ 2. **Memory Efficiency**: Terminated terminals are properly cleaned up
250
+ 3. **Cleaner API**: Terminal list only shows active terminals
251
+
252
+ ---
253
+
254
+ ## Future Plans
255
+
256
+ See `docs/meta/project-status.md` for detailed roadmap.
257
+
258
+ ### Planned Features
259
+
260
+ - [ ] Terminal session persistence across restarts
261
+ - [ ] Terminal multiplexing (tmux/screen integration)
262
+ - [ ] File upload/download support
263
+ - [ ] Terminal recording and playback
264
+ - [ ] WebSocket support for real-time updates
265
+ - [ ] Terminal sharing between users
266
+ - [ ] Custom shell profiles
267
+ - [ ] Environment variable management
268
+ - [ ] Command history and search
269
+
270
+ ---
271
+
272
+ ## Contributing
273
+
274
+ Contributions are welcome! Please see `CONTRIBUTING.md` for guidelines.
275
+
276
+ ## License
277
+
278
+ MIT License - see `LICENSE` file for details.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Persistent Terminal Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.en.md ADDED
@@ -0,0 +1,259 @@
1
+ # Persistent Terminal MCP Server
2
+
3
+ [简体中文](README.md)
4
+
5
+ Persistent Terminal MCP Server is a TypeScript implementation of a Model Context
6
+ Protocol (MCP) server that keeps terminal sessions alive for AI assistants and
7
+ automation flows. It is built on top of [`node-pty`](https://github.com/microsoft/node-pty)
8
+ so commands continue running even when the requesting client disconnects.
9
+
10
+ ## Highlights
11
+ - **Persistent PTY sessions** – create, reuse, and terminate long-running shells
12
+ - **Smart output buffering** – incremental reads plus head, tail, or head-tail
13
+ views with token estimates for large logs
14
+ - **Spinner animation compaction** – automatically detects and throttles progress
15
+ animations (like npm install spinners) to reduce noise and preserve real logs
16
+ - **Full session management** – statistics, listing, kill signals, and automatic
17
+ cleanup for inactive sessions
18
+ - **MCP-ready** – ships with tools, resources, and prompts compatible with
19
+ Claude Desktop, Claude Code, and other MCP clients
20
+ - **REST API option** – optional Express server mirrors the MCP functionality
21
+ for non-MCP integrations
22
+
23
+ ## Installation
24
+
25
+ ### One-off run (recommended for MCP clients)
26
+ Use `npx` to launch the server without a global install:
27
+ ```bash
28
+ npx persistent-terminal-mcp
29
+ ```
30
+
31
+ The REST flavor is available the same way:
32
+ ```bash
33
+ npx persistent-terminal-mcp-rest
34
+ ```
35
+
36
+ ### Project dependency
37
+ Add the package to an existing project (CLI + TypeScript APIs):
38
+ ```bash
39
+ npm install persistent-terminal-mcp
40
+ ```
41
+
42
+ Now you can reference both the CLI binaries in `node_modules/.bin/` and the
43
+ TypeScript exports:
44
+ ```ts
45
+ import { PersistentTerminalMcpServer } from 'persistent-terminal-mcp';
46
+ ```
47
+
48
+ ### Global install (optional)
49
+ ```bash
50
+ npm install --global persistent-terminal-mcp
51
+ persistent-terminal-mcp
52
+ ```
53
+
54
+ ## Local Development
55
+ Clone the repo if you want to work on the source:
56
+ ```bash
57
+ npm install # install dependencies
58
+ npm run build # compile TypeScript → dist/
59
+ npm start # launch the MCP server over stdio
60
+ ```
61
+
62
+ During development you can run the TypeScript sources directly:
63
+ ```bash
64
+ npm run dev # MCP server (tsx)
65
+ npm run dev:rest # REST server (tsx)
66
+ ```
67
+
68
+ ### Debugging Mode
69
+ To enable debug logging (output to stderr, won't interfere with MCP communication):
70
+ ```bash
71
+ MCP_DEBUG=true persistent-terminal-mcp
72
+ ```
73
+
74
+ ### Example Scripts
75
+ ```bash
76
+ npm run example:basic # basic lifecycle (create → write → read → kill)
77
+ npm run example:smart # demonstrates head/tail/head-tail reading
78
+ npm run test:tools # exercises every MCP tool end-to-end
79
+ npm run test:fixes # regression tests for recent bug fixes
80
+ ```
81
+
82
+ ## MCP Client Configuration
83
+
84
+ ### Claude Desktop (macOS / Linux)
85
+ Add the following configuration to your MCP settings file:
86
+
87
+ **Configuration file location**: `~/Library/Application Support/Claude/claude_desktop_config.json`
88
+
89
+ ```json
90
+ {
91
+ "mcpServers": {
92
+ "persistent-terminal": {
93
+ "command": "npx",
94
+ "args": [
95
+ "-y",
96
+ "persistent-terminal-mcp"
97
+ ],
98
+ "env": {
99
+ "MAX_BUFFER_SIZE": "10000",
100
+ "SESSION_TIMEOUT": "86400000",
101
+ "COMPACT_ANIMATIONS": "true",
102
+ "ANIMATION_THROTTLE_MS": "100"
103
+ }
104
+ }
105
+ }
106
+ }
107
+ ```
108
+
109
+ **Already installed?** If you installed the package globally, change `command` to
110
+ `"persistent-terminal-mcp"` and remove the `-y` argument.
111
+
112
+ ### Claude Code (CLI Method)
113
+ Use the command line to quickly add the MCP server:
114
+
115
+ ```bash
116
+ claude mcp add persistent-terminal \
117
+ --env MAX_BUFFER_SIZE=10000 \
118
+ --env SESSION_TIMEOUT=86400000 \
119
+ --env COMPACT_ANIMATIONS=true \
120
+ --env ANIMATION_THROTTLE_MS=100 \
121
+ -- npx -y persistent-terminal-mcp
122
+ ```
123
+
124
+ **Tip**: The `-y` flag answers "yes" to the download prompt so the command can run non-interactively.
125
+
126
+ **Example** (global install):
127
+ ```bash
128
+ claude mcp add persistent-terminal \
129
+ --env MAX_BUFFER_SIZE=10000 \
130
+ --env SESSION_TIMEOUT=86400000 \
131
+ --env COMPACT_ANIMATIONS=true \
132
+ --env ANIMATION_THROTTLE_MS=100 \
133
+ -- persistent-terminal-mcp
134
+ ```
135
+
136
+ ### Cursor / Cline Configuration
137
+ Configuration is similar to Claude Desktop. Please refer to the MCP configuration documentation for each client.
138
+
139
+ ### Codex Configuration
140
+ For Codex, add the following to `.codex/config.toml`:
141
+
142
+ ```toml
143
+ # MCP Server Configuration (TOML Format)
144
+ # For configuring persistent-terminal MCP server
145
+
146
+ [mcp_servers.persistent-terminal]
147
+ command = "npx"
148
+ args = ["-y", "persistent-terminal-mcp"]
149
+
150
+ [mcp_servers.persistent-terminal.env]
151
+ MAX_BUFFER_SIZE = "10000"
152
+ SESSION_TIMEOUT = "86400000"
153
+ COMPACT_ANIMATIONS = "true"
154
+ ANIMATION_THROTTLE_MS = "100"
155
+ ```
156
+
157
+ **Note**: Ensure the environment running `npx` has network access the first time so it can download the package if necessary.
158
+
159
+ ### Environment Variables
160
+ | Variable | Description | Default |
161
+ |----------|-------------|---------|
162
+ | `MAX_BUFFER_SIZE` | Maximum number of lines to keep in buffer | 10000 |
163
+ | `SESSION_TIMEOUT` | Session timeout in milliseconds | 86400000 (24 hours) |
164
+ | `COMPACT_ANIMATIONS` | Enable spinner animation compaction | true |
165
+ | `ANIMATION_THROTTLE_MS` | Animation throttle time in milliseconds | 100 |
166
+ | `MCP_DEBUG` | Enable debug logging | false |
167
+
168
+ ## Programmatic Usage (TypeScript)
169
+
170
+ ```ts
171
+ import {
172
+ PersistentTerminalMcpServer,
173
+ TerminalManager,
174
+ RestApiServer
175
+ } from 'persistent-terminal-mcp';
176
+
177
+ const manager = new TerminalManager();
178
+ const rest = new RestApiServer(manager);
179
+
180
+ await rest.start(3001);
181
+
182
+ const mcpServer = new PersistentTerminalMcpServer();
183
+ const server = mcpServer.getServer();
184
+ await server.connect(/* transport of your choice */);
185
+ ```
186
+
187
+ All core classes and type definitions are available directly from the root
188
+ module. Refer to [`src/index.ts`](src/index.ts) for the complete export list.
189
+
190
+ ## MCP Tools
191
+ | Tool | Purpose |
192
+ |------|---------|
193
+ | `create_terminal` | Create a persistent terminal session (supports `env`, `shell`, and `cwd`) |
194
+ | `create_terminal_basic` | Convenience alias for clients that can only send simple strings |
195
+ | `write_terminal` | Send input to a terminal; newline is added automatically if needed |
196
+ | `read_terminal` | Retrieve buffered output with smart truncation options |
197
+ | `wait_for_output` | Wait for terminal output to stabilize (useful after running commands) |
198
+ | `get_terminal_stats` | Inspect buffer size, line counts, estimated tokens, and activity |
199
+ | `list_terminals` | Enumerate active sessions and their metadata |
200
+ | `kill_terminal` | Terminate a session with an optional signal |
201
+
202
+ Additional MCP resources and prompts are exposed for listing sessions, viewing
203
+ output, and surfacing troubleshooting tips inside compatible clients.
204
+
205
+ ## REST API (Optional)
206
+ If you prefer HTTP, start the REST variant:
207
+ ```bash
208
+ npx persistent-terminal-mcp-rest
209
+ ```
210
+ The server listens on port `3001` (configurable) and mirrors the MCP toolset.
211
+ Endpoints include `/api/terminals`, `/api/terminals/:id/input`, `/api/terminals/:id/output`,
212
+ `/api/terminals/:id/stats`, `/api/terminals`, and `/api/terminals/:id`.
213
+
214
+ ## Project Layout
215
+ ```
216
+ docs/ → Consolidated documentation index
217
+ ├── guides/ → Usage guides and tutorials
218
+ ├── reference/ → Technical references and fixes
219
+ │ └── fixes/ → All fix documentation
220
+ ├── clients/ → Client-specific setup
221
+ └── zh/ → Chinese documentation
222
+ scripts/ → Helper scripts for local debugging
223
+ src/ → TypeScript source code
224
+ ├── __tests__/ → Unit tests
225
+ └── examples/ → Example scripts
226
+ tests/ → Test suites
227
+ └── integration/ → Integration tests
228
+ dist/ → Compiled JavaScript output
229
+ ```
230
+
231
+ ### Documentation Map
232
+ All documentation is organized under [`docs/`](docs/README.md):
233
+
234
+ **Quick Access:**
235
+ - 📖 [Documentation Index](docs/README.md) – Complete documentation map
236
+ - 🚨 [Fixes Index](docs/reference/fixes/README.md) – All fixes and solutions
237
+ - 🧪 [Integration Tests](tests/integration/README.md) – Test suite
238
+
239
+ **By Category:**
240
+ - **Guides**: Usage, troubleshooting, MCP configuration
241
+ - **Reference**: Technical details, tools summary, bug fixes
242
+ - **Fixes**: Stdio fix, Cursor fix, terminal fixes
243
+ - **Clients**: Claude Desktop / Claude Code setup
244
+ - **中文**: Chinese-language documentation
245
+
246
+ ### Important Notes
247
+ - **Stdio Purity**: This MCP server follows the MCP protocol strictly by ensuring stdout only contains JSON-RPC messages. All logging goes to stderr. See [docs/reference/fixes/STDIO_FIX.md](docs/reference/fixes/STDIO_FIX.md) for details.
248
+ - **Cursor Compatibility**: Fully compatible with Cursor and other strict MCP clients that require clean JSON-RPC communication. See [docs/reference/fixes/QUICK_FIX_GUIDE.md](docs/reference/fixes/QUICK_FIX_GUIDE.md) for quick setup.
249
+ - **Terminal Interaction**: Supports interactive applications (vim, npm create, etc.) with proper ANSI escape sequence handling. See [docs/reference/fixes/TERMINAL_FIXES.md](docs/reference/fixes/TERMINAL_FIXES.md) for details.
250
+ - **Output Stability**: Use `wait_for_output` tool to ensure complete output capture after running commands.
251
+
252
+ ## Contributing
253
+ Contributions are welcome! Please open an issue or pull request if you
254
+ encounter bugs or have ideas for new capabilities. The
255
+ [`CONTRIBUTING.md`](CONTRIBUTING.md) file outlines the recommended workflow and
256
+ coding standards.
257
+
258
+ ## License
259
+ This project is released under the [MIT License](LICENSE).