Skip to main content
Glama
kaznak

Shell Command MCP Server

by kaznak

execute-bash-script-async

Execute bash scripts asynchronously to run multiple commands in parallel, reducing waiting time by not requiring completion before starting new processes.

Instructions

This tool executes shell scripts asynchronously in bash. Executing each command creates a new bash process. Synchronous execution requires to wait the scripts completed. Asynchronous execution makes it possible to execute multiple scripts in parallel. You can reduce waiting time by planning in advance which shell scripts need to be executed and executing them in parallel. Avoid using execute-bash-script-sync tool unless you really need to, and use this execute-bash-script-async tool whenever possible.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
commandYesThe bash script to execute
optionsYes

Implementation Reference

  • The MCP tool handler function that orchestrates asynchronous bash script execution, progress notifications via notifications/tools/progress, and error handling.
    async ({ command, options = {} }, extra) => { try { // outputModeを取得、デフォルト値は'complete' const outputMode = options?.outputMode || 'complete'; // 進捗トークンを生成 const progressToken = `cmd-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`; const onOutput = (data: string, isStderr: boolean) => { const fsMark = isStderr ? 'stderr' : 'stdout'; server.notification({ method: 'notifications/tools/progress', params: { progressToken, result: { content: [ { type: 'text' as const, text: `${fsMark}: ${data}`, }, ], isComplete: false, }, }, }); }; // バックグラウンドでコマンドを実行 executeCommand(command, { ...options, onOutput, }) .then(({ exitCode }) => { // 完了通知を送信 server.notification({ method: 'notifications/tools/progress', params: { progressToken, result: { content: [ { type: 'text' as const, text: `exitCode: ${exitCode}`, }, ], isComplete: true, }, }, }); }) .catch((error) => { // エラー通知を送信 server.notification({ method: 'notifications/tools/progress', params: { progressToken, result: { content: [ { type: 'text' as const, text: `Error: ${error instanceof Error ? error.message : String(error)}`, }, ], isComplete: true, isError: true, }, }, }); }); // 初期レスポンスを返す return { content: [ { type: 'text' as const, text: `# Command execution started with output mode, ${outputMode}`, }, ], progressToken, }; } catch (error) { return { content: [ { type: 'text' as const, text: `Error: ${error instanceof Error ? error.message : String(error)}`, }, ], isError: true, }; }
  • Zod schema defining the input parameters for the tool: command (string), and options (cwd, env, timeout, outputMode).
    export const toolOptionsSchema = { command: z.string().describe('The bash script to execute'), options: z.object({ cwd: z.string().optional().describe(`The working directory to execute the script. use this option argument to avoid cd command in the first line of the script. \`~\` and environment variable is not supported. use absolute path instead. `), env: z.record(z.string(), z.string()).optional() .describe(`The environment variables for the script. Set environment variables using this option instead of using export command in the script. `), timeout: z.number().int().positive().optional().describe(`The timeout in milliseconds. Set enough long timeout even if you don't need to set timeout to avoid unexpected blocking. `), outputMode: z .enum(['complete', 'line', 'character', 'chunk']) .optional() .default(toolOptionsDefaults.outPutMode).describe(`The output mode for the script. - complete: Notify when the command is completed - line: Notify on each line of output - chunk: Notify on each chunk of output - character: Notify on each character of output `), }), };
  • The setTool function registers the 'execute-bash-script-async' tool on the MCP server using mcpServer.tool, including name, description, schema, and handler.
    export function setTool(mcpServer: McpServer) { // McpServerインスタンスから低レベルのServerインスタンスにアクセスする const server: Server = mcpServer.server; // 単一のツールとして登録 mcpServer.tool( toolName, toolDescription, toolOptionsSchema, // eslint-disable-next-line @typescript-eslint/no-unused-vars async ({ command, options = {} }, extra) => { try { // outputModeを取得、デフォルト値は'complete' const outputMode = options?.outputMode || 'complete'; // 進捗トークンを生成 const progressToken = `cmd-${Date.now()}-${Math.random().toString(36).slice(2, 7)}`; const onOutput = (data: string, isStderr: boolean) => { const fsMark = isStderr ? 'stderr' : 'stdout'; server.notification({ method: 'notifications/tools/progress', params: { progressToken, result: { content: [ { type: 'text' as const, text: `${fsMark}: ${data}`, }, ], isComplete: false, }, }, }); }; // バックグラウンドでコマンドを実行 executeCommand(command, { ...options, onOutput, }) .then(({ exitCode }) => { // 完了通知を送信 server.notification({ method: 'notifications/tools/progress', params: { progressToken, result: { content: [ { type: 'text' as const, text: `exitCode: ${exitCode}`, }, ], isComplete: true, }, }, }); }) .catch((error) => { // エラー通知を送信 server.notification({ method: 'notifications/tools/progress', params: { progressToken, result: { content: [ { type: 'text' as const, text: `Error: ${error instanceof Error ? error.message : String(error)}`, }, ], isComplete: true, isError: true, }, }, }); }); // 初期レスポンスを返す return { content: [ { type: 'text' as const, text: `# Command execution started with output mode, ${outputMode}`, }, ], progressToken, }; } catch (error) { return { content: [ { type: 'text' as const, text: `Error: ${error instanceof Error ? error.message : String(error)}`, }, ], isError: true, }; } }, ); }
  • Helper function to execute bash command asynchronously with child_process.spawn, supporting output modes (complete, line, chunk, character), timeout, cwd, env.
    export async function executeCommand( command: string, options: CommandOptions = {}, ): Promise<CommandResult> { const outputMode = (options as CommandOptions).outputMode || toolOptionsDefaults.outPutMode; const onOutput = options.onOutput; return new Promise((resolve, reject) => { // 環境変数を設定 const env = { ...process.env, ...options.env, }; // bashプロセスを起動 const bash = spawn(shellProgram, [], { cwd: options.cwd, env, stdio: ['pipe', 'pipe', 'pipe'], }); const stdoutBuffer = { current: '' }; // バッファのコピーを回避 const stderrBuffer = { current: '' }; // バッファのコピーを回避 let timeoutId: NodeJS.Timeout | null = null; const flushBuffer = () => { if (onOutput) { if (stdoutBuffer.current) { onOutput(stdoutBuffer.current, false); stdoutBuffer.current = ''; // バッファをクリア } if (stderrBuffer.current) { onOutput(stderrBuffer.current, true); stderrBuffer.current = ''; // バッファをクリア } } }; // 標準出力の処理 bash.stdout.on('data', (data) => { handleOutput(data.toString(), false, outputMode, onOutput, stdoutBuffer); }); // 標準エラー出力の処理 bash.stderr.on('data', (data) => { handleOutput(data.toString(), true, outputMode, onOutput, stderrBuffer); }); // タイムアウト処理 if (options.timeout) { timeoutId = setTimeout(() => { bash.kill(); reject(new Error(`Command timed out after ${options.timeout}ms`)); }, options.timeout); } // プロセス終了時の処理 bash.on('close', (code) => { // タイマーをクリア if (timeoutId) clearTimeout(timeoutId); // バッファをフラッシュ flushBuffer(); // NOTE これは MCP サーバの実装であるので、ログは標準エラー出力に出す console.error('bash process exited with code', code); resolve({ exitCode: code !== null ? code : 1, }); }); bash.on('error', (error) => { // タイマーをクリア if (timeoutId) clearTimeout(timeoutId); // バッファをフラッシュ flushBuffer(); // NOTE これは MCP サーバの実装であるので、ログは標準エラー出力に出す console.error('Failed to start bash process:', error); reject(error); }); // コマンドを標準入力に書き込み、EOF を送信 bash.stdin.write(command + '\n'); bash.stdin.end(); }); }
  • src/index.ts:13-14 (registration)
    Top-level registration calls to set both sync and async bash tools on the MCP server instance.
    setSyncTool(server); setAsyncTool(server);

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/kaznak/shell-command-mcp'

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