Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions cmd/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ import (
"github.com/spf13/cobra"
)

var (
useHTTP bool
httpPort int
)

// mcpCommand represents the run command which starts the MCP server
var mcpCommand = &cobra.Command{
Use: "mcp",
Expand Down Expand Up @@ -65,6 +70,9 @@ available to AI applications via the MCP protocol.
DescriptionOverride: descriptionOverride,
})

if useHTTP {
return srv.StartHTTP(httpPort)
}
return srv.Start()
},
}
Expand All @@ -78,6 +86,10 @@ func init() {
mcpCommand.Flags().StringSliceVarP(&descriptionFile, "description-file", "", []string{}, "Read the MCP server description from files (optional, can be specified multiple times)")
mcpCommand.Flags().BoolVarP(&descriptionOverride, "description-override", "", false, "Override the description found in the config file")

// Add HTTP server flags
mcpCommand.Flags().BoolVar(&useHTTP, "http", false, "Enable HTTP server mode (serve MCP over HTTP/SSE instead of stdio)")
mcpCommand.Flags().IntVar(&httpPort, "port", 8080, "Port for HTTP server (default: 8080, only used with --http)")

// Mark required flags
_ = mcpCommand.MarkFlagRequired("config")
}
7 changes: 6 additions & 1 deletion docs/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,10 +74,15 @@ mcpshell mcp [flags]

Runs an MCP server that communicates using the Model Context Protocol and exposes the tools defined in a MCP configuration file. The server loads tool definitions from a YAML configuration file and makes them available to AI applications via the MCP protocol.

**HTTP/SSE Mode**:

- `--http`: Enable HTTP server mode (serve MCP over HTTP/SSE instead of stdio)
- `--port`: Port for HTTP server (default: 8080, only used with --http)

**Example**:

```console
mcpshell mcp --config=examples/config.yaml --log-level=debug
mcpshell mcp --config=examples/config.yaml --http --port=9090 --log-level=debug
```

### EXE Command
Expand Down
112 changes: 112 additions & 0 deletions pkg/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"

"github.com/mark3labs/mcp-go/mcp"
Expand Down Expand Up @@ -602,3 +604,113 @@
}
return data
}

// StartHTTP initializes the MCP server and starts an HTTP server for MCP protocol over HTTP/SSE
func (s *Server) StartHTTP(port int) error {
s.logger.Info("Initializing MCP HTTP server on port %d", port)
if err := s.CreateServer(); err != nil {
return err
}
http.HandleFunc("/sse", s.handleMCPHTTP)
addr := fmt.Sprintf(":%d", port)
s.logger.Info("Listening on http://localhost%s/sse", addr)
fmt.Printf("MCP HTTP server listening on http://localhost%s/sse\n", addr)
Comment on lines +614 to +617

Copilot AI Aug 1, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The endpoint is named '/sse' but the implementation is a standard HTTP POST handler, not Server-Sent Events. Consider renaming to '/mcp' or implementing actual SSE if that's the intended protocol.

Suggested change
http.HandleFunc("/sse", s.handleMCPHTTP)
addr := fmt.Sprintf(":%d", port)
s.logger.Info("Listening on http://localhost%s/sse", addr)
fmt.Printf("MCP HTTP server listening on http://localhost%s/sse\n", addr)
http.HandleFunc("/mcp", s.handleMCPHTTP)
addr := fmt.Sprintf(":%d", port)
s.logger.Info("Listening on http://localhost%s/mcp", addr)
fmt.Printf("MCP HTTP server listening on http://localhost%s/mcp\n", addr)

Copilot uses AI. Check for mistakes.
return http.ListenAndServe(addr, nil)
}

// handleMCPHTTP handles HTTP POST requests for MCP protocol
func (s *Server) handleMCPHTTP(w http.ResponseWriter, r *http.Request) {
s.logger.Info("New HTTP connection from %s %s %s", r.RemoteAddr, r.Method, r.URL.Path)
if r.Method != http.MethodPost {
http.Error(w, "Only POST allowed", http.StatusMethodNotAllowed)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Failed to read body", http.StatusBadRequest)
s.logger.Error("Failed to read request body from %s: %v", r.RemoteAddr, err)
return
}

s.logger.Info("Request body: %s", string(body))

Copilot AI Aug 1, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logging the full request body may expose sensitive information in logs. Consider logging only a summary or sanitized version of the request for security purposes.

Copilot uses AI. Check for mistakes.

// Parse the JSON-RPC request
var req map[string]interface{}
if err := json.Unmarshal(body, &req); err != nil {
http.Error(w, "Invalid JSON", http.StatusBadRequest)
s.logger.Error("Invalid JSON from %s: %v", r.RemoteAddr, err)
return
}

// Intercept "initialize" method
if method, ok := req["method"].(string); ok && method == "initialize" {
id := req["id"]
s.logger.Info("Received 'initialize' from %s (id=%v)", r.RemoteAddr, id)

// Extract protocolVersion from params
protocolVersion := ""
if params, ok := req["params"].(map[string]interface{}); ok {
if pv, ok := params["protocolVersion"].(string); ok {
protocolVersion = pv
}
}
if protocolVersion == "" {
protocolVersion = "2025-03-26" // fallback, should always be present
}

resp := map[string]interface{}{
"jsonrpc": "2.0",
"id": id,
"result": map[string]interface{}{
"serverInfo": map[string]interface{}{
"name": "MCPShell",
"version": s.version,
},
"capabilities": map[string]interface{}{
"tools": map[string]interface{}{
"allowedTools": s.getAllowedToolNames(),
},
},
"sessionId": "local",
"protocolVersion": protocolVersion,
},
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
respBytes, _ := json.Marshal(resp)
Comment on lines +679 to +680

Copilot AI Aug 1, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error from json.Marshal is being ignored. Consider handling the marshaling error to ensure robust error handling.

Suggested change
w.WriteHeader(http.StatusOK)
respBytes, _ := json.Marshal(resp)
respBytes, err := json.Marshal(resp)
if err != nil {
s.logger.Error("Failed to marshal response: %v", err)
http.Error(w, `{"error":"Internal server error"}`, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)

Copilot uses AI. Check for mistakes.
s.logger.Info("Response: %s", string(respBytes))

Copilot AI Aug 1, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logging the full response may expose sensitive information in logs. Consider logging only a summary or sanitized version of the response for security purposes.

Suggested change
s.logger.Info("Response: %s", string(respBytes))
result := resp["result"].(map[string]interface{})
serverInfo := result["serverInfo"].(map[string]interface{})
sessionID := result["sessionId"]
protocolVersion := result["protocolVersion"]
s.logger.Info("Response summary: server=%s version=%s sessionId=%v protocolVersion=%v", serverInfo["name"], serverInfo["version"], sessionID, protocolVersion)

Copilot uses AI. Check for mistakes.
w.Write(respBytes)

Check failure on line 682 in pkg/server/server.go

View workflow job for this annotation

GitHub Actions / Run Tests

Error return value of `w.Write` is not checked (errcheck)
return
}

// Fallback to normal MCP handling
s.logger.Info("Received MCP request from %s: method=%v id=%v", r.RemoteAddr, req["method"], req["id"])
ctx := r.Context()
resp := s.mcpServer.HandleMessage(ctx, body)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
var respBytes []byte
switch v := resp.(type) {
case []byte:
respBytes = v
case string:
respBytes = []byte(v)
default:
respBytes, _ = json.Marshal(v)

Copilot AI Aug 1, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error from json.Marshal is being ignored. Consider handling the marshaling error to ensure robust error handling.

Suggested change
respBytes, _ = json.Marshal(v)
var err error
respBytes, err = json.Marshal(v)
if err != nil {
http.Error(w, "Failed to marshal response", http.StatusInternalServerError)
s.logger.Error("Failed to marshal response for %s: %v", r.RemoteAddr, err)
return
}

Copilot uses AI. Check for mistakes.
}
s.logger.Info("Response: %s", string(respBytes))

Copilot AI Aug 1, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Logging the full response may expose sensitive information in logs. Consider logging only a summary or sanitized version of the response for security purposes.

Suggested change
s.logger.Info("Response: %s", string(respBytes))
s.logger.Info("Response sent to %s: type=%T, length=%d bytes", r.RemoteAddr, resp, len(respBytes))

Copilot uses AI. Check for mistakes.
w.Write(respBytes)

Check failure on line 702 in pkg/server/server.go

View workflow job for this annotation

GitHub Actions / Run Tests

Error return value of `w.Write` is not checked (errcheck)
}

// Helper to get tool names
func (s *Server) getAllowedToolNames() []string {
tools, err := s.GetTools()
if err != nil {
return []string{}
}
names := make([]string, 0, len(tools))
for _, t := range tools {
names = append(names, t.Name)
}
return names
}
Loading