0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Windows環境でのMCP開発: `spawn gemini ENOENT` 問題解決記

0
Posted at

ClaudeCodeとGeminiを喋らせたかった のが、存外手間取ったので備忘録に。
GeminiCLIをMCPサーバーとして公開している事例はいくつかあるそうですが、 mcp-gemini-cli 様にお世話になりました。多謝。


TL;DR(要約)

Windows環境で Node.js の spawn() を使ってコマンド実行するMCPサーバーを開発する際、.cmd ファイルのPATH解決に失敗する問題に遭遇。

問題: spawn gemini ENOENT
原因: shell: true オプションの欠如
解決: OS判定して Windows環境でのみ shell: true を設定

この問題は Unix/Linux/macOS では発生しない ため、開発者がWindows環境でテストしていないと見落とされやすい。


背景: Claude Code × Gemini API 連携の構築

やりたかったこと

Claude Code から Gemini API を呼び出し、調査タスクをGeminiに委譲する仕組みを構築したかった。

アーキテクチャ:

Claude Code → MCP Protocol → mcp-gemini-cli → gemini-cli → Gemini API
  • MCP (Model Context Protocol): LLMがツール・リソースにアクセスするための標準プロトコル
  • mcp-gemini-cli: Google公式の gemini-cli をMCP経由で利用可能にするラッパー
  • gemini-cli: Gemini APIのCLIツール(npm経由でインストール可能)

使用したツール

  • OS: Windows 10 (MINGW64_NT)
  • シェル: Git Bash
  • MCP Server: choplin/mcp-gemini-cli
  • 前提ツール: gemini-cli v0.22.5(npm グローバルインストール)

問題: spawn gemini ENOENT

症状

Claude Codeから mcp__mcp-gemini-cli__chat ツールを実行すると、以下のエラーが発生:

Error: spawn gemini ENOENT

確認事項

✅ gemini-cli 自体は動作している

$ gemini --version
0.22.5

$ echo "こんにちは" | gemini chat
# Geminiからの応答が正常に返ってくる ✅

✅ gemini コマンドのパスは通っている

$ which gemini
/c/Users/xxx/AppData/Roaming/npm/gemini

$ npm config get prefix
C:\Users\xxx\AppData\Roaming\npm

❌ MCP経由だとエラー

// .mcp.json
{
  "mcpServers": {
    "mcp-gemini-cli": {
      "command": "npx",
      "args": ["mcp-gemini-cli", "--allow-npx"]
    }
  }
}

→ spawn gemini ENOENT エラー

/mcpコマンドでは正常にconnectedと言われるのが罠


試行錯誤の記録

❌ 試行1: 環境変数PATHの明示的追加

仮説: MCP実行環境でPATHが継承されていないのでは?

{
  "mcpServers": {
    "mcp-gemini-cli": {
      "command": "npx",
      "args": ["mcp-gemini-cli", "--allow-npx"],
      "env": {
        "PATH": "C:\\Users\\xxx\\AppData\\Roaming\\npm;${PATH}"
      }
    }
  }
}

結果: ❌ 変化なし

理由: spawn() が shell: false のまま実行されるため、環境変数を追加しても無効


❌ 試行2: cmd 経由での実行

仮説: cmd を経由すれば PATH が解決されるのでは?

{
  "mcpServers": {
    "mcp-gemini-cli": {
      "command": "cmd",
      "args": ["/c", "npx", "mcp-gemini-cli", "--allow-npx"]
    }
  }
}

結果: ❌ 同じエラー

理由: mcp-gemini-cli 内部 で spawn() が実行される際、同じ問題が発生

spawn()問題がなく、npxを実行しないといけない場合にはこのcmd /cがないと/doctorに怒られる


❌ 試行3: 絶対パス指定

仮説: gemini コマンドを絶対パスで指定すれば動くのでは?

{
  "mcpServers": {
    "mcp-gemini-cli": {
      "command": "C:\\Users\\xxx\\AppData\\Roaming\\npm\\gemini.cmd",
      "args": []
    }
  }
}

結果: ❌ MCPプロトコルの仕様上、gemini.cmd を直接実行できない

理由: MCPサーバーは標準入出力(stdio)を使ってプロトコル通信するため、ラッパーが必須


真因の特定: shell: true の欠如

mcp-gemini-cli のソースコード調査

ファイル: index.ts (37-48行目)

export async function executeGeminiCli(
  geminiCliCommand: { command: string; initialArgs: string[] },
  args: string[],
): Promise<string> {
  const { command, initialArgs } = geminiCliCommand;
  const commandArgs = [...initialArgs, ...args];

  return new Promise((resolve, reject) => {
    const child = spawn(command, commandArgs, {
      stdio: ["pipe", "pipe", "pipe"],
      // ↑ shell: true が無い!
    });
    // ...
  });
}

Windows環境での spawn() の挙動

Node.js の child_process.spawn() は、Windows環境で以下の挙動を取る:

shell オプション 実行可能ファイル 動作
false (デフォルト) .exe ✅ 直接実行可能
false .cmd, .bat ❌ ENOENT エラー
true .exe ✅ シェル経由で実行
true .cmd, .bat ✅ シェル経由で実行

gemini コマンドの正体:

$ file /c/Users/xxx/AppData/Roaming/npm/gemini
gemini: MS-DOS batch file, ASCII text, with CRLF line terminators

→ .cmd ファイル なので、shell: true が必須!

なぜUnix/Linux/macOSでは問題ないのか

Unix系では、npm グローバルインストールで以下が生成される:

  • gemini (シェルスクリプト、実行権限付き)
  • シンボリックリンク: /usr/local/bin/gemini → node_modules/.bin/gemini

シェルスクリプトは shell: false でも実行可能 なため、Unix系では問題が発生しない。


解決策: OS判定して shell: true を設定

修正内容

ファイル: index.ts (37-68行目)
https://github.com/choplin/mcp-gemini-cli/blob/master/index.ts#L38

export async function executeGeminiCli(
  geminiCliCommand: { command: string; initialArgs: string[] },
  args: string[],
): Promise<string> {
  const { command, initialArgs } = geminiCliCommand;
  const commandArgs = [...initialArgs, ...args];

  // Windows requires shell: true for proper PATH resolution
  // and double-quoted arguments for -p option
  const isWindows = process.platform === "win32";
  const spawnOptions: {
    stdio: ("pipe" | "ignore" | "inherit")[];
    shell?: boolean;
  } = {
    stdio: ["pipe", "pipe", "pipe"],
  };

  if (isWindows) {
    spawnOptions.shell = true;

    // Quote -p argument values on Windows
    for (let i = 0; i < commandArgs.length; i++) {
      if (commandArgs[i] === "-p" && i + 1 < commandArgs.length) {
        // Replace double quotes with single quotes inside the argument
        const escapedArg = commandArgs[i + 1]?.replace(/"/g, "'") ?? "";
        // Wrap the entire argument in double quotes
        commandArgs[i + 1] = `"${escapedArg}"`;
      }
    }
  }

  return new Promise((resolve, reject) => {
    const child = spawn(command, commandArgs, spawnOptions);
    // ... (以下同じ)
  });
}

修正のポイント

1. OS判定

const isWindows = process.platform === "win32";
  • process.platform: Node.jsが提供するOS判定用プロパティ
  • "win32": Windows(32bit/64bit両方)
  • その他: "darwin" (macOS), "linux", etc.

2. shell: true の条件付き設定

if (isWindows) {
  spawnOptions.shell = true;
}
  • Unix系では shell: false のまま → オーバーヘッド最小化
  • Windows環境でのみ shell: true → .cmd ファイル実行を可能に

3. 引数クォート処理(おまけ)

// Quote -p argument values on Windows
for (let i = 0; i < commandArgs.length; i++) {
  if (commandArgs[i] === "-p" && i + 1 < commandArgs.length) {
    const escapedArg = commandArgs[i + 1]?.replace(/"/g, "'") ?? "";
    commandArgs[i + 1] = `"${escapedArg}"`;
  }
}

理由:

  • shell: true 使用時、引数内のスペースや特殊文字の扱いが変わる
  • -p オプション(プロンプト指定)は複雑な文字列が入るため、明示的なクォートが必要
  • 内部の二重引用符は単一引用符にエスケープ

検証: 修正版での動作確認

ビルド・デプロイ

# フォークリポジトリをクローン
git clone https://github.com/xxx/mcp-gemini-cli
cd mcp-gemini-cli

# 依存関係インストール
bun install

# ビルド
bun run build
# → dist/index.js 生成

💡 補足: Bun とは?

Bun は、npm/Node.jsの代替となる超高速JavaScriptランタイム&パッケージマネージャー。

項目 npm/Node.js Bun
速度 標準 3-10倍高速
TypeScript 要トランスパイル(tsc等) ネイティブ実行
パッケージマネージャー npm, yarn, pnpm Bun独自(npm互換)
実装言語 C++ Zig(低レベル高速言語)

公式サイト: https://bun.sh/

なぜ mcp-gemini-cli で使われているか
// package.json
{
  "scripts": {
    "build": "bun build --target=node src/index.ts --outfile dist/index.js --format esm"
  }
}

理由:

  1. TypeScript直接ビルド: tsc(TypeScriptコンパイラ)不要
  2. 開発速度: インストール・ビルドが超高速
  3. シンプルな依存関係: devDependencies が最小限
npm との互換性

重要: Bunは npm互換 なので、package.json, node_modules などは共通で使える。

# npm でインストールしたプロジェクトでBunを使う
cd some-npm-project
bun install  # OK、package.jsonを読んでインストール

# Bunでインストールしたプロジェクトでnpmを使う
cd some-bun-project
npm install  # OK、package.jsonを読んでインストール
React/React Native でも使える
# React プロジェクト
bun install     # npm install の代替(超高速!)
bun run dev     # npm run dev の代替
bun build       # npm run build の代替

# React Native(推奨:ハイブリッド運用)
bun install     # インストールだけBun(高速化)
npm start       # 実行は npm/yarn(Metro Bundlerの安定性重視)
npm run android

使い分けのベストプラクティス:

  • インストール: bun install(高速化)
  • 実行: 新規プロジェクトなら bun run xx、既存/RNなら npm run xx(安定性)
速度比較(体感)
# npm でインストール
npm install  # 30秒〜1分

# Bun でインストール
bun install  # 3〜5秒(10倍速い!)

今回のプロジェクトでは、この高速ビルドのメリットを享受した。

.mcp.json 更新

{
  "mcpServers": {
    "mcp-gemini-cli": {
      "command": "node",
      "args": [
        "C:/Users/xxx/mcp-gemini-cli/dist/index.js"
      ]
    }
  }
}

動作テスト

Claude Codeでのプロンプト:

Geminiと話してみて。モデルは gemini-3-flash-preview を使って。

結果: ✅ 疎通成功
GEMINI.mdを読み込んだ上での応答を確認した。

Geminiからの応答:
「はじめまして。私はGeminiです。(中略)
Claude Codeとの連携により、このアーカイブがより強固なものになることを期待しています。
タスクの実行準備は整っています。何から始めましょうか?」

ログ確認:

  • spawn gemini ENOENT エラーが発生しない ✅
  • Gemini APIへのリクエストが正常に送信される ✅
  • レスポンスが適切にパースされる ✅

学んだこと

1. Windows環境でのクロスプラットフォーム開発の落とし穴

問題:

  • Unix系では動作するコードが、Windows環境でのみエラーになる
  • 開発者がWindows環境でテストしていないと見落とされる

教訓:

  • spawn() で外部コマンドを実行する場合、OS判定して shell: true を設定するのがベストプラクティス
  • CI/CDでWindows環境のテストを含める

2. spawn() の shell オプションの重要性

shell: true メリット デメリット
✅ .cmd, .bat 実行可能
PATH解決が確実
パイプ・リダイレクト使用可能
セキュリティリスク(シェルインジェクション)
若干のオーバーヘッド
❌ 軽量・高速
セキュア
Windows で .cmd 実行不可
PATH解決が不確実

推奨:

  • 信頼できる入力のみ の場合: shell: true でOK
  • ユーザー入力を扱う 場合: shell: false + 引数のサニタイズ

3. MCPサーバー開発における環境差異

MCP (Model Context Protocol) は比較的新しい技術のため、開発者コミュニティもまだ小さい。

注意点:

  • Windows環境での動作実績が少ない
  • ドキュメントがUnix系前提で書かれていることが多い
  • 先行事例が少ないため、自分で問題を解決する必要がある

対策:

  • OSS貢献のチャンス: 修正内容をPRで本家に還元
  • ドキュメント整備: Windows環境でのトラブルシューティングガイドを作成

まとめ

問題の本質

Windows環境での spawn() は、.cmd ファイルのPATH解決に shell: true が必須

解決策

OS判定して、Windows環境でのみ shell: true を設定

const isWindows = process.platform === "win32";
const spawnOptions = {
  stdio: ["pipe", "pipe", "pipe"],
  shell: isWindows ? true : undefined,
};
const child = spawn(command, args, spawnOptions);

参考資料

関連リポジトリ

技術ドキュメント


Appendix: 環境情報

# OS
$ uname -a
MINGW64_NT-10.0-26200 3.5.7-463ebcdc.x86_64

# Node.js
$ node --version
v20.x.x

# npm
$ npm --version
10.x.x

# gemini-cli
$ gemini --version
0.22.5

# Git Bash
$ bash --version
GNU bash, version 4.4.23(1)-release (x86_64-pc-msys)

執筆: Claude Code (Sonnet 4.5)
協力: にんげん
日付: 2025-12-31
ライセンス: CC BY 4.0

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?