awslabs.mysql-mcp-server 0.0.1__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.
awslabs/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
4
+ # with the License. A copy of the License is located at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
9
+ # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
10
+ # and limitations under the License.
11
+
12
+ # This file is part of the awslabs namespace.
13
+ # It is intentionally minimal to support PEP 420 namespace packages.
@@ -0,0 +1,14 @@
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
4
+ # with the License. A copy of the License is located at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
9
+ # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
10
+ # and limitations under the License.
11
+
12
+ """awslabs.mysql_mcp_server"""
13
+
14
+ __version__ = '0.0.0'
@@ -0,0 +1,150 @@
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
4
+ # with the License. A copy of the License is located at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
9
+ # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
10
+ # and limitations under the License.
11
+
12
+ import re
13
+
14
+
15
+ # -- Mutating keyword set for quick string matching --
16
+ MUTATING_KEYWORDS = {
17
+ 'INSERT',
18
+ 'UPDATE',
19
+ 'DELETE',
20
+ 'REPLACE',
21
+ 'TRUNCATE',
22
+ 'CREATE',
23
+ 'DROP',
24
+ 'ALTER',
25
+ 'RENAME',
26
+ 'GRANT',
27
+ 'REVOKE',
28
+ 'LOAD DATA',
29
+ 'LOAD XML',
30
+ 'INSTALL PLUGIN',
31
+ 'UNINSTALL PLUGIN',
32
+ }
33
+
34
+ MUTATING_PATTERN = re.compile(
35
+ r'(?i)\b(' + '|'.join(re.escape(k) for k in MUTATING_KEYWORDS) + r')\b'
36
+ )
37
+
38
+ # -- Regex for DDL statements --
39
+ DDL_REGEX = re.compile(
40
+ r"""
41
+ ^\s*(
42
+ CREATE\s+(TABLE|VIEW|INDEX|TRIGGER|PROCEDURE|FUNCTION|EVENT)|
43
+ DROP\s+(TABLE|VIEW|INDEX|TRIGGER|PROCEDURE|FUNCTION|EVENT)|
44
+ ALTER\s+(TABLE|VIEW|TRIGGER|PROCEDURE|FUNCTION|EVENT)|
45
+ RENAME\s+(TABLE)|
46
+ TRUNCATE
47
+ )\b
48
+ """,
49
+ re.IGNORECASE | re.VERBOSE,
50
+ )
51
+
52
+ # -- Regex for permission-related statements --
53
+ PERMISSION_REGEX = re.compile(
54
+ r"""
55
+ ^\s*(
56
+ GRANT(\s+ROLE)?|
57
+ REVOKE(\s+ROLE)?|
58
+ CREATE\s+(USER|ROLE)|
59
+ DROP\s+(USER|ROLE)|
60
+ SET\s+DEFAULT\s+ROLE|
61
+ SET\s+PASSWORD|
62
+ ALTER\s+USER|
63
+ RENAME\s+USER
64
+ )\b
65
+ """,
66
+ re.IGNORECASE | re.VERBOSE,
67
+ )
68
+
69
+ # -- Regex for system/control-level operations --
70
+ SYSTEM_REGEX = re.compile(
71
+ r"""
72
+ ^\s*(
73
+ SET\s+(GLOBAL|PERSIST|SESSION)|
74
+ RESET\s+(PERSIST|MASTER|SLAVE)|
75
+ FLUSH\s+(PRIVILEGES|HOSTS|LOGS|STATUS|TABLES)?|
76
+ INSTALL\s+PLUGIN|UNINSTALL\s+PLUGIN|
77
+ CHANGE\s+MASTER\s+TO|
78
+ START\s+SLAVE|STOP\s+SLAVE|
79
+ SET\s+GTID_PURGED|
80
+ PURGE\s+BINARY\s+LOGS|
81
+ LOAD\s+DATA\s+INFILE|
82
+ SELECT\s+.*\s+INTO\s+OUTFILE|
83
+ USE\s+\w+|
84
+ SET\s+autocommit
85
+ )\b
86
+ """,
87
+ re.IGNORECASE | re.VERBOSE,
88
+ )
89
+
90
+ # -- Suspicious pattern detection (SQL injection, stacked queries, etc.) --
91
+ SUSPICIOUS_PATTERNS = [
92
+ r'--.*$', # single-line comment
93
+ r'/\*.*?\*/', # multi-line comment
94
+ r"(?i)'.*?--", # comment injection
95
+ r'(?i)\bor\b\s+\d+\s*=\s*\d+', # numeric tautology
96
+ r"(?i)\bor\b\s*'[^']+'\s*=\s*'[^']+'", # string tautology
97
+ r'(?i)\bunion\b.*\bselect\b', # UNION SELECT
98
+ r'(?i)\bdrop\b', # DROP
99
+ r'(?i)\btruncate\b', # TRUNCATE
100
+ r'(?i)\bgrant\b|\brevoke\b', # GRANT or REVOKE
101
+ r'(?i);', # stacked queries
102
+ r'(?i)\bsleep\s*\(', # time-based injection
103
+ r'(?i)\bload_file\s*\(', # file read
104
+ r'(?i)\binto\s+outfile\b', # file write
105
+ ]
106
+
107
+
108
+ def detect_mutating_keywords(sql: str) -> list[str]:
109
+ """Return a list of mutating keywords found in the SQL (excluding comments)."""
110
+ matched = []
111
+
112
+ if DDL_REGEX.search(sql):
113
+ matched.append('DDL')
114
+
115
+ if PERMISSION_REGEX.search(sql):
116
+ matched.append('PERMISSION')
117
+
118
+ if SYSTEM_REGEX.search(sql):
119
+ matched.append('SYSTEM')
120
+
121
+ # Match individual keywords from MUTATING_KEYWORDS
122
+ keyword_matches = MUTATING_PATTERN.findall(sql)
123
+ if keyword_matches:
124
+ # Deduplicate and normalize casing
125
+ matched.extend(sorted({k.upper() for k in keyword_matches}))
126
+
127
+ return matched
128
+
129
+
130
+ def check_sql_injection_risk(sql: str) -> list[dict]:
131
+ """Check for potential SQL injection risks in sql query.
132
+
133
+ Args:
134
+ sql: query string
135
+
136
+ Returns:
137
+ dictionaries containing detected security issue
138
+ """
139
+ issues = []
140
+ for pattern in SUSPICIOUS_PATTERNS:
141
+ if re.search(pattern, sql):
142
+ issues.append(
143
+ {
144
+ 'type': 'sql',
145
+ 'message': f'Suspicious pattern: {pattern}',
146
+ 'severity': 'high',
147
+ }
148
+ )
149
+ break
150
+ return issues
@@ -0,0 +1,374 @@
1
+ # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
4
+ # with the License. A copy of the License is located at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
9
+ # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
10
+ # and limitations under the License.
11
+
12
+ """awslabs mysql MCP Server implementation."""
13
+
14
+ import argparse
15
+ import asyncio
16
+ import boto3
17
+ import sys
18
+ from awslabs.mysql_mcp_server.mutable_sql_detector import (
19
+ check_sql_injection_risk,
20
+ detect_mutating_keywords,
21
+ )
22
+ from botocore.exceptions import BotoCoreError, ClientError
23
+ from loguru import logger
24
+ from mcp.server.fastmcp import Context, FastMCP
25
+ from pydantic import Field
26
+ from typing import Annotated, Any, Dict, List, Optional
27
+
28
+
29
+ client_error_code_key = 'run_query ClientError code'
30
+ unexpected_error_key = 'run_query unexpected error'
31
+ write_query_prohibited_key = 'Your MCP tool only allows readonly query. If you want to write, change the MCP configuration per README.md'
32
+ query_injection_risk_key = 'Your query contains risky injection patterns'
33
+
34
+
35
+ class DummyCtx:
36
+ """A dummy context class for error handling in MCP tools."""
37
+
38
+ async def error(self, message):
39
+ """Raise a runtime error with the given message.
40
+
41
+ Args:
42
+ message: The error message to include in the runtime error
43
+ """
44
+ # Do nothing
45
+ pass
46
+
47
+
48
+ class DBConnection:
49
+ """Class that wraps DB connection client by RDS API."""
50
+
51
+ def __init__(self, cluster_arn, secret_arn, database, region, readonly, is_test=False):
52
+ """Initialize a new DB connection.
53
+
54
+ Args:
55
+ cluster_arn: The ARN of the RDS cluster
56
+ secret_arn: The ARN of the secret containing credentials
57
+ database: The name of the database to connect to
58
+ region: The AWS region where the RDS instance is located
59
+ readonly: Whether the connection should be read-only
60
+ is_test: Whether this is a test connection
61
+ """
62
+ self.cluster_arn = cluster_arn
63
+ self.secret_arn = secret_arn
64
+ self.database = database
65
+ self.readonly = readonly
66
+ if not is_test:
67
+ self.data_client = boto3.client('rds-data', region_name=region)
68
+
69
+ @property
70
+ def readonly_query(self):
71
+ """Get whether this connection is read-only.
72
+
73
+ Returns:
74
+ bool: True if the connection is read-only, False otherwise
75
+ """
76
+ return self.readonly
77
+
78
+
79
+ class DBConnectionSingleton:
80
+ """Manages a single DBConnection instance across the application.
81
+
82
+ This singleton ensures that only one DBConnection is created and reused.
83
+ """
84
+
85
+ _instance = None
86
+
87
+ def __init__(self, resource_arn, secret_arn, database, region, readonly, is_test=False):
88
+ """Initialize a new DB connection singleton.
89
+
90
+ Args:
91
+ resource_arn: The ARN of the RDS resource
92
+ secret_arn: The ARN of the secret containing credentials
93
+ database: The name of the database to connect to
94
+ region: The AWS region where the RDS instance is located
95
+ readonly: Whether the connection should be read-only
96
+ is_test: Whether this is a test connection
97
+ """
98
+ if not all([resource_arn, secret_arn, database, region]):
99
+ raise ValueError(
100
+ 'Missing required connection parameters. '
101
+ 'Please provide resource_arn, secret_arn, database, and region.'
102
+ )
103
+ self._db_connection = DBConnection(
104
+ resource_arn, secret_arn, database, region, readonly, is_test
105
+ )
106
+
107
+ @classmethod
108
+ def initialize(cls, resource_arn, secret_arn, database, region, readonly, is_test=False):
109
+ """Initialize the singleton instance if it doesn't exist.
110
+
111
+ Args:
112
+ resource_arn: The ARN of the RDS resource
113
+ secret_arn: The ARN of the secret containing credentials
114
+ database: The name of the database to connect to
115
+ region: The AWS region where the RDS instance is located
116
+ readonly: Whether the connection should be read-only
117
+ is_test: Whether this is a test connection
118
+ """
119
+ if cls._instance is None:
120
+ cls._instance = cls(resource_arn, secret_arn, database, region, readonly, is_test)
121
+
122
+ @classmethod
123
+ def get(cls):
124
+ """Get the singleton instance.
125
+
126
+ Returns:
127
+ DBConnectionSingleton: The singleton instance
128
+
129
+ Raises:
130
+ RuntimeError: If the singleton has not been initialized
131
+ """
132
+ if cls._instance is None:
133
+ raise RuntimeError('DBConnectionSingleton is not initialized.')
134
+ return cls._instance
135
+
136
+ @property
137
+ def db_connection(self):
138
+ """Get the database connection.
139
+
140
+ Returns:
141
+ DBConnection: The database connection instance
142
+ """
143
+ return self._db_connection
144
+
145
+
146
+ def extract_cell(cell: dict):
147
+ """Extracts the scalar or array value from a single cell."""
148
+ if cell.get('isNull'):
149
+ return None
150
+ for key in (
151
+ 'stringValue',
152
+ 'longValue',
153
+ 'doubleValue',
154
+ 'booleanValue',
155
+ 'blobValue',
156
+ 'arrayValue',
157
+ ):
158
+ if key in cell:
159
+ return cell[key]
160
+ return None
161
+
162
+
163
+ def parse_execute_response(response: dict) -> list[dict]:
164
+ """Convert RDS Data API execute_statement response to list of rows."""
165
+ columns = [col['name'] for col in response.get('columnMetadata', [])]
166
+ records = []
167
+
168
+ for row in response.get('records', []):
169
+ row_data = {col: extract_cell(cell) for col, cell in zip(columns, row)}
170
+ records.append(row_data)
171
+
172
+ return records
173
+
174
+
175
+ mcp = FastMCP(
176
+ 'awslabs.mysql-mcp-server',
177
+ instructions='You are an expert MySQL assistant. Use run_query and get_table_schema to interfact with the database.',
178
+ dependencies=['loguru', 'boto3', 'pydantic'],
179
+ )
180
+
181
+
182
+ @mcp.tool(name='run_query', description='Run a SQL query against a MySQL database')
183
+ async def run_query(
184
+ sql: Annotated[str, Field(description='The SQL query to run')],
185
+ ctx: Context,
186
+ db_connection=None,
187
+ query_parameters: Annotated[
188
+ Optional[List[Dict[str, Any]]], Field(description='Parameters for the SQL query')
189
+ ] = None,
190
+ ) -> list[dict]: # type: ignore
191
+ """Run a SQL query against a MySQL database.
192
+
193
+ Args:
194
+ sql: The sql statement to run
195
+ ctx: MCP context for logging and state management
196
+ db_connection: DB connection object passed by unit test. It should be None if if called by MCP server.
197
+ query_parameters: Parameters for the SQL query
198
+
199
+ Returns:
200
+ List of dictionary that contains query response rows
201
+ """
202
+ global client_error_code_key
203
+ global unexpected_error_key
204
+ global write_query_prohibited_key
205
+
206
+ if db_connection is None:
207
+ db_connection = DBConnectionSingleton.get().db_connection
208
+
209
+ if db_connection.readonly_query:
210
+ matches = detect_mutating_keywords(sql)
211
+ if (bool)(matches):
212
+ logger.info(
213
+ f'query is rejected because current setting only allows readonly query. detected keywords: {matches}, SQL query: {sql}'
214
+ )
215
+
216
+ await ctx.error(write_query_prohibited_key)
217
+ return [{'error': write_query_prohibited_key}]
218
+
219
+ issues = check_sql_injection_risk(sql)
220
+ if issues:
221
+ logger.info(
222
+ f'query is rejected because it contains risky SQL pattern, SQL query: {sql}, reasons: {issues}'
223
+ )
224
+ await ctx.error(
225
+ str({'message': 'Query parameter contains suspicious pattern', 'details': issues})
226
+ )
227
+ return [{'error': query_injection_risk_key}]
228
+
229
+ try:
230
+ logger.info(f'run_query: readonly:{db_connection.readonly_query}, SQL:{sql}')
231
+
232
+ execute_params = {
233
+ 'resourceArn': db_connection.cluster_arn,
234
+ 'secretArn': db_connection.secret_arn,
235
+ 'database': db_connection.database,
236
+ 'sql': sql,
237
+ 'includeResultMetadata': True,
238
+ }
239
+
240
+ if query_parameters:
241
+ execute_params['parameters'] = query_parameters
242
+
243
+ response = await asyncio.to_thread(
244
+ db_connection.data_client.execute_statement, **execute_params
245
+ )
246
+
247
+ logger.success('run_query successfully executed query:{}', sql)
248
+ return parse_execute_response(response)
249
+ except ClientError as e:
250
+ logger.exception(client_error_code_key)
251
+ await ctx.error(
252
+ str({'code': e.response['Error']['Code'], 'message': e.response['Error']['Message']})
253
+ )
254
+ return [{'error': client_error_code_key}]
255
+ except Exception as e:
256
+ logger.exception(unexpected_error_key)
257
+ error_details = f'{type(e).__name__}: {str(e)}'
258
+ await ctx.error(str({'message': error_details}))
259
+ return [{'error': unexpected_error_key}]
260
+
261
+
262
+ @mcp.tool(
263
+ name='get_table_schema',
264
+ description='Fetch table schema from the MySQL database',
265
+ )
266
+ async def get_table_schema(
267
+ table_name: Annotated[str, Field(description='name of the table')],
268
+ database_name: Annotated[str, Field(description='name of the database')],
269
+ ctx: Context,
270
+ ) -> list[dict]:
271
+ """Get a table's schema information given the table name.
272
+
273
+ Args:
274
+ table_name: name of the table
275
+ database_name: name of the database
276
+ ctx: MCP context for logging and state management
277
+
278
+ Returns:
279
+ List of dictionary that contains query response rows
280
+ """
281
+ logger.info(f'get_table_schema: {table_name}')
282
+
283
+ sql = """
284
+ SELECT
285
+ COLUMN_NAME,
286
+ COLUMN_TYPE,
287
+ IS_NULLABLE,
288
+ COLUMN_DEFAULT,
289
+ EXTRA,
290
+ COLUMN_KEY,
291
+ COLUMN_COMMENT
292
+ FROM
293
+ information_schema.columns
294
+ WHERE
295
+ table_schema = :database_name
296
+ AND table_name = :table_name
297
+ ORDER BY
298
+ ORDINAL_POSITION
299
+ """
300
+ params = [
301
+ {'name': 'table_name', 'value': {'stringValue': table_name}},
302
+ {'name': 'database_name', 'value': {'stringValue': database_name}},
303
+ ]
304
+
305
+ return await run_query(sql=sql, ctx=ctx, query_parameters=params)
306
+
307
+
308
+ def main():
309
+ """Main entry point for the MCP server application."""
310
+ global client_error_code_key
311
+
312
+ """Run the MCP server with CLI argument support."""
313
+ parser = argparse.ArgumentParser(
314
+ description='An AWS Labs Model Context Protocol (MCP) server for MySQL'
315
+ )
316
+ parser.add_argument('--sse', action='store_true', help='Use SSE transport')
317
+ parser.add_argument('--port', type=int, default=8888, help='Port to run the server on')
318
+ parser.add_argument('--resource_arn', required=True, help='ARN of the RDS cluster')
319
+ parser.add_argument(
320
+ '--secret_arn',
321
+ required=True,
322
+ help='ARN of the Secrets Manager secret for database credentials',
323
+ )
324
+ parser.add_argument('--database', required=True, help='Database name')
325
+ parser.add_argument(
326
+ '--region', required=True, help='AWS region for RDS Data API (default: us-west-2)'
327
+ )
328
+ parser.add_argument(
329
+ '--readonly', required=True, help='Enforce NL to SQL to only allow readonly sql statement'
330
+ )
331
+ args = parser.parse_args()
332
+
333
+ logger.info(
334
+ 'MySQL MCP init with CLUSTER_ARN:{}, SECRET_ARN:{}, REGION:{}, DATABASE:{}, READONLY:{}',
335
+ args.resource_arn,
336
+ args.secret_arn,
337
+ args.region,
338
+ args.database,
339
+ args.readonly,
340
+ )
341
+
342
+ try:
343
+ DBConnectionSingleton.initialize(
344
+ args.resource_arn, args.secret_arn, args.database, args.region, args.readonly
345
+ )
346
+ except BotoCoreError:
347
+ logger.exception('Failed to RDS API client object for MySQL. Exit the MCP server')
348
+ sys.exit(1)
349
+
350
+ # Test RDS API connection
351
+ ctx = DummyCtx()
352
+ response = asyncio.run(run_query('SELECT 1', ctx))
353
+ if (
354
+ isinstance(response, list)
355
+ and len(response) == 1
356
+ and isinstance(response[0], dict)
357
+ and 'error' in response[0]
358
+ ):
359
+ logger.error('Failed to validate RDS API db connection to MySQL. Exit the MCP server')
360
+ sys.exit(1)
361
+
362
+ logger.success('Successfully validated RDS API db connection to MySQL')
363
+
364
+ # Run server with appropriate transport
365
+ if args.sse:
366
+ mcp.settings.port = args.port
367
+ mcp.run(transport='sse')
368
+ else:
369
+ logger.info('Starting MySQL MCP server')
370
+ mcp.run()
371
+
372
+
373
+ if __name__ == '__main__':
374
+ main()
@@ -0,0 +1,125 @@
1
+ Metadata-Version: 2.4
2
+ Name: awslabs.mysql-mcp-server
3
+ Version: 0.0.1
4
+ Summary: An AWS Labs Model Context Protocol (MCP) server for mysql
5
+ Project-URL: homepage, https://awslabs.github.io/mcp/
6
+ Project-URL: docs, https://awslabs.github.io/mcp/servers/mysql-mcp-server/
7
+ Project-URL: documentation, https://awslabs.github.io/mcp/servers/mysql-mcp-server/
8
+ Project-URL: repository, https://github.com/awslabs/mcp.git
9
+ Project-URL: changelog, https://github.com/awslabs/mcp/blob/main/src/mysql-mcp-server/CHANGELOG.md
10
+ Author: Amazon Web Services
11
+ Author-email: AWSLabs MCP <203918161+awslabs-mcp@users.noreply.github.com>, Ken Zhang <kennthhz@amazon.com>
12
+ License: Apache-2.0
13
+ License-File: LICENSE
14
+ License-File: NOTICE
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Programming Language :: Python :: 3.13
23
+ Requires-Python: >=3.10
24
+ Requires-Dist: boto3>=1.38.14
25
+ Requires-Dist: botocore>=1.38.14
26
+ Requires-Dist: loguru>=0.7.0
27
+ Requires-Dist: mcp[cli]>=1.6.0
28
+ Requires-Dist: pydantic>=2.10.6
29
+ Description-Content-Type: text/markdown
30
+
31
+ # AWS Labs MySQL MCP Server
32
+
33
+ An AWS Labs Model Context Protocol (MCP) server for Aurora MySQL
34
+
35
+ ## Features
36
+
37
+ ### Natural language to MySQL SQL query
38
+
39
+ - Converting human-readable questions and commands into structured MySQL-compatible SQL queries and executing them against the configured Aurora MySQL database.
40
+
41
+ ## Prerequisites
42
+
43
+ 1. Install `uv` from [Astral](https://docs.astral.sh/uv/getting-started/installation/) or the [GitHub README](https://github.com/astral-sh/uv#installation)
44
+ 2. Install Python using `uv python install 3.10`
45
+ 3. Aurora MySQL Cluster with MySQL username and password stored in AWS Secrets Manager
46
+ 4. Enable RDS Data API for your Aurora MySQL Cluster, see [instructions here](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html)
47
+ 5. This MCP server can only be run locally on the same host as your LLM client.
48
+ 6. Docker runtime
49
+ 7. Set up AWS credentials with access to AWS services
50
+ - You need an AWS account with appropriate permissions
51
+ - Configure AWS credentials with `aws configure` or environment variables
52
+
53
+ ## Installation
54
+
55
+ Here are some ways you can work with MCP across AWS, and we'll be adding support to more products including Amazon Q Developer CLI soon: (e.g. for Amazon Q Developer CLI MCP, `~/.aws/amazonq/mcp.json`):
56
+
57
+ ```json
58
+ {
59
+ "mcpServers": {
60
+ "awslabs.mysql-mcp-server": {
61
+ "command": "uvx",
62
+ "args": [
63
+ "awslabs.mysql-mcp-server@latest",
64
+ "--resource_arn", "[your data]",
65
+ "--secret_arn", "[your data]",
66
+ "--database", "[your data]",
67
+ "--region", "[your data]",
68
+ "--readonly", "True"
69
+ ],
70
+ "env": {
71
+ "AWS_PROFILE": "your-aws-profile",
72
+ "AWS_REGION": "us-east-1",
73
+ "FASTMCP_LOG_LEVEL": "ERROR"
74
+ },
75
+ "disabled": false,
76
+ "autoApprove": []
77
+ }
78
+ }
79
+ }
80
+ ```
81
+
82
+ ### Build and install docker image locally on the same host of your LLM client
83
+
84
+ 1. 'git clone https://github.com/awslabs/mcp.git'
85
+ 2. Go to sub-directory 'src/mysql-mcp-server/'
86
+ 3. Run 'docker build -t awslabs/mysql-mcp-server:latest .'
87
+
88
+ ### Add or update your LLM client's config with following:
89
+ <pre><code>
90
+ {
91
+ "mcpServers": {
92
+ "awslabs.mysql-mcp-server": {
93
+ "command": "docker",
94
+ "args": [
95
+ "run",
96
+ "-i",
97
+ "--rm",
98
+ "-e", "AWS_ACCESS_KEY_ID=[your data]",
99
+ "-e", "AWS_SECRET_ACCESS_KEY=[your data]",
100
+ "-e", "AWS_REGION=[your data]",
101
+ "awslabs/mysql-mcp-server:latest",
102
+ "--resource_arn", "[your data]",
103
+ "--secret_arn", "[your data]",
104
+ "--database", "[your data]",
105
+ "--region", "[your data]",
106
+ "--readonly", "True"
107
+ ]
108
+ }
109
+ }
110
+ }
111
+ </code></pre>
112
+
113
+ NOTE: By default, only read-only queries are allowed and it is controlled by --readonly parameter above. Set it to False if you also want to allow writable DML or DDL.
114
+
115
+ ### AWS Authentication
116
+
117
+ The MCP server uses the AWS profile specified in the `AWS_PROFILE` environment variable. If not provided, it defaults to the "default" profile in your AWS configuration file.
118
+
119
+ ```json
120
+ "env": {
121
+ "AWS_PROFILE": "your-aws-profile"
122
+ }
123
+ ```
124
+
125
+ Make sure the AWS profile has permissions to access the [RDS data API](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/data-api.html#data-api.access), and the secret from AWS Secrets Manager. The MCP server creates a boto3 session using the specified profile to authenticate with AWS services. Your AWS IAM credentials remain on your local machine and are strictly used for accessing AWS services.
@@ -0,0 +1,10 @@
1
+ awslabs/__init__.py,sha256=47wJeKcStxEJwX7SVVV2pnAWYR8FxcaYoT3YTmZ5Plg,674
2
+ awslabs/mysql_mcp_server/__init__.py,sha256=_BajTXfPB4ubIrro0PBWJrVdwecctN3j2BaUo18DdL4,613
3
+ awslabs/mysql_mcp_server/mutable_sql_detector.py,sha256=iaZZz1_p2VRBkJPclcGMSUU51Vo70lDMK_o2fntvQ5w,4162
4
+ awslabs/mysql_mcp_server/server.py,sha256=H51EjatD4CudZvIaH7SfxS9Dc31DSqwBzDtty8CoKyY,12722
5
+ awslabs_mysql_mcp_server-0.0.1.dist-info/METADATA,sha256=fCj0xCeS-uhRPBLt96bLdgXB5nMW3j68QuLQuTUPD6E,4842
6
+ awslabs_mysql_mcp_server-0.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
7
+ awslabs_mysql_mcp_server-0.0.1.dist-info/entry_points.txt,sha256=dQAG1BpfKE6diUKtCqzxwvWfPxDWGIEa87YcEb0T4rc,82
8
+ awslabs_mysql_mcp_server-0.0.1.dist-info/licenses/LICENSE,sha256=CeipvOyAZxBGUsFoaFqwkx54aPnIKEtm9a5u2uXxEws,10142
9
+ awslabs_mysql_mcp_server-0.0.1.dist-info/licenses/NOTICE,sha256=lpdr2_2JGgD-RqTEnqMJttKCZVvC88gX4rbk0m8UifU,92
10
+ awslabs_mysql_mcp_server-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ awslabs.mysql-mcp-server = awslabs.mysql_mcp_server.server:main
@@ -0,0 +1,175 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
@@ -0,0 +1,2 @@
1
+ awslabs.mysql-mcp-server
2
+ Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.