-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Add MCP service and routing #3261
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
fiftin
wants to merge
1
commit into
develop
Choose a base branch
from
codex/create-mcp-service-package-and-endpoints
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+266
−1
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -28,6 +28,7 @@ func TestApiPing(t *testing.T) { | |
nil, | ||
nil, | ||
nil, | ||
nil, | ||
) | ||
|
||
r.ServeHTTP(rr, req) | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
package mcp | ||
|
||
import ( | ||
"net/http/httptest" | ||
"testing" | ||
|
||
"github.com/gorilla/mux" | ||
"github.com/gorilla/websocket" | ||
|
||
"github.com/semaphoreui/semaphore/db" | ||
mcpservice "github.com/semaphoreui/semaphore/services/mcp" | ||
) | ||
|
||
type mockProjectStore struct { | ||
projects []db.Project | ||
} | ||
|
||
func (m *mockProjectStore) GetAllProjects() ([]db.Project, error) { | ||
return m.projects, nil | ||
} | ||
|
||
type mockTaskPool struct{} | ||
|
||
func (m *mockTaskPool) AddTask(task db.Task, userID *int, username string, projectID int, needAlias bool) (db.Task, error) { | ||
task.ID = 1 | ||
return task, nil | ||
} | ||
|
||
func setupServer(t *testing.T) (*websocket.Conn, func()) { | ||
store := &mockProjectStore{projects: []db.Project{{ID: 1, Name: "demo"}}} | ||
pool := &mockTaskPool{} | ||
srv := mcpservice.NewServer(store, pool) | ||
r := mux.NewRouter() | ||
Route(r, srv) | ||
ts := httptest.NewServer(r) | ||
wsURL := "ws" + ts.URL[len("http"):len(ts.URL)] + "/mcp/ws" | ||
conn, _, err := websocket.DefaultDialer.Dial(wsURL, nil) | ||
if err != nil { | ||
t.Fatalf("dial: %v", err) | ||
} | ||
cleanup := func() { conn.Close(); ts.Close() } | ||
return conn, cleanup | ||
} | ||
|
||
func TestHandshakeAndListProjects(t *testing.T) { | ||
conn, cleanup := setupServer(t) | ||
defer cleanup() | ||
|
||
if err := conn.WriteJSON(map[string]string{"command": "handshake"}); err != nil { | ||
t.Fatalf("write handshake: %v", err) | ||
} | ||
var resp map[string]interface{} | ||
if err := conn.ReadJSON(&resp); err != nil { | ||
t.Fatalf("read handshake: %v", err) | ||
} | ||
if resp["status"] != "ok" { | ||
t.Fatalf("handshake failed: %v", resp) | ||
} | ||
|
||
if err := conn.WriteJSON(map[string]string{"command": "list_projects"}); err != nil { | ||
t.Fatalf("write list: %v", err) | ||
} | ||
var list struct { | ||
Projects []db.Project `json:"projects"` | ||
} | ||
if err := conn.ReadJSON(&list); err != nil { | ||
t.Fatalf("read list: %v", err) | ||
} | ||
if len(list.Projects) != 1 || list.Projects[0].Name != "demo" { | ||
t.Fatalf("unexpected projects: %+v", list.Projects) | ||
} | ||
} | ||
|
||
func TestTriggerTask(t *testing.T) { | ||
conn, cleanup := setupServer(t) | ||
defer cleanup() | ||
_ = conn.WriteJSON(map[string]string{"command": "handshake"}) | ||
_ = conn.ReadJSON(&map[string]interface{}{}) | ||
|
||
if err := conn.WriteJSON(map[string]interface{}{"command": "trigger_task", "project_id": 1, "template_id": 2}); err != nil { | ||
t.Fatalf("write trigger: %v", err) | ||
} | ||
var resp struct { | ||
TaskID int `json:"task_id"` | ||
} | ||
if err := conn.ReadJSON(&resp); err != nil { | ||
t.Fatalf("read trigger: %v", err) | ||
} | ||
if resp.TaskID != 1 { | ||
t.Fatalf("unexpected task id: %d", resp.TaskID) | ||
} | ||
} | ||
|
||
func TestUnknownCommand(t *testing.T) { | ||
conn, cleanup := setupServer(t) | ||
defer cleanup() | ||
_ = conn.WriteJSON(map[string]string{"command": "handshake"}) | ||
_ = conn.ReadJSON(&map[string]interface{}{}) | ||
|
||
if err := conn.WriteJSON(map[string]string{"command": "bad"}); err != nil { | ||
t.Fatalf("write bad: %v", err) | ||
} | ||
var resp map[string]interface{} | ||
if err := conn.ReadJSON(&resp); err != nil { | ||
t.Fatalf("read bad: %v", err) | ||
} | ||
if resp["error"] != "unknown_command" { | ||
t.Fatalf("unexpected response: %v", resp) | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package mcp | ||
|
||
import ( | ||
"github.com/gorilla/mux" | ||
mcpservice "github.com/semaphoreui/semaphore/services/mcp" | ||
) | ||
|
||
// Route mounts MCP handlers under /mcp. | ||
func Route(r *mux.Router, srv *mcpservice.Server) { | ||
if srv == nil { | ||
return | ||
} | ||
sub := r.PathPrefix("/mcp").Subrouter() | ||
sub.HandleFunc("/ws", srv.ServeWS).Methods("GET", "HEAD") | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
package mcp | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/gorilla/websocket" | ||
"github.com/semaphoreui/semaphore/db" | ||
) | ||
|
||
// ProjectService defines the methods required to list projects. | ||
type ProjectService interface { | ||
GetAllProjects() ([]db.Project, error) | ||
} | ||
|
||
// TaskService defines the methods required to trigger tasks. | ||
type TaskService interface { | ||
AddTask(task db.Task, userID *int, username string, projectID int, needAlias bool) (db.Task, error) | ||
} | ||
|
||
// Server implements a minimal Model Context Protocol server. | ||
type Server struct { | ||
projects ProjectService | ||
tasks TaskService | ||
} | ||
|
||
// NewServer creates a new MCP server. | ||
func NewServer(projects ProjectService, tasks TaskService) *Server { | ||
return &Server{projects: projects, tasks: tasks} | ||
} | ||
|
||
// request represents a client command. | ||
type request struct { | ||
Command string `json:"command"` | ||
ProjectID int `json:"project_id,omitempty"` | ||
TemplateID int `json:"template_id,omitempty"` | ||
} | ||
|
||
// response is sent back to the client. | ||
type response struct { | ||
Command string `json:"command,omitempty"` | ||
Status string `json:"status,omitempty"` | ||
Error string `json:"error,omitempty"` | ||
Projects []db.Project `json:"projects,omitempty"` | ||
TaskID int `json:"task_id,omitempty"` | ||
} | ||
|
||
var upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} | ||
|
||
// ServeWS upgrades the connection to WebSocket and handles MCP commands. | ||
func (s *Server) ServeWS(w http.ResponseWriter, r *http.Request) { | ||
conn, err := upgrader.Upgrade(w, r, nil) | ||
if err != nil { | ||
http.Error(w, err.Error(), http.StatusInternalServerError) | ||
return | ||
} | ||
defer conn.Close() | ||
|
||
handshaked := false | ||
for { | ||
var req request | ||
if err := conn.ReadJSON(&req); err != nil { | ||
return | ||
} | ||
|
||
if !handshaked && req.Command != "handshake" { | ||
_ = conn.WriteJSON(response{Error: "handshake_required"}) | ||
continue | ||
} | ||
|
||
switch req.Command { | ||
case "handshake": | ||
handshaked = true | ||
_ = conn.WriteJSON(response{Command: "handshake", Status: "ok"}) | ||
case "list_projects": | ||
projects, err := s.projects.GetAllProjects() | ||
if err != nil { | ||
_ = conn.WriteJSON(response{Command: "list_projects", Error: err.Error()}) | ||
continue | ||
} | ||
_ = conn.WriteJSON(response{Command: "list_projects", Projects: projects}) | ||
case "trigger_task": | ||
task, err := s.tasks.AddTask(db.Task{TemplateID: req.TemplateID}, nil, "", req.ProjectID, false) | ||
if err != nil { | ||
_ = conn.WriteJSON(response{Command: "trigger_task", Error: err.Error()}) | ||
continue | ||
} | ||
_ = conn.WriteJSON(response{Command: "trigger_task", TaskID: task.ID, Status: "queued"}) | ||
default: | ||
_ = conn.WriteJSON(response{Error: "unknown_command"}) | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P0] Gate MCP websocket behind authentication
The new MCP route is mounted directly on the root router without any of the existing authentication or store middlewares, so
/mcp/ws
is publicly reachable by anyone who can hit the server. Becauseservices/mcp/server.go
exposes operations likelist_projects
andtrigger_task
using real services, an unauthenticated client can enumerate projects and enqueue tasks. This bypasses all permission checks and effectively gives remote callers full task execution rights; the handler should be placed under the authenticated API subrouter or otherwise enforce authentication before accepting commands.Useful? React with 👍 / 👎.