一个轻量级、零开销的纯Bash实现的模型上下文协议(MCP)服务器。
为什么? 大多数MCP服务器只是API封装并进行模式转换。此实现提供了Node.js、Python或其他重型运行时环境的零开销替代方案。
jq用于JSON处理(在macOS上使用brew install jq安装)git clone https://github.com/muthuishere/mcp-server-bash-sdk
cd mcp-server-bash-sdk
chmod +x mcpserver_core.sh moviemcpserver.sh
echo '{"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "get_movies"}, "id": 1}' | ./moviemcpserver.sh
┌─────────────┐ ┌────────────────────────┐
│ MCP主机 │ │ MCP服务器 │
│ (AI系统) │◄──────► │ (moviemcpserver.sh) │
└─────────────┘ 标准I/O └────────────────────────┘
│
┌───────┴──────────┐
▼ ▼
┌─────────────────┐ ┌───────────────┐
│ 协议层 │ │ 业务逻辑 │
│(mcpserver_core.sh)│ │(tool_* 函数) │
└─────────────────┘ └───────────────┘
│ │
▼ ▼
┌─────────────────┐ ┌───────────────┐
│ 配置 │ │ 外部服务/API │
│ (JSON文件) │ │ │
└─────────────────┘ └───────────────┘
当为MCP服务器实现工具函数时,请遵循以下指南:
tool_前缀开头,并跟随在tools_list.json中定义的相同名称$1weatherserver.sh)#!/bin/bash
# 天气API实现
# 在引入核心之前覆盖配置路径
MCP_CONFIG_FILE="$(dirname "${BASH_SOURCE[0]}")/assets/weatherserver_config.json"
MCP_TOOLS_LIST_FILE="$(dirname "${BASH_SOURCE[0]}")/assets/weatherserver_tools.json"
MCP_LOG_FILE="$(dirname "${BASH_SOURCE[0]}")/logs/weatherserver.log"
# MCP服务器工具函数指南:
# 1. 将所有工具函数命名为带有前缀“tool_”并跟随在tools_list.json中定义的相同名称
# 2. 函数应接受一个包含JSON参数的单个参数"$1"
# 3. 对于成功的操作:回显预期的结果并返回0
# 4. 对于错误:回显错误消息并返回1
# 5. 所有工具函数都基于tools_list.json自动暴露给MCP服务器
# 引入核心MCP服务器实现
source "$(dirname "${BASH_SOURCE[0]}")/mcpserver_core.sh"
# 访问环境变量
API_KEY="${MCP_API_KEY:-default_key}"
# 工具:获取某个地点的当前天气
# 参数:接收一个包含地点的JSON对象
# 成功:回显JSON结果并返回0
# 错误:回显错误消息并返回1
tool_get_weather() {
local args="$1"
local location=$(echo "$args" | jq -r '.location')
# 参数验证
if [[ -z "$location" ]]; then
echo "缺少必需的参数:location"
return 1
fi
# 调用外部API
local weather=$(curl -s "https://api.example.com/weather?location=$location&apikey=$API_KEY")
echo "$weather"
return 0
}
# 启动MCP服务器
run_mcp_server "$@"
assets/weatherserver_tools.json{
"tools": [
{
"name": "get_weather",
"description": "获取某个地点的当前天气",
"inputSchema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称或坐标"
}
},
"required": ["location"]
}
}
]
}
assets/weatherserver_config.json{
"protocolVersion": "2025-03-26",
"serverInfo": {
"name": "WeatherServer",
"version": "1.0.0"
},
"capabilities": {
"tools": {
"listChanged": true
}
},
"instructions": "此服务器提供天气信息。"
}
chmod +x weatherserver.sh
"mcp": {
"servers": {
"my-weather-server": {
"type": "stdio",
"command": "/path/to/your/weatherserver.sh",
"args": [],
"env": {
"MCP_API_KEY": "your-api-key"
}
}
}
}
/mcp my-weather-server get weather for New York
对于AI助手和本地工具执行,这些并不是阻碍问题。
本项目根据MIT许可证发布 - 查看LICENSE文件了解详情。
博客:https://medium.com/@muthuishere/why-i-built-an-mcp-server-sdk-in-shell-yes-bash-6f2192072279