Skip to main content
Glama

exec_with_secrets

Execute a child shell command with project secrets injected as environment variables and redact any leaked secret values from captured output before returning to the agent.

Instructions

[exec] Run a child shell command with project secrets injected as environment variables and any leaked secret values redacted from captured stdout/stderr before they return to the agent. Use to let an agent run a script that needs credentials (npm run db:migrate, terraform plan, vercel deploy) without ever putting plaintext values in the chat; prefer env_generate if you need to write a .env file to disk and validate_secret for upstream liveness checks. Spawns a real child process — has whatever side effects the command itself causes (writes, network, exec). Subject to BOTH tool policy and exec policy (allowlist/denylist). Returns a text body with Exit code: N then STDOUT: and STDERR: blocks; both streams are scrubbed against the secret values that were injected.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesExecutable name or full command to run. Example: 'pnpm', 'node', '/usr/bin/env'. Must be allowed by exec policy.
argsNoPositional arguments passed to `command`. Example: ['run', 'db:migrate']. Each element is passed verbatim with no extra shell parsing.
keysNoWhitelist of exact key names to inject. Omit to inject every secret in scope (subject to `tags`).
tagsNoInject only secrets carrying at least one of these tags. Combinable with `keys` as an AND filter.
profileNoExec sandbox profile. 'restricted' (default) limits PATH and inheritable env vars; 'ci' is restricted plus CI-friendly defaults (no TTY); 'unrestricted' inherits the full server environment — only pick this when you understand the leak risk.restricted
scopeNoWhere the secret lives. 'global' = user keyring (default if omitted on reads), 'project' = scoped to projectPath, 'team' = team-shared (needs teamId), 'org' = org-shared (needs orgId).
projectPathNoAbsolute path to the project root for project-scoped secrets and policy resolution. Defaults to the MCP server's current working directory when omitted.
teamIdNoTeam identifier for team-scoped secrets. Required only when scope='team'. Example: 'acme-platform'.
orgIdNoOrganization identifier for org-scoped secrets. Required only when scope='org'. Example: 'acme-corp'.

Implementation Reference

  • The master registration function that calls registerToolingTools(server) on line 27, which registers the 'exec_with_secrets' tool on the MCP server.
    export function registerMcpTools(server: McpServer): void {
      registerSecretTools(server);
      registerProjectTools(server);
      registerTunnelTools(server);
      registerTeleportTools(server);
      registerAuditTools(server);
      registerValidationTools(server);
      registerHookTools(server);
      registerToolingTools(server);
      registerAgentTools(server);
      registerPolicyTools(server);
    }
  • The registerToolingTools function that defines the 'exec_with_secrets' MCP tool via server.tool(...). This is where the tool is named, its Zod input schema is defined (command, args, keys, tags, profile, scope, projectPath, teamId, orgId), and the handler async function is provided.
    export function registerToolingTools(server: McpServer): void {
      server.tool(
        "exec_with_secrets",
        [
          "[exec] Run a child shell command with project secrets injected as environment variables and any leaked secret values redacted from captured stdout/stderr before they return to the agent.",
          "Use to let an agent run a script that needs credentials (`npm run db:migrate`, `terraform plan`, `vercel deploy`) without ever putting plaintext values in the chat; prefer `env_generate` if you need to write a `.env` file to disk and `validate_secret` for upstream liveness checks.",
          "Spawns a real child process — has whatever side effects the command itself causes (writes, network, exec). Subject to BOTH tool policy and exec policy (allowlist/denylist). Returns a text body with `Exit code: N` then `STDOUT:` and `STDERR:` blocks; both streams are scrubbed against the secret values that were injected.",
        ].join(" "),
        {
          command: z
            .string()
            .describe(
              "Executable name or full command to run. Example: 'pnpm', 'node', '/usr/bin/env'. Must be allowed by exec policy.",
            ),
          args: z
            .array(z.string())
            .optional()
            .describe(
              "Positional arguments passed to `command`. Example: ['run', 'db:migrate']. Each element is passed verbatim with no extra shell parsing.",
            ),
          keys: z
            .array(z.string())
            .optional()
            .describe(
              "Whitelist of exact key names to inject. Omit to inject every secret in scope (subject to `tags`).",
            ),
          tags: z
            .array(z.string())
            .optional()
            .describe(
              "Inject only secrets carrying at least one of these tags. Combinable with `keys` as an AND filter.",
            ),
          profile: z
            .enum(["unrestricted", "restricted", "ci"])
            .optional()
            .default("restricted")
            .describe(
              "Exec sandbox profile. 'restricted' (default) limits PATH and inheritable env vars; 'ci' is restricted plus CI-friendly defaults (no TTY); 'unrestricted' inherits the full server environment — only pick this when you understand the leak risk.",
            ),
          scope,
          projectPath,
          teamId,
          orgId,
        },
        async (params) => {
          const toolBlock = enforceToolPolicy("exec_with_secrets", params.projectPath);
          if (toolBlock) return toolBlock;
    
          const execBlock = checkExecPolicy(params.command, params.projectPath);
          if (!execBlock.allowed) {
            return text(`Policy Denied: ${execBlock.reason}`, true);
          }
    
          try {
            const result = await execCommand({
              command: params.command,
              args: params.args ?? [],
              keys: params.keys,
              tags: params.tags,
              profile: params.profile,
              scope: params.scope,
              projectPath: params.projectPath,
              source: "mcp",
              captureOutput: true,
            });
    
            const output: string[] = [];
            output.push(`Exit code: ${result.code}`);
            if (result.stdout) output.push(`STDOUT:\n${result.stdout}`);
            if (result.stderr) output.push(`STDERR:\n${result.stderr}`);
    
            return text(output.join("\n\n"));
          } catch (err) {
            return text(
              `Execution failed: ${err instanceof Error ? err.message : String(err)}`,
              true,
            );
          }
        },
      );
  • The handler function for 'exec_with_secrets'. It checks tool policy via enforceToolPolicy, checks exec policy via checkExecPolicy, then delegates to execCommand() from the core exec module with the user's parameters, collects stdout/stderr with secret redaction, and returns a formatted text response.
    async (params) => {
      const toolBlock = enforceToolPolicy("exec_with_secrets", params.projectPath);
      if (toolBlock) return toolBlock;
    
      const execBlock = checkExecPolicy(params.command, params.projectPath);
      if (!execBlock.allowed) {
        return text(`Policy Denied: ${execBlock.reason}`, true);
      }
    
      try {
        const result = await execCommand({
          command: params.command,
          args: params.args ?? [],
          keys: params.keys,
          tags: params.tags,
          profile: params.profile,
          scope: params.scope,
          projectPath: params.projectPath,
          source: "mcp",
          captureOutput: true,
        });
    
        const output: string[] = [];
        output.push(`Exit code: ${result.code}`);
        if (result.stdout) output.push(`STDOUT:\n${result.stdout}`);
        if (result.stderr) output.push(`STDERR:\n${result.stderr}`);
    
        return text(output.join("\n\n"));
      } catch (err) {
        return text(
          `Execution failed: ${err instanceof Error ? err.message : String(err)}`,
          true,
        );
      }
    },
  • The core execCommand function that actually spawns the child process with secrets injected into the environment. It retrieves matching secrets from the keyring (filtered by keys/tags), sets up RedactionTransform pipes on stdout/stderr to scrub secret values, enforces profile restrictions (network, denylist, runtime), and returns {code, stdout, stderr}.
    export async function execCommand(opts: ExecOptions): Promise<ExecResult> {
      const profile = getProfile(opts.profile);
      const fullCommand = [opts.command, ...opts.args].join(" ");
    
      const policyDecision = checkExecPolicy(fullCommand, opts.projectPath);
      if (!policyDecision.allowed) {
        throw new Error(`Policy Denied: ${policyDecision.reason}`);
      }
    
      if (profile.denyCommands) {
        const denied = profile.denyCommands.find((d) => {
          const pattern = new RegExp(`(^|[\\s/])${d.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(\\s|$)`, "i");
          return pattern.test(fullCommand);
        });
        if (denied) {
          throw new Error(`Exec profile "${profile.name}" denies command containing "${denied}"`);
        }
      }
      if (profile.allowCommands) {
        const allowed = profile.allowCommands.some((a) => fullCommand.startsWith(a));
        if (!allowed) {
          throw new Error(`Exec profile "${profile.name}" does not allow command "${opts.command}"`);
        }
      }
    
      const envMap: Record<string, string> = {};
      for (const [k, v] of Object.entries(process.env)) {
        if (v !== undefined) envMap[k] = v;
      }
    
      if (profile.stripEnvVars) {
        for (const key of profile.stripEnvVars) {
          delete envMap[key];
        }
      }
    
      const secretsToRedact = new Set<string>();
    
      let entries = listSecrets({
        scope: opts.scope,
        projectPath: opts.projectPath,
        source: opts.source ?? "cli",
        silent: true, // list silently
      });
    
      if (opts.keys?.length) {
        const keySet = new Set(opts.keys);
        entries = entries.filter((e) => keySet.has(e.key));
      }
    
      if (opts.tags?.length) {
        entries = entries.filter((e) =>
          opts.tags!.some((t) => e.envelope?.meta.tags?.includes(t)),
        );
      }
    
      for (const entry of entries) {
        if (entry.envelope) {
          const decay = checkDecay(entry.envelope);
          if (decay.isExpired) continue;
        }
    
        const val = getSecret(entry.key, {
          scope: entry.scope,
          projectPath: opts.projectPath,
          env: opts.env,
          source: opts.source ?? "cli",
          silent: false, // Log access for execution
        });
    
        if (val !== null) {
          envMap[entry.key] = val;
          if (val.length > 5) {
            secretsToRedact.add(val);
          }
        }
      }
    
      const maxRuntime = profile.maxRuntimeSeconds ?? getExecMaxRuntime(opts.projectPath);
    
      return new Promise((resolve, reject) => {
        // Enforce network restrictions for profiles that disallow network access.
        const networkTools = new Set([
          "curl", "wget", "ping", "nc", "netcat", "ssh", "telnet", "ftp", "dig", "nslookup",
        ]);
    
        if (profile.allowNetwork === false && networkTools.has(opts.command)) {
          const msg = `[QRING] Execution blocked: network access is disabled for profile "${profile.name}", command "${opts.command}" is considered network-related`;
          if (opts.captureOutput) {
            return resolve({ code: 126, stdout: "", stderr: msg });
          }
          process.stderr.write(msg + "\n");
          return resolve({ code: 126, stdout: "", stderr: "" });
        }
    
        const child = spawn(opts.command, opts.args, {
          env: envMap,
          stdio: ["inherit", "pipe", "pipe"],
          shell: false,
        });
    
        let timedOut = false;
        let timer: ReturnType<typeof setTimeout> | undefined;
    
        if (maxRuntime) {
          timer = setTimeout(() => {
            timedOut = true;
            child.kill("SIGKILL");
          }, maxRuntime * 1000);
        }
    
        const stdoutRedact = new RedactionTransform([...secretsToRedact]);
        const stderrRedact = new RedactionTransform([...secretsToRedact]);
    
        if (child.stdout) child.stdout.pipe(stdoutRedact);
        if (child.stderr) child.stderr.pipe(stderrRedact);
    
        let stdoutStr = "";
        let stderrStr = "";
    
        if (opts.captureOutput) {
          stdoutRedact.on("data", (d) => (stdoutStr += d.toString()));
          stderrRedact.on("data", (d) => (stderrStr += d.toString()));
        } else {
          stdoutRedact.pipe(process.stdout);
          stderrRedact.pipe(process.stderr);
        }
    
        child.on("close", (code) => {
          if (timer) clearTimeout(timer);
          if (timedOut) {
            resolve({ code: 124, stdout: stdoutStr, stderr: stderrStr + `\n[QRING] Process killed: exceeded ${maxRuntime}s runtime limit` });
          } else {
            resolve({ code: code ?? 0, stdout: stdoutStr, stderr: stderrStr });
          }
        });
    
        child.on("error", (err) => {
          if (timer) clearTimeout(timer);
          reject(err);
        });
      });
    }
  • The RedactionTransform class — a Node.js Transform stream that replaces any known secret values (longer than 5 chars) in stdout/stderr with '[QRING:REDACTED]', ensuring leaked secrets never appear in the returned output.
    export class RedactionTransform extends Transform {
      private patterns: { value: string; replacement: string }[] = [];
      private tail: string = "";
      private maxLen: number = 0;
    
      constructor(secretsToRedact: string[]) {
        super();
        // Only redact secrets > 5 chars to avoid destroying output
        const validSecrets = secretsToRedact.filter((s) => s.length > 5);
        // Sort by length descending to match longest first
        validSecrets.sort((a, b) => b.length - a.length);
    
        this.patterns = validSecrets.map((s) => ({
          value: s,
          replacement: "[QRING:REDACTED]",
        }));
    
        if (validSecrets.length > 0) {
          this.maxLen = validSecrets[0].length;
        }
      }
    
      _transform(chunk: Buffer | string, _encoding: string, callback: () => void) {
        if (this.patterns.length === 0) {
          this.push(chunk);
          return callback();
        }
    
        const text = this.tail + chunk.toString();
        let redacted = text;
    
        for (const { value, replacement } of this.patterns) {
          redacted = redacted.split(value).join(replacement);
        }
    
        if (redacted.length < this.maxLen) {
          this.tail = redacted;
          return callback();
        }
    
        const outputLen = redacted.length - this.maxLen + 1;
        const output = redacted.slice(0, outputLen);
        this.tail = redacted.slice(outputLen);
    
        this.push(output);
        callback();
      }
    
      _flush(callback: () => void) {
        if (this.tail) {
          let final = this.tail;
          for (const { value, replacement } of this.patterns) {
            final = final.split(value).join(replacement);
          }
          this.push(final);
        }
        callback();
      }
    }
  • The Zod schema for 'exec_with_secrets' parameters: command (string), args (optional string array), keys (optional string array), tags (optional string array), profile (enum of unrestricted/restricted/ci), and common schemas for scope, projectPath, teamId, orgId.
    {
      command: z
        .string()
        .describe(
          "Executable name or full command to run. Example: 'pnpm', 'node', '/usr/bin/env'. Must be allowed by exec policy.",
        ),
      args: z
        .array(z.string())
        .optional()
        .describe(
          "Positional arguments passed to `command`. Example: ['run', 'db:migrate']. Each element is passed verbatim with no extra shell parsing.",
        ),
      keys: z
        .array(z.string())
        .optional()
        .describe(
          "Whitelist of exact key names to inject. Omit to inject every secret in scope (subject to `tags`).",
        ),
      tags: z
        .array(z.string())
        .optional()
        .describe(
          "Inject only secrets carrying at least one of these tags. Combinable with `keys` as an AND filter.",
        ),
      profile: z
        .enum(["unrestricted", "restricted", "ci"])
        .optional()
        .default("restricted")
        .describe(
          "Exec sandbox profile. 'restricted' (default) limits PATH and inheritable env vars; 'ci' is restricted plus CI-friendly defaults (no TTY); 'unrestricted' inherits the full server environment — only pick this when you understand the leak risk.",
        ),
      scope,
      projectPath,
      teamId,
      orgId,
    },
  • src/mcp/server.ts:5-12 (registration)
    The createMcpServer function which creates the MCP server instance and calls registerMcpTools, the entry point for all tool registrations including exec_with_secrets.
    export function createMcpServer(): McpServer {
      const server = new McpServer({
        name: "q-ring",
        version: PACKAGE_VERSION,
      });
      registerMcpTools(server);
      return server;
    }
Behavior5/5

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

Despite no annotations, description fully discloses side effects (spawns child process, writes, network, exec), policy subjection (tool and exec policy), and return format (Exit code, STDOUT, STDERR scrubbed). No contradictions.

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

Conciseness4/5

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

Single dense paragraph with all key information. Could be slightly more structured (e.g., bullet points), but it's clear and free of fluff.

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?

Given no output schema and no annotations, description covers purpose, usage, behavioral traits, parameter roles, and return format comprehensively. Minimal gaps.

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

Parameters3/5

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

Schema coverage is 100%, baseline is 3. Description adds no significant extra meaning beyond schema descriptions for parameters; it merely restates or gives examples already in schema.

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 states the tool runs a child shell command with project secrets injected and leaked values scrubbed. It distinguishes from siblings like `env_generate` and `validate_secret` by specifying alternative use cases.

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?

Explicit when-to-use (running scripts needing credentials) and when-not (prefer `env_generate` for .env files, `validate_secret` for liveness checks). Also mentions policy restrictions.

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/I4cTime/quantum_ring'

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