postgres-scout-mcp 1.0.0

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.
package/LICENSE ADDED
@@ -0,0 +1,190 @@
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 the 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 the 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 any 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
+ Copyright 2026 Boban Lukic
179
+
180
+ Licensed under the Apache License, Version 2.0 (the "License");
181
+ you may not use this file except in compliance with the License.
182
+ You may obtain a copy of the License at
183
+
184
+ http://www.apache.org/licenses/LICENSE-2.0
185
+
186
+ Unless required by applicable law or agreed to in writing, software
187
+ distributed under the License is distributed on an "AS IS" BASIS,
188
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
189
+ See the License for the specific language governing permissions and
190
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,234 @@
1
+ # Postgres Scout MCP
2
+
3
+ Scout your PostgreSQL databases with AI - A production-ready Model Context Protocol server with built-in safety features, monitoring, and data quality tools.
4
+
5
+ ## Setup
6
+
7
+ ### Claude Desktop / Claude Code
8
+
9
+ Add to your MCP config (`~/.config/claude-desktop/config.json` or `~/.claude.json`):
10
+
11
+ ```json
12
+ {
13
+ "mcpServers": {
14
+ "postgres-scout": {
15
+ "command": "npx",
16
+ "args": [
17
+ "-y",
18
+ "postgres-scout-mcp",
19
+ "postgresql://localhost:5432/mydb"
20
+ ],
21
+ "type": "stdio"
22
+ }
23
+ }
24
+ }
25
+ ```
26
+
27
+ ### Recommended: Separate Read-Only and Read-Write Instances
28
+
29
+ The server runs in **read-only mode by default** for safety. For write operations, use a separate instance:
30
+
31
+ ```json
32
+ {
33
+ "mcpServers": {
34
+ "postgres-scout-readonly": {
35
+ "command": "npx",
36
+ "args": ["-y", "postgres-scout-mcp", "--read-only", "postgresql://localhost:5432/production"],
37
+ "type": "stdio"
38
+ },
39
+ "postgres-scout-readwrite": {
40
+ "command": "npx",
41
+ "args": ["-y", "postgres-scout-mcp", "--read-write", "postgresql://localhost:5432/development"],
42
+ "type": "stdio"
43
+ }
44
+ }
45
+ }
46
+ ```
47
+
48
+ This gives you:
49
+ - **postgres-scout-readonly**: Safe exploration without risk of data modification
50
+ - **postgres-scout-readwrite**: Write operations available when explicitly needed
51
+ - Clear separation of capabilities
52
+ - Option to point read-write to a development database for extra safety
53
+
54
+ ### Global Install
55
+
56
+ ```bash
57
+ npm install -g postgres-scout-mcp
58
+ postgres-scout-mcp postgresql://localhost:5432/mydb
59
+ ```
60
+
61
+ ### Standalone Usage
62
+
63
+ ```bash
64
+ # Default read-only mode (safest)
65
+ postgres-scout-mcp
66
+
67
+ # Explicitly enable read-write mode (use with caution)
68
+ postgres-scout-mcp --read-write
69
+
70
+ # With custom URI in read-only mode
71
+ postgres-scout-mcp postgresql://localhost:5432/mydb
72
+
73
+ # Read-write mode with custom connection
74
+ postgres-scout-mcp --read-write postgresql://localhost:5432/mydb
75
+ ```
76
+
77
+ ### Command Line Options
78
+
79
+ ```
80
+ --read-only Run server in read-only mode (default)
81
+ --read-write Run server in read-write mode (enables all write operations)
82
+ --mode <mode> Set mode: 'read-only' or 'read-write'
83
+ ```
84
+
85
+ ### Environment Variables
86
+
87
+ ```bash
88
+ # Security
89
+ QUERY_TIMEOUT=30000 # milliseconds (default: 30s)
90
+ MAX_RESULT_ROWS=10000 # prevent memory exhaustion
91
+ ENABLE_RATE_LIMIT=true
92
+ RATE_LIMIT_MAX_REQUESTS=100
93
+ RATE_LIMIT_WINDOW_MS=60000 # 1 minute
94
+
95
+ # Logging
96
+ LOG_DIR=./logs
97
+ LOG_LEVEL=info # debug, info, warn, error
98
+
99
+ # Connection Pool
100
+ PGMAXPOOLSIZE=10
101
+ PGMINPOOLSIZE=2
102
+ PGIDLETIMEOUT=10000
103
+ ```
104
+
105
+ ## Security
106
+
107
+ - **Read-only by default** — write operations must be explicitly enabled
108
+ - All queries use parameterized values
109
+ - SQL injection prevention with input validation and pattern detection
110
+ - Identifier sanitization for table/column names
111
+ - Rate limiting on all operations
112
+ - Query timeouts to prevent long-running queries
113
+ - Response size limits to prevent memory exhaustion
114
+
115
+ ## Available Tools
116
+
117
+ ### Read Operations (both modes)
118
+
119
+ - **Database**: `listDatabases`, `getDatabaseStats`
120
+ - **Schema**: `listSchemas`, `listTables`, `describeTable`
121
+ - **Query**: `executeQuery`, `explainQuery`
122
+
123
+ ### Data Quality
124
+
125
+ - `findDuplicates` — find duplicate rows based on column combinations
126
+ - `findMissingValues` — NULL analysis across columns
127
+ - `findOrphans` — find orphaned records via foreign key references
128
+ - `checkConstraintViolations` — detect constraint issues
129
+ - `analyzeTypeConsistency` — find type inconsistencies across rows
130
+
131
+ ### Export
132
+
133
+ - `exportTable` — export to CSV, JSON, JSONL, or SQL
134
+ - `generateInsertStatements` — generate INSERT statements with batching
135
+
136
+ ### Relationships
137
+
138
+ - `exploreRelationships` — follow multi-hop relationships and discover dependencies
139
+ - `analyzeForeignKeys` — analyze foreign key structure
140
+
141
+ ### Temporal Queries
142
+
143
+ - `findRecent` — find rows within a time window
144
+ - `analyzeTimeSeries` — time series analysis with anomaly detection
145
+ - `detectSeasonality` — detect seasonal patterns
146
+
147
+ ### Monitoring
148
+
149
+ - `getCurrentActivity` — active queries and connections
150
+ - `analyzeLocks` — lock analysis
151
+ - `getIndexUsage` — index usage statistics
152
+
153
+ ### Live Monitoring
154
+
155
+ - `getLiveMetrics` — real-time performance metrics
156
+ - `getHottestTables` — identify most active tables
157
+ - `getTableMetrics` — detailed metrics per table
158
+
159
+ ### Maintenance & Optimization
160
+
161
+ - `getHealthScore` — overall database health score
162
+ - `getSlowQueries` — slow query analysis (requires `pg_stat_statements`)
163
+ - `analyzeTableBloat` — table bloat analysis
164
+ - `suggestVacuum` — VACUUM recommendations
165
+ - `suggestIndexes` — index recommendations
166
+ - `suggestPartitioning` — partitioning suggestions
167
+ - `detectAnomalies` — anomaly detection
168
+ - `optimizeQuery` — query optimization suggestions
169
+
170
+ ### Write Operations (read-write mode only)
171
+
172
+ - `previewUpdate`, `previewDelete` — preview changes before applying
173
+ - `safeUpdate` — UPDATE with row limits and preview
174
+ - `safeDelete` — DELETE with row limits and preview
175
+ - `safeInsert` — INSERT with validation
176
+
177
+ ## Logging
178
+
179
+ File logging is **disabled by default**. Enable it with the `ENABLE_LOGGING=true` environment variable:
180
+
181
+ ```json
182
+ {
183
+ "mcpServers": {
184
+ "postgres-scout": {
185
+ "command": "npx",
186
+ "args": ["-y", "postgres-scout-mcp", "postgresql://localhost:5432/mydb"],
187
+ "env": { "ENABLE_LOGGING": "true", "LOG_DIR": "./logs" },
188
+ "type": "stdio"
189
+ }
190
+ }
191
+ }
192
+ ```
193
+
194
+ When enabled, two log files are created in `LOG_DIR` (defaults to `./logs`):
195
+
196
+ - **tool-usage.log**: Every tool call with timestamp, tool name, and arguments
197
+ - **error.log**: Errors with stack traces and the arguments that caused them
198
+
199
+ ## Examples
200
+
201
+ ### Basic Operations
202
+ ```
203
+ executeQuery({ query: "SELECT id, email FROM users WHERE status = $1 LIMIT 10", params: ["active"] })
204
+ explainQuery({ query: "SELECT * FROM orders WHERE customer_id = $1", params: [123], analyze: true })
205
+ listTables({ schema: "public" })
206
+ ```
207
+
208
+ ### Data Quality
209
+ ```
210
+ findDuplicates({ table: "users", columns: ["email"] })
211
+ findOrphans({ table: "orders", column: "customer_id", referencedTable: "customers", referencedColumn: "id" })
212
+ findMissingValues({ table: "users", columns: ["email", "phone"] })
213
+ ```
214
+
215
+ ### Monitoring
216
+ ```
217
+ getLiveMetrics({ metrics: ["queries", "connections", "cache"], duration: 30000, interval: 1000 })
218
+ getHottestTables({ limit: 5, orderBy: "seq_scan" })
219
+ getSlowQueries({ minDurationMs: 100, limit: 10 })
220
+ ```
221
+
222
+ ## Development
223
+
224
+ ```bash
225
+ git clone https://github.com/bluwork/postgres-scout-mcp.git
226
+ cd postgres-scout-mcp
227
+ pnpm install
228
+ pnpm build
229
+ pnpm test
230
+ ```
231
+
232
+ ## License
233
+
234
+ Apache-2.0
package/bin/cli.js ADDED
@@ -0,0 +1,67 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { fileURLToPath } from 'url';
4
+ import { dirname, join } from 'path';
5
+ import { spawnSync } from 'child_process';
6
+
7
+ // Get the directory of the current module
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ // Parse command line arguments
12
+ const args = process.argv.slice(2);
13
+ const helpText = `
14
+ Postgres Scout MCP - PostgreSQL Model Context Protocol Server
15
+
16
+ Usage:
17
+ postgres-scout-mcp [options] [postgresql-uri]
18
+
19
+ Options:
20
+ --help, -h Show this help message
21
+ --version, -v Show version number
22
+ --read-only Run server in read-only mode (default)
23
+ --read-write Run server in read-write mode (enables all write operations)
24
+ --mode <mode> Set mode: 'read-only' or 'read-write'
25
+
26
+ Arguments:
27
+ postgresql-uri PostgreSQL connection URI (default: postgresql://localhost:5432/postgres)
28
+
29
+ Examples:
30
+ postgres-scout-mcp
31
+ postgres-scout-mcp --read-write postgresql://localhost:5432/mydb
32
+ postgres-scout-mcp --mode read-only postgresql://localhost:5432/mydb
33
+ `;
34
+
35
+ // Handle command-line options
36
+ if (args.includes('--help') || args.includes('-h')) {
37
+ console.log(helpText);
38
+ process.exit(0);
39
+ }
40
+
41
+ if (args.includes('--version') || args.includes('-v')) {
42
+ // Read version from package.json
43
+ try {
44
+ const packageJsonPath = join(__dirname, '..', 'package.json');
45
+ const packageJson = await import(packageJsonPath, { with: { type: 'json' } });
46
+ console.log(`Postgres Scout MCP v${packageJson.default.version}`);
47
+ process.exit(0);
48
+ } catch (error) {
49
+ console.error(
50
+ 'Could not determine version:',
51
+ error instanceof Error ? error.message : String(error)
52
+ );
53
+ process.exit(1);
54
+ }
55
+ }
56
+
57
+ const filteredArgs = args.filter((arg) => !['--help', '-h', '--version', '-v'].includes(arg));
58
+
59
+ // Launch the actual MCP server
60
+ const serverPath = join(__dirname, '..', 'dist', 'index.js');
61
+ const nodeProcess = spawnSync('node', [serverPath, ...filteredArgs], {
62
+ stdio: 'inherit',
63
+ shell: process.platform === 'win32',
64
+ });
65
+
66
+ // Forward the exit code from the child process
67
+ process.exit(nodeProcess.status || 0);
@@ -0,0 +1,52 @@
1
+ import { parseIntSafe } from '../utils/sanitize.js';
2
+ export function parseCommandLineArgs(args) {
3
+ let mode = 'read-only';
4
+ let connectionString = '';
5
+ for (let i = 0; i < args.length; i++) {
6
+ const arg = args[i];
7
+ if (arg === '--read-write' || arg === '-w') {
8
+ mode = 'read-write';
9
+ }
10
+ else if (arg === '--read-only' || arg === '-r') {
11
+ mode = 'read-only';
12
+ }
13
+ else if (!arg.startsWith('-')) {
14
+ connectionString = arg;
15
+ }
16
+ }
17
+ if (!connectionString) {
18
+ connectionString = process.env.DATABASE_URL || '';
19
+ }
20
+ if (!connectionString) {
21
+ throw new Error('Database connection string required. Provide as argument or set DATABASE_URL environment variable.');
22
+ }
23
+ return { mode, connectionString };
24
+ }
25
+ export function createServerConfig(args) {
26
+ return {
27
+ mode: args.mode,
28
+ connectionString: args.connectionString,
29
+ queryTimeout: parseIntSafe(process.env.QUERY_TIMEOUT || '30000', 30000),
30
+ maxResultRows: parseIntSafe(process.env.MAX_RESULT_ROWS || '10000', 10000),
31
+ enableRateLimit: process.env.ENABLE_RATE_LIMIT !== 'false',
32
+ rateLimitMaxRequests: parseIntSafe(process.env.RATE_LIMIT_MAX_REQUESTS || '100', 100),
33
+ rateLimitWindowMs: parseIntSafe(process.env.RATE_LIMIT_WINDOW_MS || '60000', 60000),
34
+ logDir: process.env.LOG_DIR || './logs',
35
+ logLevel: process.env.LOG_LEVEL || 'info'
36
+ };
37
+ }
38
+ export function validateConfig(config) {
39
+ if (!config.connectionString) {
40
+ throw new Error('Connection string is required');
41
+ }
42
+ if (config.queryTimeout < 1000 || config.queryTimeout > 600000) {
43
+ throw new Error('Query timeout must be between 1000ms and 600000ms');
44
+ }
45
+ if (config.maxResultRows < 1 || config.maxResultRows > 100000) {
46
+ throw new Error('Max result rows must be between 1 and 100000');
47
+ }
48
+ if (!['read-only', 'read-write'].includes(config.mode)) {
49
+ throw new Error('Mode must be either "read-only" or "read-write"');
50
+ }
51
+ }
52
+ //# sourceMappingURL=environment.js.map
package/dist/index.js ADDED
@@ -0,0 +1,59 @@
1
+ #!/usr/bin/env node
2
+ import { parseCommandLineArgs, createServerConfig, validateConfig } from './config/environment.js';
3
+ import { createLogger } from './utils/logger.js';
4
+ import { createDatabaseConnection, closeDatabaseConnection } from './utils/database.js';
5
+ import { createMCPServer, startServer } from './server/setup.js';
6
+ async function main() {
7
+ let logger;
8
+ let connection;
9
+ try {
10
+ const args = parseCommandLineArgs(process.argv.slice(2));
11
+ const config = createServerConfig(args);
12
+ validateConfig(config);
13
+ logger = createLogger(config.logDir, config.logLevel);
14
+ logger.info('main', 'Starting Postgres Scout MCP', {
15
+ mode: config.mode,
16
+ logLevel: config.logLevel
17
+ });
18
+ connection = await createDatabaseConnection(config, logger);
19
+ logger.info('main', 'Database connection established', {
20
+ database: connection.pool.options.database
21
+ });
22
+ const server = createMCPServer(connection, logger, config);
23
+ await startServer(server, logger);
24
+ const shutdown = async () => {
25
+ if (logger) {
26
+ logger.info('main', 'Shutting down...');
27
+ }
28
+ if (connection && logger) {
29
+ await closeDatabaseConnection(connection, logger);
30
+ }
31
+ process.exit(0);
32
+ };
33
+ process.on('SIGINT', shutdown);
34
+ process.on('SIGTERM', shutdown);
35
+ }
36
+ catch (error) {
37
+ const errorMessage = error instanceof Error ? error.message : String(error);
38
+ if (logger) {
39
+ logger.error('main', 'Fatal error', { error: errorMessage });
40
+ }
41
+ else {
42
+ console.error('Fatal error:', errorMessage);
43
+ }
44
+ if (connection) {
45
+ try {
46
+ await closeDatabaseConnection(connection, logger);
47
+ }
48
+ catch (closeError) {
49
+ console.error('Error closing connection:', closeError);
50
+ }
51
+ }
52
+ process.exit(1);
53
+ }
54
+ }
55
+ main().catch((error) => {
56
+ console.error('Unhandled error:', error);
57
+ process.exit(1);
58
+ });
59
+ //# sourceMappingURL=index.js.map