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
| Name | Required | Description | Default |
|---|---|---|---|
| command | Yes | Executable name or full command to run. Example: 'pnpm', 'node', '/usr/bin/env'. Must be allowed by exec policy. | |
| args | No | Positional arguments passed to `command`. Example: ['run', 'db:migrate']. Each element is passed verbatim with no extra shell parsing. | |
| keys | No | Whitelist of exact key names to inject. Omit to inject every secret in scope (subject to `tags`). | |
| tags | No | Inject only secrets carrying at least one of these tags. Combinable with `keys` as an AND filter. | |
| profile | No | 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. | restricted |
| scope | No | Where 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). | |
| projectPath | No | Absolute path to the project root for project-scoped secrets and policy resolution. Defaults to the MCP server's current working directory when omitted. | |
| teamId | No | Team identifier for team-scoped secrets. Required only when scope='team'. Example: 'acme-platform'. | |
| orgId | No | Organization identifier for org-scoped secrets. Required only when scope='org'. Example: 'acme-corp'. |
Implementation Reference
- src/mcp/tool-registration.ts:19-30 (registration)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); } - src/mcp/tools/tooling.ts:14-93 (registration)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, ); } }, ); - src/mcp/tools/tooling.ts:58-92 (handler)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, ); } }, - src/core/exec.ts:130-272 (handler)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); }); }); } - src/core/exec.ts:70-128 (helper)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(); } } - src/mcp/tools/tooling.ts:22-57 (schema)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; }