iflow-mcp_blazickjp_shell-mcp-server 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,231 @@
1
+ Metadata-Version: 2.4
2
+ Name: iflow-mcp_blazickjp_shell-mcp-server
3
+ Version: 0.1.0
4
+ Summary: Shell MCP Server for Claude AI Application
5
+ Author-email: blazickjp <joe.blazick@yahoo.com>
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: mcp>=1.0.0
9
+ Requires-Dist: pydantic-settings>=2.0.0
10
+ Requires-Dist: pydantic>=2.0.0
11
+ Provides-Extra: test
12
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == 'test'
13
+ Requires-Dist: pytest-cov>=4.1.0; extra == 'test'
14
+ Requires-Dist: pytest>=7.0.0; extra == 'test'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # 🖥️ Shell MCP Server
18
+
19
+ [![PyPI version](https://badge.fury.io/py/shell-mcp-server.svg)](https://badge.fury.io/py/shell-mcp-server)
20
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
21
+ [![Python](https://img.shields.io/badge/python-3.11+-blue.svg)](https://www.python.org/downloads/)
22
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
23
+
24
+ > 🚀 Add secure shell command execution capabilities to your AI applications with the Shell MCP Server! Built for the Model Context Protocol.
25
+
26
+ <a href="https://glama.ai/mcp/servers/@blazickjp/shell-mcp-server">
27
+ <img width="380" height="200" src="https://glama.ai/mcp/servers/@blazickjp/shell-mcp-server/badge" alt="Shell Server MCP server" />
28
+ </a>
29
+
30
+ ## ✨ Features
31
+
32
+ - 🔒 **Secure Execution** - Commands run only in specified directories
33
+ - 🐚 **Multiple Shells** - Support for bash, sh, cmd, powershell
34
+ - ⏱️ **Timeout Control** - Automatic termination of long-running commands
35
+ - 🌍 **Cross-Platform** - Works on both Unix and Windows systems
36
+ - 🛡️ **Safe by Default** - Built-in directory and shell validation
37
+
38
+ ## 🚀 Quick Start
39
+
40
+ ### Installation
41
+
42
+ ```bash
43
+ # Using pip
44
+ pip install shell-mcp-server
45
+
46
+ # Using uv (recommended)
47
+ uv pip install shell-mcp-server
48
+ ```
49
+
50
+ ### 🔌 Claude Desktop Integration
51
+
52
+ Add this to your Claude Desktop config to enable shell command execution:
53
+
54
+ <details>
55
+ <summary>📝 Click to view configuration</summary>
56
+
57
+ ```json
58
+ {
59
+ "mcpServers": {
60
+ "shell-mcp-server": {
61
+ "command": "uv",
62
+ "args": [
63
+ "--directory",
64
+ "/path/to/shell-mcp-server",
65
+ "run",
66
+ "shell-mcp-server",
67
+ "/path/to/allowed/dir1",
68
+ "/path/to/allowed/dir2",
69
+ "--shell", "bash", "/bin/bash",
70
+ "--shell", "zsh", "/bin/zsh"
71
+ ]
72
+ }
73
+ }
74
+ }
75
+ ```
76
+ </details>
77
+
78
+ ## 🎮 Usage Examples
79
+
80
+ ### Basic File Operations
81
+ ```python
82
+ # List directory contents
83
+ result = execute_command(
84
+ command="ls -la",
85
+ shell="bash",
86
+ cwd="/path/to/project"
87
+ )
88
+
89
+ # Find files by pattern
90
+ result = execute_command(
91
+ command="find . -name '*.py'",
92
+ shell="bash",
93
+ cwd="/path/to/project"
94
+ )
95
+ ```
96
+
97
+ ### Project Management
98
+ ```python
99
+ # Git operations
100
+ result = execute_command(
101
+ command="git status && git diff",
102
+ shell="bash",
103
+ cwd="/path/to/repo"
104
+ )
105
+
106
+ # Package management
107
+ result = execute_command(
108
+ command="pip list --outdated",
109
+ shell="bash",
110
+ cwd="/path/to/python/project"
111
+ )
112
+ ```
113
+
114
+ ### System Information
115
+ ```python
116
+ # Resource usage
117
+ result = execute_command(
118
+ command="df -h && free -h",
119
+ shell="bash",
120
+ cwd="/path/to/dir"
121
+ )
122
+
123
+ # Process monitoring
124
+ result = execute_command(
125
+ command="ps aux | grep python",
126
+ shell="bash",
127
+ cwd="/path/to/dir"
128
+ )
129
+ ```
130
+
131
+ ### File Processing
132
+ ```python
133
+ # Search file content
134
+ result = execute_command(
135
+ command="grep -r 'TODO' .",
136
+ shell="bash",
137
+ cwd="/path/to/project"
138
+ )
139
+
140
+ # File manipulation
141
+ result = execute_command(
142
+ command="awk '{print $1}' data.csv | sort | uniq -c",
143
+ shell="bash",
144
+ cwd="/path/to/data"
145
+ )
146
+ ```
147
+
148
+ ### Windows-Specific Examples
149
+ ```python
150
+ # List processes
151
+ result = execute_command(
152
+ command="Get-Process | Where-Object {$_.CPU -gt 10}",
153
+ shell="powershell",
154
+ cwd="C:\\path\\to\\dir"
155
+ )
156
+
157
+ # System information
158
+ result = execute_command(
159
+ command="systeminfo | findstr /B /C:'OS'",
160
+ shell="cmd",
161
+ cwd="C:\\path\\to\\dir"
162
+ )
163
+ ```
164
+
165
+ ## ⚙️ Configuration
166
+
167
+ Configure behavior with command-line arguments:
168
+
169
+ | Argument | Description |
170
+ |----------|-------------|
171
+ | `directories` | 📁 List of allowed directories |
172
+ | `--shell name path` | 🐚 Shell specifications (name and path) |
173
+
174
+ Environment variables:
175
+ - `COMMAND_TIMEOUT`: ⏱️ Max execution time in seconds (default: 30)
176
+
177
+ ## 🛡️ Security Features
178
+
179
+ - 🔐 **Directory Isolation**: Commands can only execute in specified directories
180
+ - 🔒 **Shell Control**: Only configured shells are allowed
181
+ - ⏰ **Timeout Protection**: All commands have a configurable timeout
182
+ - 🛑 **Path Validation**: Working directory validation prevents traversal attacks
183
+ - 👤 **Permission Isolation**: Commands run with the same permissions as the server process
184
+
185
+ ## 🛠️ Development
186
+
187
+ Set up your development environment:
188
+
189
+ ```bash
190
+ # Create and activate virtual environment
191
+ uv venv
192
+ source .venv/bin/activate
193
+
194
+ # Install development dependencies
195
+ uv pip install -e ".[test]"
196
+
197
+ # Run tests
198
+ python -m pytest
199
+
200
+ # Run tests with coverage
201
+ python -m pytest --cov=shell_mcp_server
202
+ ```
203
+
204
+ ## 🤝 Contributing
205
+
206
+ Contributions are welcome! Feel free to:
207
+
208
+ - 🐛 Report bugs
209
+ - 💡 Suggest features
210
+ - 🔧 Submit pull requests
211
+ - 📚 Improve documentation
212
+
213
+ ## 📜 License
214
+
215
+ MIT License - see [LICENSE](LICENSE) for details.
216
+
217
+ ---
218
+
219
+ <div align="center">
220
+
221
+ ### 🌟 Enhance Your AI with Secure Shell Access! 🌟
222
+
223
+ Built for the [Model Context Protocol](https://github.com/anthropics/anthropic-tools) | Made with ❤️ by the MCP Community
224
+
225
+ <details>
226
+ <summary>🎉 Star us on GitHub!</summary>
227
+ <br>
228
+ If you find this tool useful, consider giving it a star! It helps others discover the project.
229
+ </details>
230
+
231
+ </div>
@@ -0,0 +1,8 @@
1
+ shell_mcp_server/__init__.py,sha256=ovAp5TM0MqnMk3hUovDs3zW_KWnZcSPJRga7auz8yqo,248
2
+ shell_mcp_server/config.py,sha256=qTFZ64VNXHl5Ie9DvjyKuNkrzGH5toOMbDIYTOx9djI,1525
3
+ shell_mcp_server/server.py,sha256=USlegBvdC_CtbZw_tY3WJFkw_FjGEyv4Y7vanTbjnFM,6699
4
+ iflow_mcp_blazickjp_shell_mcp_server-0.1.0.dist-info/METADATA,sha256=ghEJyi8zXTIZc2GMYbVqvW0jn5_NotmvrDHnlS17lDc,5768
5
+ iflow_mcp_blazickjp_shell_mcp_server-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
6
+ iflow_mcp_blazickjp_shell_mcp_server-0.1.0.dist-info/entry_points.txt,sha256=uU33kdLorqZrlsFgrszpUNpbey1hpoeUGanALjvI950,59
7
+ iflow_mcp_blazickjp_shell_mcp_server-0.1.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
8
+ iflow_mcp_blazickjp_shell_mcp_server-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ shell-mcp-server = shell_mcp_server:main
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,13 @@
1
+ """Shell MCP Server package."""
2
+
3
+ from . import server
4
+ import asyncio
5
+
6
+
7
+ def main():
8
+ """Main entry point for the package."""
9
+ asyncio.run(server.main())
10
+
11
+
12
+ # Optionally expose other important items at package level
13
+ __all__ = ["main", "server"]
@@ -0,0 +1,44 @@
1
+ """
2
+ Configuration Settings for Shell MCP Server
3
+ ========================================
4
+
5
+ This module defines the settings and configuration options for the shell MCP server.
6
+ """
7
+
8
+ from pydantic_settings import BaseSettings
9
+ from pydantic import ConfigDict
10
+ from typing import List, Dict
11
+ import os
12
+
13
+
14
+ class Settings(BaseSettings):
15
+ """
16
+ Application settings class using pydantic_settings.
17
+
18
+ Attributes:
19
+ APP_NAME (str): Name of the application
20
+ APP_VERSION (str): Current version of the application
21
+ COMMAND_TIMEOUT (int): Timeout for command execution in seconds
22
+ ALLOWED_DIRECTORIES (List[str]): List of directories where commands can be executed
23
+ ALLOWED_SHELLS (Dict[str, str]): Dictionary of shell names to their paths
24
+ """
25
+
26
+ APP_NAME: str = "shell-mcp-server"
27
+ APP_VERSION: str = "0.1.0"
28
+ COMMAND_TIMEOUT: int = 30
29
+ ALLOWED_DIRECTORIES: List[str] = []
30
+ ALLOWED_SHELLS: Dict[str, str] = {}
31
+
32
+ def __init__(self, directories: List[str], shells: Dict[str, str]):
33
+ super().__init__()
34
+ self.ALLOWED_DIRECTORIES = [os.path.abspath(d) for d in directories]
35
+ self.ALLOWED_SHELLS = shells
36
+
37
+ def is_path_allowed(self, path: str) -> bool:
38
+ """Check if a path is within any of the allowed directories."""
39
+ abs_path = os.path.abspath(path)
40
+ return any(
41
+ abs_path.startswith(allowed_dir) for allowed_dir in self.ALLOWED_DIRECTORIES
42
+ )
43
+
44
+ model_config = ConfigDict(env_file=".env", env_file_encoding="utf-8")
@@ -0,0 +1,200 @@
1
+ """
2
+ Shell MCP Server
3
+ ==============
4
+
5
+ This module implements an MCP server that provides secure shell command execution
6
+ within specified working directories using specified shells.
7
+
8
+ Key Features:
9
+ - Safe command execution in specified directories
10
+ - Supports multiple shell types (bash, sh, cmd, powershell)
11
+ - Command timeout handling
12
+ - Cross-platform support
13
+ - Robust error handling
14
+ """
15
+
16
+ import asyncio
17
+ import os
18
+ import sys
19
+ import argparse
20
+ from typing import Dict, Any, List
21
+ import mcp
22
+ import mcp.types as types
23
+ from mcp.server import Server, InitializationOptions, NotificationOptions
24
+ from .config import Settings
25
+
26
+
27
+ # Parse command line arguments for directories and shells
28
+ def parse_args() -> tuple[List[str], Dict[str, str]]:
29
+ """Parse command line arguments for directories and shells."""
30
+ parser = argparse.ArgumentParser(description="Shell MCP Server")
31
+ parser.add_argument('directories', nargs='+', help='Allowed directories for command execution')
32
+ parser.add_argument('--shell', action='append', nargs=2, metavar=('name', 'path'),
33
+ help='Shell specification in format: name path')
34
+
35
+ args = parser.parse_args()
36
+
37
+ # Convert shell arguments to dictionary
38
+ shells = {}
39
+ if args.shell:
40
+ shells = {name: path for name, path in args.shell}
41
+
42
+ # Default to system shell if none specified
43
+ if not shells:
44
+ if sys.platform == 'win32':
45
+ shells = {'cmd': 'cmd.exe', 'powershell': 'powershell.exe'}
46
+ else:
47
+ shells = {'bash': '/bin/bash', 'sh': '/bin/sh'}
48
+
49
+ return args.directories, shells
50
+
51
+
52
+ # Initialize server settings and create server instance - skip arg parsing for tests
53
+ if 'pytest' not in sys.modules:
54
+ directories, shells = parse_args()
55
+ settings = Settings(directories=directories, shells=shells)
56
+ else:
57
+ settings = Settings(directories=['/tmp'], shells={'bash': '/bin/bash'})
58
+
59
+ server = Server(settings.APP_NAME)
60
+
61
+
62
+ async def run_shell_command(shell: str, command: str, cwd: str) -> Dict[str, Any]:
63
+ """
64
+ Execute a shell command safely and return its output.
65
+
66
+ Args:
67
+ shell (str): Name of the shell to use
68
+ command (str): The command to execute
69
+ cwd (str): Working directory for command execution
70
+
71
+ Returns:
72
+ Dict[str, Any]: Command execution results including stdout, stderr, and exit code
73
+ """
74
+ if not settings.is_path_allowed(cwd):
75
+ raise ValueError(f"Directory '{cwd}' is not in the allowed directories list")
76
+
77
+ if shell not in settings.ALLOWED_SHELLS:
78
+ raise ValueError(f"Shell '{shell}' is not allowed. Available shells: {list(settings.ALLOWED_SHELLS.keys())}")
79
+
80
+ shell_path = settings.ALLOWED_SHELLS[shell]
81
+
82
+ try:
83
+ if sys.platform == 'win32':
84
+ shell_cmd = [shell_path, '/c', command] if shell == 'cmd' else [shell_path, '-Command', command]
85
+ else:
86
+ shell_cmd = [shell_path, '-c', command]
87
+
88
+ process = await asyncio.create_subprocess_exec(
89
+ *shell_cmd,
90
+ stdout=asyncio.subprocess.PIPE,
91
+ stderr=asyncio.subprocess.PIPE,
92
+ cwd=cwd
93
+ )
94
+
95
+ try:
96
+ stdout, stderr = await asyncio.wait_for(
97
+ process.communicate(),
98
+ timeout=settings.COMMAND_TIMEOUT
99
+ )
100
+
101
+ return {
102
+ "stdout": stdout.decode() if stdout else "",
103
+ "stderr": stderr.decode() if stderr else "",
104
+ "exit_code": process.returncode,
105
+ "command": command,
106
+ "shell": shell,
107
+ "cwd": cwd
108
+ }
109
+
110
+ except asyncio.TimeoutError:
111
+ try:
112
+ process.kill()
113
+ await process.wait()
114
+ except ProcessLookupError:
115
+ pass
116
+ raise TimeoutError(f"Command execution timed out after {settings.COMMAND_TIMEOUT} seconds")
117
+
118
+ except TimeoutError:
119
+ raise
120
+ except Exception as e:
121
+ return {
122
+ "stdout": "",
123
+ "stderr": str(e),
124
+ "exit_code": -1,
125
+ "command": command,
126
+ "shell": shell,
127
+ "cwd": cwd
128
+ }
129
+
130
+
131
+ @server.list_tools()
132
+ async def list_tools() -> List[types.Tool]:
133
+ """List available shell tools."""
134
+ return [
135
+ types.Tool(
136
+ name="execute_command",
137
+ description="Execute a shell command in a specified directory using a specified shell",
138
+ inputSchema={
139
+ "type": "object",
140
+ "properties": {
141
+ "command": {
142
+ "type": "string",
143
+ "description": "The shell command to execute",
144
+ },
145
+ "shell": {
146
+ "type": "string",
147
+ "description": f"Shell to use for execution. Available: {list(settings.ALLOWED_SHELLS.keys())}",
148
+ },
149
+ "cwd": {
150
+ "type": "string",
151
+ "description": "Working directory for command execution",
152
+ },
153
+ },
154
+ "required": ["command", "shell", "cwd"],
155
+ },
156
+ )
157
+ ]
158
+
159
+
160
+ @server.call_tool()
161
+ async def call_tool(name: str, arguments: Dict[str, Any]) -> List[types.TextContent]:
162
+ """
163
+ Handle tool calls for shell command execution.
164
+
165
+ Args:
166
+ name (str): The name of the tool to call (must be 'execute_command')
167
+ arguments (Dict[str, Any]): Tool arguments including 'command', 'shell', and 'cwd'
168
+
169
+ Returns:
170
+ List[types.TextContent]: The command execution results or error message
171
+ """
172
+ if name != "execute_command":
173
+ return [types.TextContent(type="text", text=f"Error: Unknown tool {name}")]
174
+
175
+ command = arguments["command"]
176
+ shell = arguments["shell"]
177
+ cwd = arguments["cwd"]
178
+
179
+ try:
180
+ result = await run_shell_command(shell, command, cwd)
181
+ return [types.TextContent(type="text", text=str(result))]
182
+ except Exception as e:
183
+ return [types.TextContent(type="text", text=f"Error: {str(e)}")]
184
+
185
+
186
+ async def main():
187
+ """Main entry point for the shell MCP server."""
188
+ async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
189
+ await server.run(
190
+ read_stream,
191
+ write_stream,
192
+ InitializationOptions(
193
+ server_name=settings.APP_NAME,
194
+ server_version=settings.APP_VERSION,
195
+ capabilities=server.get_capabilities(
196
+ notification_options=NotificationOptions(),
197
+ experimental_capabilities={},
198
+ ),
199
+ ),
200
+ )