Skip to main content
Glama
dhipskind253

mssql-mcp

by dhipskind253

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

TableJSON Schema
NameRequiredDescriptionDefault

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();
    }
  • 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;
    }
  • 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),
    }));
  • 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}`;
    }
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Without annotations, the description carries full burden. It discloses the core action (re-fetch and reconnect) but does not detail specific side effects like connection interruptions or state changes. However, the simplicity of the tool makes this acceptable.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Two concise sentences with no extraneous information. Key points are front-loaded.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a zero-parameter tool with no output schema, the description sufficiently explains the purpose, triggers, and expected behavior.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The tool has zero parameters, so baseline is 4. The description adds no parameter-specific info but is not needed.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly specifies the verb 'Re-fetch' and the resource 'database credentials from AWS Secrets Manager and reconnect'. It distinguishes itself from sibling tools which are read-only or schema-focused, as this is the only tool that manages credentials.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit when-to-use scenarios: after running `aws sso login` (to recover from expired session) or after secret rotation. This guides the agent away from unnecessary calls during normal operation.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/dhipskind253/mssql-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server