refresh_secret
Re-fetch database credentials from AWS Secrets Manager and reconnect. Use after running aws sso login to recover from an expired session or after secret rotation.
Instructions
Re-fetch the database credentials from AWS Secrets Manager and reconnect. Call this after running aws sso login to recover from an expired session, or after the secret has been rotated.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||
Implementation Reference
- src/index.ts:177-186 (registration)Registration of the 'refresh_secret' tool on the MCP server. It accepts no parameters (empty schema) and, when called, delegates to db.refresh() via runTool.
server.tool( 'refresh_secret', 'Re-fetch the database credentials from AWS Secrets Manager and reconnect. Call this after running `aws sso login` to recover from an expired session, or after the secret has been rotated.', {}, async () => runTool(async () => { await db.refresh(); return 'Secret refreshed and connection re-established.'; }) ); - src/db.ts:62-73 (handler)The real handler logic: DbManager.refresh() closes any existing connection pool, clears cached secret, then re-fetches the secret from AWS Secrets Manager and re-establishes a fresh connection pool.
async refresh(): Promise<void> { if (this.pool) { try { await this.pool.close(); } catch { // ignore — we're tearing it down anyway } this.pool = null; } this.secret = null; await this.getPool(); } - src/aws.ts:37-69 (helper)Helper function fetchSecret() that retrieves the secret from AWS Secrets Manager and validates it against SecretSchema. Called again by db.refresh() after clearing the cached secret.
export async function fetchSecret(cfg: AwsConfig): Promise<DbSecret> { const client = new SecretsManagerClient({ region: cfg.awsRegion }); const arn = buildSecretArn(cfg); const result = await client.send(new GetSecretValueCommand({ SecretId: arn })); if (!result.SecretString) { throw new Error( `[AWS_SECRET_INVALID] Secret "${cfg.secretName}" has no SecretString value (binary secrets are not supported).` ); } let parsed: unknown; try { parsed = JSON.parse(result.SecretString); } catch { throw new Error( `[AWS_SECRET_INVALID] Secret "${cfg.secretName}" is not valid JSON. Expected fields: host, port, database, username, password.` ); } const validated = SecretSchema.safeParse(parsed); if (!validated.success) { const issues = validated.error.issues .map((i) => `${i.path.join('.') || '<root>'}: ${i.message}`) .join('; '); throw new Error( `[AWS_SECRET_INVALID] Secret "${cfg.secretName}" is missing or has invalid fields. ${issues}` ); } return validated.data; } - src/aws.ts:13-29 (schema)Zod schema for the database secret fetched from AWS Secrets Manager. Validates required fields (host, port, database, username, password) with sensible defaults for port (1433) and encrypt (true).
export const SecretSchema = z.preprocess((raw) => { // Accept `dbname` (the AWS RDS-credentials template name) as an alias for `database`. if (raw && typeof raw === 'object') { const r = raw as Record<string, unknown>; if (!('database' in r) && 'dbname' in r) { return { ...r, database: r.dbname }; } } return raw; }, z.object({ host: z.string().min(1), port: z.coerce.number().int().positive().default(1433), database: z.string().min(1), username: z.string().min(1), password: z.string().min(1), encrypt: z.coerce.boolean().default(true), })); - src/aws.ts:79-125 (helper)Error formatter that produces user-facing messages mentioning the refresh_secret tool when SSO credentials are expired or missing.
export function formatAwsError(err: unknown, cfg: AwsConfig): string { const e = err as { name?: string; Code?: string; message?: string } | undefined; const name = e?.name ?? e?.Code ?? ''; const msg = e?.message ?? String(err); const isExpired = name === 'ExpiredTokenException' || name === 'ExpiredToken' || /token.*expired|expired.*token|sso session.*expired/i.test(msg); const isMissingCreds = name === 'CredentialsProviderError' || /could not load credentials|unable to load credentials|no credentials/i.test(msg); if (isExpired || isMissingCreds) { return [ '[AWS_AUTH_REQUIRED]', isExpired ? 'AWS SSO session is expired.' : 'No AWS credentials available.', 'Run `aws sso login` (or your team\'s SSO command) in any terminal,', 'then call the `refresh_secret` tool to retry — no MCP restart needed.', ].join(' '); } if (name === 'AccessDeniedException' || /access.*denied|not authorized/i.test(msg)) { return [ '[AWS_ACCESS_DENIED]', `Your AWS principal cannot read secret "${cfg.secretName}" in account ${cfg.awsAccountId} (${cfg.awsRegion}).`, 'Required permission: secretsmanager:GetSecretValue.', `Underlying: ${msg}`, ].join(' '); } if ( name === 'ResourceNotFoundException' || /not.*found|does not exist/i.test(msg) ) { return [ '[AWS_SECRET_NOT_FOUND]', `Secret "${cfg.secretName}" was not found in account ${cfg.awsAccountId} (${cfg.awsRegion}).`, 'Verify SECRET_NAME, AWS_ACCOUNT_ID, and AWS_REGION.', ].join(' '); } return `[AWS_ERROR] ${name || 'Unknown'}: ${msg}`; }