mcp-bridge.sh•2.68 kB
#!/bin/bash
# MCP Bridge Script for Claude Desktop
# This script bridges stdio communication to HTTP for the Laravel MCP server
SERVER_URL="http://localhost:8000/mcp"
SESSION_ID=""
DEBUG_LOG="/tmp/mcp-bridge.log"
# Function to log debug messages
log_debug() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1" >> "$DEBUG_LOG"
}
# Function to send HTTP request and handle response
send_http_request() {
local json_data="$1"
log_debug "Sending request: $json_data"
# Prepare curl command with session header if we have one
local curl_cmd="curl -s -X POST \"$SERVER_URL\" -H \"Content-Type: application/json\" -H \"Accept: application/json\""
if [ -n "$SESSION_ID" ]; then
curl_cmd="$curl_cmd -H \"Mcp-Session-Id: $SESSION_ID\""
fi
curl_cmd="$curl_cmd -d '$json_data'"
# Execute curl and capture both response and headers
local response
local headers_file=$(mktemp)
response=$(curl -s -X POST "$SERVER_URL" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
$([ -n "$SESSION_ID" ] && echo "-H \"Mcp-Session-Id: $SESSION_ID\"") \
-D "$headers_file" \
-d "$json_data" 2>/dev/null)
# Extract session ID from headers if this is an initialize response
if echo "$json_data" | grep -q '"method":"initialize"'; then
SESSION_ID=$(grep -i "mcp-session-id:" "$headers_file" | cut -d' ' -f2 | tr -d '\r\n')
log_debug "Extracted session ID: $SESSION_ID"
fi
rm -f "$headers_file"
log_debug "Response: $response"
echo "$response"
}
# Function to handle JSON-RPC communication
handle_jsonrpc() {
local input="$1"
# Basic JSON validation - check if it starts with { and ends with }
if [[ "$input" =~ ^\{.*\}$ ]]; then
# Send to HTTP server and return response
send_http_request "$input"
else
log_debug "Invalid JSON format: $input"
return 1
fi
}
# Main loop - read from stdin and process each line
log_debug "MCP Bridge starting..."
while IFS= read -r line; do
if [ -n "$line" ]; then
log_debug "Received line: $line"
# Handle the JSON-RPC message
response=$(handle_jsonrpc "$line")
if [ $? -eq 0 ] && [ -n "$response" ]; then
echo "$response"
log_debug "Sent response: $response"
else
log_debug "Failed to process request or empty response"
# Send a generic error response
echo '{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"Internal error"}}'
fi
fi
done
log_debug "MCP Bridge stopping..."