【gemini cli】shell function 呼叫 ai + mcp
新增一個ai專案資料夾
~/Documents/ai_workspace/gemini_func
新增一個檔案 mongo-otp (此範例是透過mongo mcp 查詢otp)
user_id_input=""
model_to_use="gemini-2.5-flash"
# --- 參數解析 ---
while [[ $# -gt 0 ]]; do
case "$1" in
--model)
if [[ -n "$2" ]]; then
model_to_use="$2"
shift 2
else
echo " 錯誤:--model 參數需要模型名稱" >&2
exit 1
fi
;;
-*)
echo " 不支援的選項 '$1'" >&2
exit 1
;;
*)
if [[ -n "$user_id_input" ]]; then
echo " 錯誤:只能輸入一個 userId" >&2
exit 1
fi
user_id_input="$1"
shift
;;
esac
done
if [[ -z "$user_id_input" ]]; then
echo "請輸入 userId,例如:mongo-otp 11111" >&2
exit 1
fi
echo "正在查詢 OTP,使用者 ID: $user_id_input"
echo "使用模型: $model_to_use"
echo "向 MCP 查詢 MongoDB..."
prompt=$(cat <<EOF
你是一位熟悉 MongoDB 的後端工程師,請根據下列需求準確地協助產出查詢結果,並同時附上正確的 MongoDB 查詢語法(db.collection.find(...))以供我 debug。
1. 在 myDB.user collection 中,用 userId = "$user_id_input" 查出對應的 _id。
2. 接著在 myDB.captcha collection 中,查出 user_id = 上面查到的 _id 的資料。
3. 根據 modifyDate 欄位進行降序排序,只取出最新一筆。
4. 僅回傳該筆資料中的 captcha 欄位內容。
5. captcha.user_id 是字串型別,請不要使用 ObjectId(...)。
:pushpin: 最後請只回傳 captcha 的值,不包任何文字、說明、格式、MCP DEBUG 訊息等。
EOF
)
otp=$(echo "$prompt" | gemini -m "$model_to_use" --no-sandbox | sed '/MCP STDERR/d;/\[DEBUG\]/d' | tail -n1)
if [[ -n "$otp" ]]; then
echo "OTP: $otp"
else
echo "找不到 OTP,可能使用者 ID 有誤或無資料。" >&2
exit 1
fi
此範例需要設定 mongdob mcp: https://bookstack.treemanou.com/books/treeman/page/gemini-climcpmongodb
# 把ai專案下的檔案賦予執行權限
find ~/Documents/ai_workspace/gemini_func -type f -exec chmod +x {} \;
# 在 ~/.zshrc 把ai專案路徑加入環境變數,這樣之前的檔案就可以直接呼叫
export PATH="$PATH:$HOME/Documents/ai_workspace/gemini_func"
直接輸入 mongo-otp 就會執行shell,透過ai + mongo mcp 查詢
$mongo-otp 0011111
正在查詢 OTP,使用者 ID: 0011111
使用模型: gemini-2.5-flash
向 MCP 查詢 MongoDB...
OTP: awsedr