@bilims/mcp-sqlserver
Version:
MCP Server for Microsoft SQL Server with CRUD operations and data analysis capabilities
83 lines • 2.64 kB
JavaScript
import sql from 'mssql';
export class DatabaseConnection {
pool = null;
config;
constructor(config) {
this.config = config;
}
async connect() {
if (this.pool && this.pool.connected) {
return;
}
const poolConfig = {
server: this.config.host,
port: this.config.port,
database: this.config.database,
user: this.config.username,
password: this.config.password,
options: {
encrypt: this.config.encrypt,
trustServerCertificate: this.config.trustServerCertificate,
enableArithAbort: this.config.enableArithAbort,
instanceName: this.config.instanceName,
},
pool: {
min: this.config.pool.min,
max: this.config.pool.max,
idleTimeoutMillis: 30000,
acquireTimeoutMillis: this.config.connectionTimeout,
},
connectionTimeout: this.config.connectionTimeout,
requestTimeout: this.config.requestTimeout,
};
this.pool = new sql.ConnectionPool(poolConfig);
this.pool.on('error', (err) => {
process.stderr.write(`Database pool error: ${err.message || err}\n`);
});
try {
await this.pool.connect();
// Silent connection - don't contaminate stdio
}
catch (error) {
process.stderr.write(`Failed to connect to database: ${error}\n`);
this.pool = null;
throw error;
}
}
async disconnect() {
if (this.pool) {
await this.pool.close();
this.pool = null;
}
}
getPool() {
if (!this.pool || !this.pool.connected) {
throw new Error('Database not connected. Call connect() first.');
}
return this.pool;
}
async testConnection() {
try {
const request = this.getPool().request();
await request.query('SELECT 1 as test');
return true;
}
catch (error) {
process.stderr.write(`Connection test failed: ${error}\n`);
return false;
}
}
async getServerInfo() {
const request = this.getPool().request();
const result = await request.query(`
SELECT
@ as version,
SERVERPROPERTY('Edition') as edition
`);
return {
version: result.recordset[0].version,
edition: result.recordset[0].edition
};
}
}
//# sourceMappingURL=connection.js.map