iflow-mcp_mcp-db-navigator 1.0.2__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024
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.
@@ -0,0 +1,189 @@
1
+ Metadata-Version: 2.4
2
+ Name: iflow-mcp_mcp-db-navigator
3
+ Version: 1.0.2
4
+ Summary: A powerful MySQL/MariaDB database navigation tool using MCP (Model Control Protocol).
5
+ Author-email: "Ahmed S. Said-ahmed" <ahmed@pharoslab.net>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Homepage, https://github.com/yourusername/mcp-db
28
+ Requires-Python: >=3.8
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Requires-Dist: fastmcp>=0.1.0
32
+ Requires-Dist: mysql-connector-python>=8.0.26
33
+ Requires-Dist: pydantic>=2.0.0
34
+ Requires-Dist: cryptography>=3.4.7
35
+ Requires-Dist: typing-extensions>=4.0.0
36
+ Dynamic: license-file
37
+
38
+ # MySQL Navigator MCP
39
+
40
+ A powerful MySQL/MariaDB database navigation tool using MCP (Model Control Protocol) for easy database querying and management.
41
+
42
+ ## Features
43
+
44
+ - Connect to MySQL/MariaDB databases
45
+ - Switch between different databases dynamically
46
+ - Execute SQL queries with type safety
47
+ - Retrieve database schema information
48
+ - Pydantic model validation for query parameters
49
+ - Secure credential management
50
+ - Comprehensive logging system
51
+ - Connection pooling and retry mechanisms
52
+ - SSL/TLS support for secure connections
53
+
54
+ ## Log File Location (Cross-Platform)
55
+
56
+ By default, all logs are written to:
57
+
58
+ - **Windows:** `C:\Users\<YourUsername>\.mcp\mcp-db.log`
59
+ - **macOS/Linux:** `/home/<yourusername>/.mcp/mcp-db.log` or `/Users/<yourusername>/.mcp/mcp-db.log`
60
+
61
+ If the `.mcp` folder does not exist in your home directory, the application will automatically create it. If you run into any issues, you can manually create the folder:
62
+
63
+ **Windows:**
64
+ ```powershell
65
+ mkdir $env:USERPROFILE\.mcp
66
+ ```
67
+ **macOS/Linux:**
68
+ ```bash
69
+ mkdir -p ~/.mcp
70
+ ```
71
+
72
+ ## Installation
73
+
74
+ ### From PyPI (recommended for most users):
75
+ ```bash
76
+ pip install mcp-db-navigator
77
+ ```
78
+
79
+ ### From source (for development):
80
+ ```bash
81
+ git clone <your-repo-url>
82
+ cd mcp-db
83
+ pip install -e .
84
+ ```
85
+
86
+ 3. Create a `.env` file with your database credentials:
87
+ ```env
88
+ DB_HOST=your_host
89
+ DB_PORT=your_port
90
+ DB_NAME=your_database_name
91
+ DB_USER=your_username
92
+ DB_PASSWORD=your_password
93
+ DB_SSL_CA=/path/to/ssl/ca.pem # Optional: for SSL/TLS connections
94
+ DB_MAX_RETRIES=3 # Optional: number of connection retries
95
+ DB_RETRY_DELAY=1.0 # Optional: delay between retries in seconds
96
+ ```
97
+
98
+ ## Usage Examples
99
+
100
+ ### 1. Command Line
101
+ Run the MCP server directly from your terminal:
102
+ ```bash
103
+ mcp-db --config /path/to/your/project/.env
104
+ ```
105
+
106
+ ### 2. In Cursor
107
+ To use this MCP server in [Cursor](https://www.cursor.so):
108
+ - Open Cursor settings and add a new MCP server.
109
+ - Use the following configuration (example):
110
+
111
+ ```json
112
+ {
113
+ "mcpServers": {
114
+ "mysql-navigator": {
115
+ "command": "mcp-db",
116
+ "args": [
117
+ "--config",
118
+ "/absolute/path/to/your/.env"
119
+ ]
120
+ }
121
+ }
122
+ }
123
+ ```
124
+ - Make sure the path to your `.env` file is absolute.
125
+
126
+ ### 3. In Claude Desktop
127
+ If Claude Desktop supports MCP servers:
128
+ - Add a new MCP server and point it to the `mcp-db` command with the `--config` argument as above.
129
+ - Refer to Claude Desktop's documentation for details on adding custom MCP servers.
130
+
131
+ ## Query Parameters
132
+
133
+ The query dictionary supports the following parameters:
134
+
135
+ - `table_name` (required): Name of the table to query
136
+ - `select_fields` (optional): List of fields to select (defaults to ["*"])
137
+ - `where_conditions` (optional): Dictionary of field-value pairs for WHERE clause
138
+ - `order_by` (optional): List of fields to order by
139
+ - `order_direction` (optional): Sort direction "ASC" or "DESC" (default: "ASC")
140
+ - `limit` (optional): Number of records to return
141
+ - `offset` (optional): Number of records to skip
142
+ - `group_by` (optional): List of fields to group by
143
+ - `having` (optional): Dictionary of field-value pairs for HAVING clause
144
+ - `join_table` (optional): Name of the table to join with
145
+ - `join_type` (optional): Type of JOIN operation (default: "INNER")
146
+ - `join_conditions` (optional): Dictionary of join conditions
147
+
148
+ ## Security Features
149
+
150
+ - Database credentials are managed through a config file
151
+ - Passwords are stored as SecretStr in Pydantic models
152
+ - Input validation for all query parameters
153
+ - SQL injection prevention through parameterized queries
154
+ - SSL/TLS support for encrypted connections
155
+ - Connection string sanitization
156
+ - Rate limiting for queries
157
+ - Query parameter sanitization
158
+
159
+ ## Production Features
160
+
161
+ ### Error Handling
162
+ - Comprehensive error handling for database operations
163
+ - Connection timeout handling
164
+ - Automatic retry mechanism for failed connections
165
+ - Input validation for all parameters
166
+
167
+ ### Performance
168
+ - Connection pooling for optimal resource usage
169
+ - Query execution time logging
170
+ - Connection pool statistics
171
+ - Performance metrics collection
172
+
173
+ ### Monitoring
174
+ - Structured logging with different log levels
175
+ - Query execution tracking
176
+ - Connection state monitoring
177
+ - Error rate tracking
178
+
179
+ ## Contributing
180
+
181
+ 1. Fork the repository
182
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
183
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
184
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
185
+ 5. Open a Pull Request
186
+
187
+ ## License
188
+
189
+ This project is licensed under the MIT License - see the LICENSE file for details.
@@ -0,0 +1,152 @@
1
+ # MySQL Navigator MCP
2
+
3
+ A powerful MySQL/MariaDB database navigation tool using MCP (Model Control Protocol) for easy database querying and management.
4
+
5
+ ## Features
6
+
7
+ - Connect to MySQL/MariaDB databases
8
+ - Switch between different databases dynamically
9
+ - Execute SQL queries with type safety
10
+ - Retrieve database schema information
11
+ - Pydantic model validation for query parameters
12
+ - Secure credential management
13
+ - Comprehensive logging system
14
+ - Connection pooling and retry mechanisms
15
+ - SSL/TLS support for secure connections
16
+
17
+ ## Log File Location (Cross-Platform)
18
+
19
+ By default, all logs are written to:
20
+
21
+ - **Windows:** `C:\Users\<YourUsername>\.mcp\mcp-db.log`
22
+ - **macOS/Linux:** `/home/<yourusername>/.mcp/mcp-db.log` or `/Users/<yourusername>/.mcp/mcp-db.log`
23
+
24
+ If the `.mcp` folder does not exist in your home directory, the application will automatically create it. If you run into any issues, you can manually create the folder:
25
+
26
+ **Windows:**
27
+ ```powershell
28
+ mkdir $env:USERPROFILE\.mcp
29
+ ```
30
+ **macOS/Linux:**
31
+ ```bash
32
+ mkdir -p ~/.mcp
33
+ ```
34
+
35
+ ## Installation
36
+
37
+ ### From PyPI (recommended for most users):
38
+ ```bash
39
+ pip install mcp-db-navigator
40
+ ```
41
+
42
+ ### From source (for development):
43
+ ```bash
44
+ git clone <your-repo-url>
45
+ cd mcp-db
46
+ pip install -e .
47
+ ```
48
+
49
+ 3. Create a `.env` file with your database credentials:
50
+ ```env
51
+ DB_HOST=your_host
52
+ DB_PORT=your_port
53
+ DB_NAME=your_database_name
54
+ DB_USER=your_username
55
+ DB_PASSWORD=your_password
56
+ DB_SSL_CA=/path/to/ssl/ca.pem # Optional: for SSL/TLS connections
57
+ DB_MAX_RETRIES=3 # Optional: number of connection retries
58
+ DB_RETRY_DELAY=1.0 # Optional: delay between retries in seconds
59
+ ```
60
+
61
+ ## Usage Examples
62
+
63
+ ### 1. Command Line
64
+ Run the MCP server directly from your terminal:
65
+ ```bash
66
+ mcp-db --config /path/to/your/project/.env
67
+ ```
68
+
69
+ ### 2. In Cursor
70
+ To use this MCP server in [Cursor](https://www.cursor.so):
71
+ - Open Cursor settings and add a new MCP server.
72
+ - Use the following configuration (example):
73
+
74
+ ```json
75
+ {
76
+ "mcpServers": {
77
+ "mysql-navigator": {
78
+ "command": "mcp-db",
79
+ "args": [
80
+ "--config",
81
+ "/absolute/path/to/your/.env"
82
+ ]
83
+ }
84
+ }
85
+ }
86
+ ```
87
+ - Make sure the path to your `.env` file is absolute.
88
+
89
+ ### 3. In Claude Desktop
90
+ If Claude Desktop supports MCP servers:
91
+ - Add a new MCP server and point it to the `mcp-db` command with the `--config` argument as above.
92
+ - Refer to Claude Desktop's documentation for details on adding custom MCP servers.
93
+
94
+ ## Query Parameters
95
+
96
+ The query dictionary supports the following parameters:
97
+
98
+ - `table_name` (required): Name of the table to query
99
+ - `select_fields` (optional): List of fields to select (defaults to ["*"])
100
+ - `where_conditions` (optional): Dictionary of field-value pairs for WHERE clause
101
+ - `order_by` (optional): List of fields to order by
102
+ - `order_direction` (optional): Sort direction "ASC" or "DESC" (default: "ASC")
103
+ - `limit` (optional): Number of records to return
104
+ - `offset` (optional): Number of records to skip
105
+ - `group_by` (optional): List of fields to group by
106
+ - `having` (optional): Dictionary of field-value pairs for HAVING clause
107
+ - `join_table` (optional): Name of the table to join with
108
+ - `join_type` (optional): Type of JOIN operation (default: "INNER")
109
+ - `join_conditions` (optional): Dictionary of join conditions
110
+
111
+ ## Security Features
112
+
113
+ - Database credentials are managed through a config file
114
+ - Passwords are stored as SecretStr in Pydantic models
115
+ - Input validation for all query parameters
116
+ - SQL injection prevention through parameterized queries
117
+ - SSL/TLS support for encrypted connections
118
+ - Connection string sanitization
119
+ - Rate limiting for queries
120
+ - Query parameter sanitization
121
+
122
+ ## Production Features
123
+
124
+ ### Error Handling
125
+ - Comprehensive error handling for database operations
126
+ - Connection timeout handling
127
+ - Automatic retry mechanism for failed connections
128
+ - Input validation for all parameters
129
+
130
+ ### Performance
131
+ - Connection pooling for optimal resource usage
132
+ - Query execution time logging
133
+ - Connection pool statistics
134
+ - Performance metrics collection
135
+
136
+ ### Monitoring
137
+ - Structured logging with different log levels
138
+ - Query execution tracking
139
+ - Connection state monitoring
140
+ - Error rate tracking
141
+
142
+ ## Contributing
143
+
144
+ 1. Fork the repository
145
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
146
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
147
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
148
+ 5. Open a Pull Request
149
+
150
+ ## License
151
+
152
+ This project is licensed under the MIT License - see the LICENSE file for details.
@@ -0,0 +1,189 @@
1
+ Metadata-Version: 2.4
2
+ Name: iflow-mcp_mcp-db-navigator
3
+ Version: 1.0.2
4
+ Summary: A powerful MySQL/MariaDB database navigation tool using MCP (Model Control Protocol).
5
+ Author-email: "Ahmed S. Said-ahmed" <ahmed@pharoslab.net>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2024
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Homepage, https://github.com/yourusername/mcp-db
28
+ Requires-Python: >=3.8
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Requires-Dist: fastmcp>=0.1.0
32
+ Requires-Dist: mysql-connector-python>=8.0.26
33
+ Requires-Dist: pydantic>=2.0.0
34
+ Requires-Dist: cryptography>=3.4.7
35
+ Requires-Dist: typing-extensions>=4.0.0
36
+ Dynamic: license-file
37
+
38
+ # MySQL Navigator MCP
39
+
40
+ A powerful MySQL/MariaDB database navigation tool using MCP (Model Control Protocol) for easy database querying and management.
41
+
42
+ ## Features
43
+
44
+ - Connect to MySQL/MariaDB databases
45
+ - Switch between different databases dynamically
46
+ - Execute SQL queries with type safety
47
+ - Retrieve database schema information
48
+ - Pydantic model validation for query parameters
49
+ - Secure credential management
50
+ - Comprehensive logging system
51
+ - Connection pooling and retry mechanisms
52
+ - SSL/TLS support for secure connections
53
+
54
+ ## Log File Location (Cross-Platform)
55
+
56
+ By default, all logs are written to:
57
+
58
+ - **Windows:** `C:\Users\<YourUsername>\.mcp\mcp-db.log`
59
+ - **macOS/Linux:** `/home/<yourusername>/.mcp/mcp-db.log` or `/Users/<yourusername>/.mcp/mcp-db.log`
60
+
61
+ If the `.mcp` folder does not exist in your home directory, the application will automatically create it. If you run into any issues, you can manually create the folder:
62
+
63
+ **Windows:**
64
+ ```powershell
65
+ mkdir $env:USERPROFILE\.mcp
66
+ ```
67
+ **macOS/Linux:**
68
+ ```bash
69
+ mkdir -p ~/.mcp
70
+ ```
71
+
72
+ ## Installation
73
+
74
+ ### From PyPI (recommended for most users):
75
+ ```bash
76
+ pip install mcp-db-navigator
77
+ ```
78
+
79
+ ### From source (for development):
80
+ ```bash
81
+ git clone <your-repo-url>
82
+ cd mcp-db
83
+ pip install -e .
84
+ ```
85
+
86
+ 3. Create a `.env` file with your database credentials:
87
+ ```env
88
+ DB_HOST=your_host
89
+ DB_PORT=your_port
90
+ DB_NAME=your_database_name
91
+ DB_USER=your_username
92
+ DB_PASSWORD=your_password
93
+ DB_SSL_CA=/path/to/ssl/ca.pem # Optional: for SSL/TLS connections
94
+ DB_MAX_RETRIES=3 # Optional: number of connection retries
95
+ DB_RETRY_DELAY=1.0 # Optional: delay between retries in seconds
96
+ ```
97
+
98
+ ## Usage Examples
99
+
100
+ ### 1. Command Line
101
+ Run the MCP server directly from your terminal:
102
+ ```bash
103
+ mcp-db --config /path/to/your/project/.env
104
+ ```
105
+
106
+ ### 2. In Cursor
107
+ To use this MCP server in [Cursor](https://www.cursor.so):
108
+ - Open Cursor settings and add a new MCP server.
109
+ - Use the following configuration (example):
110
+
111
+ ```json
112
+ {
113
+ "mcpServers": {
114
+ "mysql-navigator": {
115
+ "command": "mcp-db",
116
+ "args": [
117
+ "--config",
118
+ "/absolute/path/to/your/.env"
119
+ ]
120
+ }
121
+ }
122
+ }
123
+ ```
124
+ - Make sure the path to your `.env` file is absolute.
125
+
126
+ ### 3. In Claude Desktop
127
+ If Claude Desktop supports MCP servers:
128
+ - Add a new MCP server and point it to the `mcp-db` command with the `--config` argument as above.
129
+ - Refer to Claude Desktop's documentation for details on adding custom MCP servers.
130
+
131
+ ## Query Parameters
132
+
133
+ The query dictionary supports the following parameters:
134
+
135
+ - `table_name` (required): Name of the table to query
136
+ - `select_fields` (optional): List of fields to select (defaults to ["*"])
137
+ - `where_conditions` (optional): Dictionary of field-value pairs for WHERE clause
138
+ - `order_by` (optional): List of fields to order by
139
+ - `order_direction` (optional): Sort direction "ASC" or "DESC" (default: "ASC")
140
+ - `limit` (optional): Number of records to return
141
+ - `offset` (optional): Number of records to skip
142
+ - `group_by` (optional): List of fields to group by
143
+ - `having` (optional): Dictionary of field-value pairs for HAVING clause
144
+ - `join_table` (optional): Name of the table to join with
145
+ - `join_type` (optional): Type of JOIN operation (default: "INNER")
146
+ - `join_conditions` (optional): Dictionary of join conditions
147
+
148
+ ## Security Features
149
+
150
+ - Database credentials are managed through a config file
151
+ - Passwords are stored as SecretStr in Pydantic models
152
+ - Input validation for all query parameters
153
+ - SQL injection prevention through parameterized queries
154
+ - SSL/TLS support for encrypted connections
155
+ - Connection string sanitization
156
+ - Rate limiting for queries
157
+ - Query parameter sanitization
158
+
159
+ ## Production Features
160
+
161
+ ### Error Handling
162
+ - Comprehensive error handling for database operations
163
+ - Connection timeout handling
164
+ - Automatic retry mechanism for failed connections
165
+ - Input validation for all parameters
166
+
167
+ ### Performance
168
+ - Connection pooling for optimal resource usage
169
+ - Query execution time logging
170
+ - Connection pool statistics
171
+ - Performance metrics collection
172
+
173
+ ### Monitoring
174
+ - Structured logging with different log levels
175
+ - Query execution tracking
176
+ - Connection state monitoring
177
+ - Error rate tracking
178
+
179
+ ## Contributing
180
+
181
+ 1. Fork the repository
182
+ 2. Create your feature branch (`git checkout -b feature/amazing-feature`)
183
+ 3. Commit your changes (`git commit -m 'Add some amazing feature'`)
184
+ 4. Push to the branch (`git push origin feature/amazing-feature`)
185
+ 5. Open a Pull Request
186
+
187
+ ## License
188
+
189
+ This project is licensed under the MIT License - see the LICENSE file for details.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ iflow_mcp_mcp_db_navigator.egg-info/PKG-INFO
5
+ iflow_mcp_mcp_db_navigator.egg-info/SOURCES.txt
6
+ iflow_mcp_mcp_db_navigator.egg-info/dependency_links.txt
7
+ iflow_mcp_mcp_db_navigator.egg-info/entry_points.txt
8
+ iflow_mcp_mcp_db_navigator.egg-info/requires.txt
9
+ iflow_mcp_mcp_db_navigator.egg-info/top_level.txt
10
+ mcp_db/__init__.py
11
+ mcp_db/connection_pool.py
12
+ mcp_db/db.py
13
+ mcp_db/metrics.py
14
+ mcp_db/security.py
15
+ mcp_db/server.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ mcp-db = mcp_db.server:main_cli
@@ -0,0 +1,5 @@
1
+ fastmcp>=0.1.0
2
+ mysql-connector-python>=8.0.26
3
+ pydantic>=2.0.0
4
+ cryptography>=3.4.7
5
+ typing-extensions>=4.0.0
File without changes
@@ -0,0 +1,84 @@
1
+ from mysql.connector import pooling, Error
2
+ import logging
3
+ from typing import Any
4
+ from mcp_db.db import DatabaseCredentials
5
+ from mcp_db.security import SecurityManager
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ class ConnectionPool:
10
+ _instance = None
11
+ _pool = None
12
+
13
+ def __new__(cls):
14
+ if cls._instance is None:
15
+ cls._instance = super(ConnectionPool, cls).__new__(cls)
16
+ return cls._instance
17
+
18
+ def __init__(self):
19
+ self.pool_name = "mysql_pool"
20
+ self.pool_size = 5
21
+ self.security_manager = SecurityManager()
22
+
23
+ def initialize_pool(self, credentials: DatabaseCredentials) -> None:
24
+ """Initialize the connection pool with given credentials"""
25
+ if self._pool is not None:
26
+ logger.warning("Pool already initialized")
27
+ return
28
+
29
+ try:
30
+ # Get SSL context if SSL CA is provided
31
+ ssl_context = self.security_manager.get_ssl_context(credentials.ssl_ca)
32
+
33
+ pool_config = {
34
+ "pool_name": self.pool_name,
35
+ "pool_size": self.pool_size,
36
+ "host": credentials.host,
37
+ "port": credentials.port,
38
+ "database": credentials.database,
39
+ "user": credentials.username,
40
+ "password": credentials.password.get_secret_value(),
41
+ "connect_timeout": 10, # 10 seconds timeout
42
+ "use_pure": True, # Use pure Python implementation
43
+ }
44
+
45
+ # Add SSL configuration if available
46
+ if ssl_context:
47
+ pool_config.update(ssl_context)
48
+ logger.info("SSL/TLS connection enabled")
49
+
50
+ # Remove None values
51
+ pool_config = {k: v for k, v in pool_config.items() if v is not None}
52
+
53
+ self._pool = pooling.MySQLConnectionPool(**pool_config)
54
+ logger.info(f"Connection pool initialized with size {self.pool_size}")
55
+
56
+ except Error as e:
57
+ logger.error(f"Failed to initialize connection pool: {e}")
58
+ raise
59
+
60
+ def get_connection(self) -> Any:
61
+ """Get a connection from the pool"""
62
+ if self._pool is None:
63
+ raise RuntimeError("Pool not initialized. Call initialize_pool first.")
64
+
65
+ try:
66
+ connection = self._pool.get_connection()
67
+ logger.debug("Retrieved connection from pool")
68
+ return connection
69
+ except Error as e:
70
+ logger.error(f"Failed to get connection from pool: {e}")
71
+ raise
72
+
73
+ def close_all(self) -> None:
74
+ """Close all connections in the pool"""
75
+ if self._pool is not None:
76
+ try:
77
+ # Close all connections
78
+ self._pool._remove_connections()
79
+ logger.info("All connections in pool closed")
80
+ except Error as e:
81
+ logger.error(f"Error closing pool connections: {e}")
82
+ raise
83
+ finally:
84
+ self._pool = None