iflow-mcp_yugabyte-yugabytedb-mcp-server 1.0.3__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,318 @@
1
+ Metadata-Version: 2.4
2
+ Name: iflow-mcp_yugabyte-yugabytedb-mcp-server
3
+ Version: 1.0.3
4
+ Summary: Add your description here
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: mcp[cli]>=1.9.4
9
+ Requires-Dist: httpx~=0.28.0
10
+ Requires-Dist: fastapi>=0.115.12
11
+ Requires-Dist: psycopg2-binary>=2.9.10
12
+ Requires-Dist: boto3>=1.42.37
13
+ Dynamic: license-file
14
+
15
+ # YugabyteDB MCP Server
16
+
17
+ An [MCP](https://modelcontextprotocol.io/) server implementation for YugabyteDB that allows LLMs to directly interact with your database.
18
+
19
+ ## Features
20
+
21
+ - List all tables in the database, including schema and row counts
22
+ - Run read-only SQL queries and return results as JSON
23
+ - Designed for use with [FastMCP](https://github.com/jlowin/fastmcp) and compatible with MCP clients like Claude Desktop, Cursor, and Windsurf Editor
24
+
25
+ ## Prerequisites
26
+
27
+ - Python 3.10 or higher
28
+ - [uv](https://docs.astral.sh/uv/) installed to manage and run the server
29
+ - A running YugabyteDB database
30
+ - An [MCP client](https://modelcontextprotocol.io/clients) such as [Claude Desktop](https://claude.ai/download) or [Cursor](https://cursor.sh/)
31
+
32
+ ## Installation
33
+
34
+ Clone this repository and install dependencies:
35
+
36
+ ```bash
37
+ git clone git@github.com:yugabyte/yugabytedb-mcp-server.git
38
+ cd yugabytedb-mcp-server
39
+ uv sync
40
+ ```
41
+
42
+ ## Configuration
43
+
44
+ The server is configured using the following:
45
+
46
+ | Environment Variable | Argument | Optional | Description |
47
+ |----------------------|----------|----------|-------------|
48
+ | `YUGABYTEDB_URL` | `--yugabytedb-url` | No | Connection string for your YugabyteDB database (e.g., `dbname=database_name host=hostname port=5433 user=username password=password`) |
49
+ | `YB_MCP_TRANSPORT` | `--transport` | Yes | Transport protocol to use: `stdio` or `http` (default: `stdio`) |
50
+ | `YB_MCP_STATELESS_HTTP` | `--stateless-http`| Yes | Enable stateless Streamable-HTTP mode: `true` or `false` (default: `false`) |
51
+ | `YB_AWS_SSL_ROOT_CERT_SECRET_ARN` | `--yb-aws-ssl-root-cert-secret-arn` | Yes | ARN of the AWS Secrets Manager secret containing the TLS root certificate |
52
+ | `YB_AWS_SSL_ROOT_CERT_KEY` | `--yb-aws-ssl-root-cert-key` | Yes | Key inside the secret JSON that selects which certificate to use |
53
+ | `YB_SSL_ROOT_CERT_PATH` | `--yb-ssl-root-cert-path` | Yes | Filesystem path where the root certificate will be written (default: `/tmp/yb-root.crt`) |
54
+ | `YB_AWS_SSL_ROOT_CERT_SECRET_REGION` | `--yb-aws-ssl-root-cert-secret-region` | Yes | Region of the AWS Secrets Manager secret containing the TLS root certificate |
55
+
56
+
57
+ ## Usage
58
+
59
+ ### Running the Server
60
+
61
+ You can run the server with `STDIO` transport using uv:
62
+
63
+ ```bash
64
+ uv run src/server.py
65
+ ```
66
+
67
+
68
+ or with stateful `Streamable-HTTP` transport:
69
+
70
+ ```bash
71
+ uv run src/server.py --transport http
72
+ ```
73
+
74
+ or with stateless `Streamable-HTTP` transport:
75
+
76
+ ```bash
77
+ uv run src/server.py --transport http --stateless-http
78
+ ```
79
+
80
+ ### Running the Server with Docker
81
+
82
+ Build the Docker image:
83
+
84
+ ```bash
85
+ docker build -t mcp/yugabytedb .
86
+ ```
87
+
88
+ Run the container with `STDIO` transport:
89
+
90
+ ```bash
91
+ docker run -p 8000:8000 -e YUGABYTEDB_URL="your-db-url" mcp/yugabytedb
92
+ ```
93
+
94
+ or with `Streamable-HTTP` transport:
95
+
96
+ Stateful Server:
97
+ ```bash
98
+ docker run -p 8000:8000 \
99
+ -e YUGABYTEDB_URL="your-db-url" \
100
+ mcp/yugabytedb --transport=http
101
+
102
+ ```
103
+ Stateless Server:
104
+ ```bash
105
+ docker run -p 8000:8000 \
106
+ -e YUGABYTEDB_URL="your-db-url" \
107
+ -e YB_MCP_TRANSPORT=http \
108
+ -e YB_MCP_STATELESS_HTTP=true \
109
+ mcp/yugabytedb
110
+
111
+ ```
112
+ Stateless Server with SSL enabled cluster:
113
+ ```bash
114
+ docker run -p 8000:8000 \
115
+ -v /path/to/root.crt:/certs/root.crt:ro \
116
+ -e YUGABYTEDB_URL="your-db-url" \
117
+ mcp/yugabytedb \
118
+ --transport=http \
119
+ --stateless-http
120
+
121
+ ```
122
+
123
+ ### Running with TLS Certificates from AWS Secrets Manager
124
+
125
+ If your YugabyteDB cluster has TLS enabled and its root certificate is stored in AWS Secrets Manager, the MCP server can automatically fetch and configure it.
126
+
127
+ #### Plaintext secret (PEM stored directly)
128
+
129
+ The secret value contains the PEM certificate itself.
130
+
131
+ ```bash
132
+ docker run -p 8000:8000 \
133
+ -e YUGABYTEDB_URL="host=... port=5433 dbname=... user=... password=... sslmode=verify-full" \
134
+ -e YB_MCP_TRANSPORT=http \
135
+ -e YB_MCP_STATELESS_HTTP=true \
136
+ -e YB_AWS_SSL_ROOT_CERT_SECRET_ARN=arn:ofthe:secret:manager \
137
+ -e YB_AWS_SSL_ROOT_CERT_SECRET_REGION=region-of-the-secret-manager \
138
+ -e AWS_ACCESS_KEY_ID="XXX" \
139
+ -e AWS_SECRET_ACCESS_KEY="XXX" \
140
+ -e AWS_SESSION_TOKEN="XXX" \
141
+ mcp/yugabytedb
142
+ ```
143
+
144
+ #### JSON secret (multiple certificates in one secret)
145
+ The secret value is JSON, for example:
146
+
147
+ ```json
148
+
149
+ {
150
+ "cert-cluster-1": "-----BEGIN CERTIFICATE----- ...",
151
+ "cert-cluster-2": "-----BEGIN CERTIFICATE----- ..."
152
+ }
153
+ ```
154
+ Select which certificate to use:
155
+
156
+ ```bash
157
+ docker run -p 8000:8000 \
158
+ -e YUGABYTEDB_URL="host=... port=5433 dbname=... user=... password=... sslmode=verify-full" \
159
+ -e YB_MCP_TRANSPORT=http \
160
+ -e YB_MCP_STATELESS_HTTP=true \
161
+ -e YB_AWS_SSL_ROOT_CERT_SECRET_ARN=arn:ofthe:secret:manager \
162
+ -e YB_AWS_SSL_ROOT_CERT_KEY=cert-cluster-1 \
163
+ -e YB_AWS_SSL_ROOT_CERT_SECRET_REGION=region-of-the-secret-manager \
164
+ -e AWS_ACCESS_KEY_ID="XXX" \
165
+ -e AWS_SECRET_ACCESS_KEY="XXX" \
166
+ -e AWS_SESSION_TOKEN="XXX" \
167
+ mcp/yugabytedb
168
+ ```
169
+ By default the certificate is written to /tmp/yb-root.crt.
170
+ You can override this using:
171
+
172
+ ```bash
173
+ -e YB_SSL_ROOT_CERT_PATH=/custom/path/root.crt
174
+ ```
175
+
176
+ ### MCP Client Configuration
177
+
178
+ To use this server with an MCP client (e.g., Claude Desktop, Cursor), add it to your MCP client configuration.
179
+
180
+ #### Running via `uv`
181
+
182
+ Example configuration for Cursor:
183
+
184
+ ```json
185
+ {
186
+ "mcpServers": {
187
+ "yugabytedb-mcp": {
188
+ "command": "uv",
189
+ "args": [
190
+ "--directory",
191
+ "/path/to/cloned/yugabytedb-mcp-server/",
192
+ "run",
193
+ "src/server.py"
194
+ ],
195
+ "env": {
196
+ "YUGABYTEDB_URL": "dbname=database_name host=hostname port=5433 user=username password=password load_balance=true topology_keys=cloud.region.zone1,cloud.region.zone2"
197
+ }
198
+ }
199
+ }
200
+ }
201
+ ```
202
+
203
+ - Replace `/path/to/cloned/yugabytedb-mcp-server/` with the path to your cloned repository.
204
+ - Set the correct database URL in the `env` section.
205
+
206
+ #### Running via Docker (e.g., in Claude)
207
+
208
+ After building the docker container, add the following to `claude_config.json` entry or equivalent json files for other editors:
209
+
210
+ ```json
211
+ {
212
+ "mcpServers": {
213
+ "yugabytedb-mcp-docker": {
214
+ "command": "docker",
215
+ "args": [
216
+ "run",
217
+ "--rm",
218
+ "-i",
219
+ "-e",
220
+ "YUGABYTEDB_URL=dbname=yugabyte host=host.docker.internal port=5433 user=yugabyte password=yugabyte load_balance=false",
221
+ "mcp/yugabytedb"
222
+ ]
223
+ }
224
+ }
225
+ }
226
+ ```
227
+
228
+ ### Claude Desktop
229
+
230
+ 1. Edit the configuration file. Go to Claude -> Settings -> Developer -> Edit Config
231
+ 2. Add the above configuration under `mcpServers`.
232
+ 3. Restart Claude Desktop.
233
+
234
+ #### Claude Desktop Logs
235
+
236
+ The logs for Claude Desktop can be found in the following locations:
237
+
238
+ - MacOS: ~/Library/Logs/Claude
239
+ - Windows: %APPDATA%\Claude\Logs
240
+
241
+ The logs can be used to diagnose connection issues or other problems with your MCP server configuration. For more details, refer to the [official documentation](https://modelcontextprotocol.io/quickstart/user#getting-logs-from-claude-for-desktop).
242
+
243
+ ### Cursor
244
+
245
+ 1. Install [Cursor](https://cursor.sh/) on your machine.
246
+ 2. Go to Cursor > Settings > Cursor Settings > MCP > Add a new global MCP server.
247
+ 3. Add the configuration as above.
248
+ 4. Save the configuration.
249
+ 5. You will see yugabytedb-mcp-server as an added server in MCP servers list. Refresh to see if server is enabled.
250
+
251
+ #### Cursor Logs
252
+
253
+ In the bottom panel of Cursor, click on "Output" and select "Cursor MCP" from the dropdown menu to view server logs. This can help diagnose connection issues or other problems with your MCP server configuration.
254
+
255
+ ### Windsurf Editor
256
+
257
+ 1. Install [Windsurf Editor](https://windsurf.com/download) on your machine.
258
+ 2. Go to Windsurf > Settings > Windsurf Settings > Cascade > Model Context Protocol (MCP) Servers > Add server > Add custom server.
259
+ 3. Add the configuration as above.
260
+ 4. Save and refresh.
261
+
262
+ ### Streamable-HTTP with MCP Inspector
263
+
264
+ 1. Start the server using Streamable-HTTP:
265
+ ```bash
266
+ uv run src/server.py --transport http
267
+ ```
268
+
269
+ Or with Docker:
270
+
271
+ ```bash
272
+ docker run -p 8000:8000 -e YUGABYTEDB_URL="..." mcp/yugabytedb --transport=http
273
+ ```
274
+
275
+ 2. Launch the inspector:
276
+ ```bash
277
+ npx @modelcontextprotocol/inspector
278
+ ```
279
+
280
+ 3. In the GUI, use the URL:
281
+
282
+ ```
283
+ http://localhost:8000/mcp
284
+ ```
285
+
286
+ - Change transport type to `Streamable-HTTP`
287
+ - Add the proxy token from the terminal output
288
+
289
+ ### Tools Provided
290
+
291
+ - **summarize_database**: Lists all tables in the database, including schema and row counts.
292
+ - **run_read_only_query**: Runs a read-only SQL query and returns the results as JSON.
293
+
294
+ ### Example Usage
295
+
296
+ Once connected via an MCP client, you can:
297
+ - Ask for a summary of the database tables and schemas
298
+ - Run SELECT queries and get results in JSON
299
+
300
+ ## Environment Variables
301
+
302
+ - `YUGABYTEDB_URL`: (required) The connection string for your YugabyteDB/PostgreSQL database
303
+
304
+ ## Troubleshooting
305
+
306
+ - Ensure the `YUGABYTEDB_URL` is set and correct
307
+ - Verify your database is running and accessible
308
+ - Check that your user has the necessary permissions
309
+ - Make sure `uv` is installed and available in your PATH. Note: If claude is unable to access uv, giving the error: `spawn uv ENOENT`, try symlinking the uv for global access:
310
+ ```shell
311
+ sudo ln -s "$(which uv)" /usr/local/bin/uv
312
+ ```
313
+ - Review logs in your MCP client for connection or query errors
314
+
315
+ ## Development
316
+
317
+ - Project dependencies are managed in `pyproject.toml`
318
+ - Main server logic is in `src/server.py`
@@ -0,0 +1,7 @@
1
+ server.py,sha256=bc2juN3YT-P6yla0kglOyxeEAvpM4mcAqz_ySgUzwDc,9567
2
+ iflow_mcp_yugabyte_yugabytedb_mcp_server-1.0.3.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
3
+ iflow_mcp_yugabyte_yugabytedb_mcp_server-1.0.3.dist-info/METADATA,sha256=RHm9yfD5pPEv1VWSW4RinmmfCxSY9hy-vVxCbDI7bqY,9655
4
+ iflow_mcp_yugabyte_yugabytedb_mcp_server-1.0.3.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
5
+ iflow_mcp_yugabyte_yugabytedb_mcp_server-1.0.3.dist-info/entry_points.txt,sha256=0qR8G3C-z5Jb99iC45ysBZsnVGYgPefWGinP2Bhq9hE,54
6
+ iflow_mcp_yugabyte_yugabytedb_mcp_server-1.0.3.dist-info/top_level.txt,sha256=StKOSmRhvWS5IPcvhsDRbtxUTEofJgYFGOu5AAJdSWo,7
7
+ iflow_mcp_yugabyte_yugabytedb_mcp_server-1.0.3.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.10.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ yugabytedb_mcp_server = 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.
server.py ADDED
@@ -0,0 +1,278 @@
1
+ # server.py
2
+ import json
3
+ import os
4
+ import sys
5
+ import argparse
6
+ import psycopg2
7
+ from typing import List, Dict, Any, AsyncIterator
8
+ from dataclasses import dataclass
9
+ from contextlib import asynccontextmanager, AsyncExitStack
10
+ from mcp.server.fastmcp import FastMCP, Context
11
+ import uvicorn
12
+ from fastapi import FastAPI
13
+ from starlette.responses import JSONResponse
14
+ import boto3
15
+
16
+ @dataclass
17
+ class AppContext:
18
+ conn: psycopg2.extensions.connection | None = None
19
+
20
+ @dataclass
21
+ class ServerConfig:
22
+ yugabytedb_url: str
23
+ transport: str
24
+ stateless_http: bool
25
+ ssl_root_cert_secret_arn: str | None
26
+ ssl_root_cert_key: str | None
27
+ ssl_root_cert_path: str
28
+ ssl_root_cert_secret_region: str
29
+
30
+ def normalize_pem(pem: str) -> str:
31
+ # Remove surrounding spaces
32
+ pem = pem.strip()
33
+
34
+ # Fix cases where newlines were replaced by spaces
35
+ pem = pem.replace("-----BEGIN CERTIFICATE----- ", "-----BEGIN CERTIFICATE-----\n")
36
+ pem = pem.replace(" -----END CERTIFICATE-----", "\n-----END CERTIFICATE-----")
37
+
38
+ # Also fix intermediate blocks
39
+ pem = pem.replace("-----END CERTIFICATE----- -----BEGIN CERTIFICATE-----",
40
+ "-----END CERTIFICATE-----\n\n-----BEGIN CERTIFICATE-----")
41
+
42
+ return pem + "\n"
43
+
44
+
45
+ def write_root_cert(config: ServerConfig):
46
+ if not config.ssl_root_cert_secret_arn:
47
+ return None
48
+
49
+ try:
50
+ sm = boto3.client("secretsmanager", region_name=config.ssl_root_cert_secret_region)
51
+ resp = sm.get_secret_value(SecretId=config.ssl_root_cert_secret_arn)
52
+ secret_string = resp["SecretString"]
53
+
54
+ # If raw PEM, just use it
55
+ if "BEGIN CERTIFICATE" in secret_string and not secret_string.strip().startswith("{"):
56
+ pem = secret_string
57
+ else:
58
+ data = json.loads(secret_string)
59
+
60
+ if config.ssl_root_cert_key:
61
+ if config.ssl_root_cert_key not in data:
62
+ raise RuntimeError(f"Certificate key '{config.ssl_root_cert_key}' not found in secret")
63
+ pem = data[config.ssl_root_cert_key]
64
+ else:
65
+ # Backward-compatible: allow exactly one entry
66
+ if len(data) != 1:
67
+ raise RuntimeError(
68
+ "Multiple certificates found in secret; set YB_AWS_SSL_ROOT_CERT_KEY to select one"
69
+ )
70
+ pem = next(iter(data.values()))
71
+
72
+ pem = normalize_pem(pem)
73
+ with open(config.ssl_root_cert_path, "w") as f:
74
+ f.write(pem.strip() + "\n")
75
+
76
+ return config.ssl_root_cert_path
77
+
78
+ except Exception as e:
79
+ print(f"Failed to load root cert from Secrets Manager: {e}", file=sys.stderr)
80
+ raise
81
+
82
+
83
+ @asynccontextmanager
84
+ async def app_lifespan(server: FastMCP, config: ServerConfig) -> AsyncIterator[AppContext]:
85
+ # Skip database connection for testing if YUGABYTEDB_URL is not set
86
+ if not config.yugabytedb_url:
87
+ print("YUGABYTEDB_URL is not set, running in demo mode without database connection", file=sys.stderr)
88
+ yield AppContext(conn=None)
89
+ return
90
+
91
+ print("Connecting to database...", file=sys.stderr)
92
+ database_url = config.yugabytedb_url
93
+ cert_path = write_root_cert(config)
94
+ if cert_path and "sslrootcert" not in database_url:
95
+ database_url += f" sslrootcert={cert_path}"
96
+ conn = psycopg2.connect(database_url)
97
+ try:
98
+ yield AppContext(conn=conn)
99
+ finally:
100
+ print("Closing database connection...", file=sys.stderr)
101
+ conn.close()
102
+
103
+
104
+ def summarize_database(ctx: Context, schema: str = "public") -> List[Dict[str, Any]]:
105
+ """
106
+ Summarize the database: list tables with schema and row counts.
107
+ """
108
+ summary = []
109
+ # Get config from context
110
+ config = ctx.request_context.lifespan_context.config
111
+ conn = ctx.request_context.lifespan_context.conn
112
+
113
+ # If no database connection, return demo data
114
+ if conn is None:
115
+ return [{"error": "No database connection configured. Please set YUGABYTEDB_URL environment variable."}]
116
+
117
+ with conn.cursor() as cur:
118
+ try:
119
+ cur.execute("""
120
+ SELECT table_name
121
+ FROM information_schema.tables
122
+ WHERE table_schema = %s
123
+ ORDER BY table_name
124
+ """, (schema,))
125
+ tables = [row[0] for row in cur.fetchall()]
126
+
127
+ for table in tables:
128
+ cur.execute("""
129
+ SELECT column_name, data_type
130
+ FROM information_schema.columns
131
+ WHERE table_schema = %s AND table_name = %s
132
+ ORDER BY ordinal_position
133
+ """, (schema, table,))
134
+ schema_info = [{"column_name": col, "data_type": dtype} for col, dtype in cur.fetchall()]
135
+
136
+ cur.execute(f"SELECT COUNT(*) FROM {schema}.\"{table}\"")
137
+ row_count = cur.fetchone()[0]
138
+
139
+ summary.append({
140
+ "table": table,
141
+ "row_count": row_count,
142
+ "schema": schema_info
143
+ })
144
+
145
+ except Exception as e:
146
+ summary.append({"error": str(e)})
147
+
148
+ return summary
149
+
150
+
151
+ def run_read_only_query(ctx: Context, query: str) -> str:
152
+ """
153
+ Run a read-only SQL query and return the results as JSON.
154
+ """
155
+ conn = ctx.request_context.lifespan_context.conn
156
+
157
+ # If no database connection, return error message
158
+ if conn is None:
159
+ return json.dumps({"error": "No database connection configured. Please set YUGABYTEDB_URL environment variable."}, indent=2)
160
+
161
+ with conn.cursor() as cur:
162
+ try:
163
+ cur.execute("BEGIN READ ONLY")
164
+ cur.execute(query)
165
+ rows = cur.fetchall()
166
+ column_names = [desc[0] for desc in cur.description]
167
+ result = [dict(zip(column_names, row)) for row in rows]
168
+ return json.dumps(result, indent=2)
169
+ except Exception as e:
170
+ return f"Error executing query: {e}"
171
+ finally:
172
+ try:
173
+ cur.execute("ROLLBACK")
174
+ except Exception as e:
175
+ return f"Couldn't ROLLBACK transaction: {e}"
176
+
177
+
178
+ def parse_config() -> ServerConfig:
179
+ parser = argparse.ArgumentParser()
180
+ parser.add_argument(
181
+ "--transport",
182
+ default=os.environ.get("YB_MCP_TRANSPORT", "stdio"),
183
+ help="stdio | http (env: YB_MCP_TRANSPORT)",
184
+ )
185
+ parser.add_argument(
186
+ "--stateless-http",
187
+ action="store_true",
188
+ default=os.environ.get("YB_MCP_STATELESS_HTTP", "").lower() == "true",
189
+ help="Enable stateless HTTP mode (env: YB_MCP_STATELESS_HTTP=true)",
190
+ )
191
+ parser.add_argument(
192
+ "--yugabytedb-url",
193
+ default=os.environ.get("YUGABYTEDB_URL"),
194
+ help="YugabyteDB connection string (env: YUGABYTEDB_URL)",
195
+ )
196
+ parser.add_argument(
197
+ "--yb-aws-ssl-root-cert-secret-arn",
198
+ default=os.getenv("YB_AWS_SSL_ROOT_CERT_SECRET_ARN"),
199
+ help="ARN of the AWS Secrets Manager secret containing the TLS root certificate",
200
+ )
201
+ parser.add_argument(
202
+ "--yb-aws-ssl-root-cert-key",
203
+ default=os.getenv("YB_AWS_SSL_ROOT_CERT_KEY"),
204
+ help="Key inside the secret JSON that selects which certificate to use",
205
+ )
206
+ parser.add_argument(
207
+ "--yb-ssl-root-cert-path",
208
+ default=os.getenv("YB_SSL_ROOT_CERT_PATH","/tmp/yb-root.crt"),
209
+ help="Filesystem path where the root certificate will be written (default: `/tmp/yb-root.crt`)"
210
+ )
211
+ parser.add_argument(
212
+ "--yb-aws-ssl-root-cert-secret-region",
213
+ default=os.getenv("YB_AWS_SSL_ROOT_CERT_SECRET_REGION"),
214
+ help="Region of the AWS Secrets Manager secret containing the TLS root certificate",
215
+ )
216
+
217
+ args = parser.parse_args()
218
+ return ServerConfig(
219
+ yugabytedb_url=args.yugabytedb_url,
220
+ transport=args.transport,
221
+ stateless_http=args.stateless_http,
222
+ ssl_root_cert_secret_arn=args.yb_aws_ssl_root_cert_secret_arn,
223
+ ssl_root_cert_key=args.yb_aws_ssl_root_cert_key,
224
+ ssl_root_cert_path=args.yb_ssl_root_cert_path,
225
+ ssl_root_cert_secret_region=args.yb_aws_ssl_root_cert_secret_region,
226
+ )
227
+
228
+
229
+ class YugabyteDBMCPServer:
230
+ def __init__(self, config: ServerConfig):
231
+ self.config = config
232
+ self.mcp = FastMCP(
233
+ "yugabytedb-mcp",
234
+ lifespan=lambda server: app_lifespan(server, config),
235
+ json_response=True,
236
+ stateless_http=config.stateless_http,
237
+ )
238
+
239
+ self._register_tools()
240
+
241
+ def _register_tools(self):
242
+ self.mcp.add_tool(summarize_database)
243
+ self.mcp.add_tool(run_read_only_query)
244
+
245
+ def run(self, host="0.0.0.0", port=8000):
246
+ if self.config.transport == "http":
247
+ self._run_http(host, port)
248
+ else:
249
+ self.mcp.run(transport="stdio")
250
+
251
+ def _run_http(self, host, port):
252
+ @asynccontextmanager
253
+ async def lifespan(app: FastAPI):
254
+ async with AsyncExitStack() as stack:
255
+ await stack.enter_async_context(self.mcp.session_manager.run())
256
+ yield
257
+
258
+ app = FastAPI(lifespan=lifespan)
259
+
260
+ @app.get("/ping")
261
+ async def ping():
262
+ return JSONResponse({"status": "ok"})
263
+
264
+ app.mount("/", self.mcp.streamable_http_app())
265
+
266
+ uvicorn.run(app, host=host, port=port)
267
+
268
+
269
+ if __name__ == "__main__":
270
+ CONFIG = parse_config()
271
+ server = YugabyteDBMCPServer(CONFIG)
272
+ server.run()
273
+
274
+
275
+ def main():
276
+ CONFIG = parse_config()
277
+ server = YugabyteDBMCPServer(CONFIG)
278
+ server.run()