├── .gitignore ├── LICENSE ├── README.md └── secrets_manager.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # UV 98 | # Similar to Pipfile.lock, it is generally recommended to include uv.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | #uv.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 116 | .pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | 163 | # PyCharm 164 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 165 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 166 | # and can be added to the global gitignore or merged into this file. For a more nuclear 167 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 168 | #.idea/ 169 | 170 | # Ruff stuff: 171 | .ruff_cache/ 172 | 173 | # PyPI configuration file 174 | .pypirc 175 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2025 Amir Shaked 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Secrets Manager for MCP Server 2 | 3 | ## Overview 4 | 5 | `secrets_manager.py` is a Python utility that enables MCP servers to securely store and retrieve sensitive information using the system's native keychain/credential manager instead of relying on `.env` files. This approach significantly improves security by leveraging the operating system's built-in secure storage mechanisms. 6 | 7 | ## Key Features 8 | 9 | - **Cross-Platform Support**: Works on macOS (Keychain), Windows (Credential Locker), and other platforms (using appropriate keyring backends) 10 | - **Secure Storage**: Stores sensitive data like API keys in the system's secure credential storage 11 | - **Simple API**: Provides straightforward functions for storing and retrieving secrets 12 | - **Command-Line Interface**: Includes a CLI for managing secrets directly 13 | 14 | ## Core Functionality 15 | 16 | ### Secret Storage 17 | 18 | The script uses the `keyring` library to store secrets in the system's native credential manager: 19 | 20 | - On macOS: Stores secrets in the macOS Keychain 21 | - On Windows: Uses the Windows Credential Locker 22 | - On other platforms: Uses the best available keyring backend 23 | 24 | ### Main Functions 25 | 26 | 1. **`get_secret(service_name, secret_key)`**: Retrieves a secret from the system keyring 27 | 2. **`set_secret(service_name, secret_key, secret_value)`**: Stores a secret in the system keyring 28 | 3. **`setup_secrets()`**: Interactive function to collect and store initial secrets 29 | 4. **`test_get_secret()`**: Tests the retrieval of stored secrets 30 | 5. **`get_keyring_name()`**: Returns the name of the current keyring backend based on the platform 31 | 32 | ### Command-Line Interface 33 | 34 | The script can be run directly with the following options: 35 | 36 | - `--store`: Initiates the interactive secret storage process 37 | - `--test`: Tests retrieving stored secrets 38 | - `--info`: Displays information about the current keyring backend 39 | 40 | ## Usage Example 41 | 42 | Instead of storing API keys in `.env` files: 43 | 44 | ```python 45 | # Old approach with .env files 46 | API_KEY = os.getenv("API_KEY") # Insecure, stored in plaintext 47 | 48 | # New approach with secrets_manager 49 | from secrets_manager import get_secret 50 | API_KEY = get_secret("MyMCPServer", "api_key") # Secure, stored in system keychain 51 | ``` 52 | 53 | ## Benefits for MCP Servers 54 | 55 | 1. **Enhanced Security**: Secrets are stored in the operating system's secure storage rather than in plaintext files 56 | 2. **Simplified Management**: No need to manage `.env` files or worry about them being accidentally committed to version control 57 | 3. **User-Friendly**: Provides an interactive interface for setting up secrets 58 | 4. **Reliable Access**: Consistent API for accessing secrets across different platforms 59 | 60 | ## Implementation Note 61 | 62 | The script includes a commented example of how to access the stored secret directly from the macOS terminal: 63 | 64 | ```bash 65 | security find-generic-password -l "MyMCPServer" -a "api_key" -g 66 | ``` 67 | -------------------------------------------------------------------------------- /secrets_manager.py: -------------------------------------------------------------------------------- 1 | import keyring 2 | import getpass 3 | import argparse 4 | import os 5 | import platform 6 | from dotenv import load_dotenv 7 | 8 | # Load environment variables from .env file 9 | load_dotenv() 10 | 11 | # Get SERVICE_NAME from environment variables 12 | SERVICE_NAME = os.getenv("SERVICE_NAME", "MyMCPServer") # Default if not found 13 | 14 | def get_secret(service_name, secret_key): 15 | """Retrieve a secret from system keyring.""" 16 | try: 17 | secret = keyring.get_password(service_name, secret_key) 18 | if secret is None: 19 | raise KeyError(f"Secret '{secret_key}' not found in keyring for service '{service_name}'") 20 | return secret 21 | except Exception as e: 22 | print(f"Error accessing keyring: {e}") 23 | raise 24 | 25 | def set_secret(service_name, secret_key, secret_value): 26 | """Store a secret in system keyring.""" 27 | try: 28 | keyring.set_password(service_name, secret_key, secret_value) 29 | print(f"Secret '{secret_key}' stored successfully") 30 | except Exception as e: 31 | print(f"Error storing secret: {e}") 32 | raise 33 | 34 | def setup_secrets(): 35 | """Store initial secrets in keyring""" 36 | system = platform.system() 37 | print(f"Setting up secrets for {SERVICE_NAME} on {system}...") 38 | 39 | # Get secrets from user 40 | api_key = getpass.getpass("Enter API key: ") 41 | 42 | # Store in keyring 43 | keyring.set_password(SERVICE_NAME, "api_key", api_key) 44 | print(f"Secret stored successfully in {get_keyring_name()} for {SERVICE_NAME}") 45 | 46 | def test_get_secret(): 47 | """Test retrieving the stored secret""" 48 | try: 49 | system = platform.system() 50 | print(f"Retrieving secret for {SERVICE_NAME} from {get_keyring_name()}...") 51 | api_key = get_secret(SERVICE_NAME, "api_key") 52 | print(f"Retrieved API key: {api_key}") 53 | except Exception as e: 54 | print(f"Error retrieving secret: {e}") 55 | 56 | def get_keyring_name(): 57 | """Get the name of the current keyring backend""" 58 | system = platform.system() 59 | if system == "Darwin": 60 | return "macOS Keychain" 61 | elif system == "Windows": 62 | return "Windows Credential Locker" 63 | else: 64 | return keyring.get_keyring().__class__.__name__ 65 | 66 | if __name__ == "__main__": 67 | parser = argparse.ArgumentParser(description="Manage secrets for Server") 68 | parser.add_argument("--store", action="store_true", help="Store secrets in keyring") 69 | parser.add_argument("--test", action="store_true", help="Test retrieving secrets") 70 | parser.add_argument("--info", action="store_true", help="Show keyring backend information") 71 | 72 | args = parser.parse_args() 73 | 74 | if args.info: 75 | print(f"Platform: {platform.system()}") 76 | print(f"Keyring backend: {get_keyring_name()}") 77 | elif args.store: 78 | setup_secrets() 79 | elif args.test: 80 | test_get_secret() 81 | else: 82 | print("Please specify an action: --store, --test, or --info") 83 | parser.print_help() 84 | 85 | --------------------------------------------------------------------------------