Files
ragflow/internal/service/mcp_test.go
web-dev0521 b8db200757 feat(go-api): implement MCP server management endpoints (#15281)
## Summary

Ports the MCP (Model Context Protocol) server management endpoints that
power `web/src/pages/user-setting/mcp/` from Python
(`api/apps/restful_apis/mcp_api.py`) to Go. There were no MCP routes in
the Go server before this change.

Closes #15275 (subtask of #15240).

## Endpoints implemented (base path `/api/v1`)

| Method | Path | Description |
|--------|------|-------------|
| GET | `/mcp/servers` | List tenant servers (keyword / order /
pagination) |
| POST | `/mcp/servers` | Create a server |
| GET | `/mcp/servers/{mcp_id}` | Get one (`?mode=download` exports
config) |
| PUT | `/mcp/servers/{mcp_id}` | Update a server |
| DELETE | `/mcp/servers/{mcp_id}` | Delete a server |
| POST | `/mcp/import` | Bulk import from JSON config |
| POST | `/mcp/servers/{mcp_id}/test` | Connect + list tools (see notes)
|

## Implementation

Follows the existing `handler → service → dao` layering (per PR #14790):

- **entity** (`internal/entity/mcp.go`): added `MCPServerType` constants
and `IsValidMCPServerType` over the existing `MCPServer` model.
- **dao** (`internal/dao/mcp.go`): new `MCPServerDAO` with tenant-scoped
CRUD, a keyword filter, and a **whitelisted order-column map** (guards
against SQL injection via the caller-supplied `orderby`).
- **service** (`internal/service/mcp.go`): new `MCPService` —
list/get/export/create/update/delete/import/test — mirroring
`MCPServerService` and the `mcp_api` request validation, with sentinel
errors for clean code mapping.
- **handler** (`internal/handler/mcp.go`): new `MCPHandler` with the
seven handlers and Python-compatible response codes.
- **router / server_main**: registered the `/mcp` group and wired the
handler.

## Deviations from Python (documented in code)

1. **Bulk import is at `POST /mcp/import`, not `/mcp/servers/import`.**
gin (v1.9.1) cannot register a static segment and a path param at the
same tree node, so `/mcp/servers/import` would collide with
`/mcp/servers/:mcp_id` and panic at startup. The frontend should call
`/mcp/import`.
2. **No live tool discovery on create/update/import.** The Python path
runs `get_mcp_tools` over SSE / streamable-HTTP and stores
`variables.tools`. The Go server has no MCP client yet, so these persist
`variables`/`headers` but leave `variables.tools` unpopulated.
3. **`/test` returns a data error (`ErrMCPTestUnsupported`)** until a Go
MCP client lands. Per the issue, the live-connection path is scoped as a
follow-up; the handler still validates `url` + `server_type`.

## Testing

- Added `internal/service/mcp_test.go` covering `IsValidMCPServerType`
and the `TestServer` validation/short-circuit paths (no DB required).
- No Go toolchain was available in the dev environment, so `go build
./...` / `go vet ./...` verification is left to CI.

## Follow-ups

- Go MCP client (SSE / streamable-HTTP) to enable live tool discovery
and the real `/test` behavior.
- Reconcile the `/mcp/import` vs `/mcp/servers/import` path with the
frontend.

---------
2026-06-05 13:25:09 +08:00

129 lines
3.9 KiB
Go

//
// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package service
import (
"errors"
"fmt"
"strings"
"testing"
"ragflow/internal/entity"
)
func TestIsValidMCPServerType(t *testing.T) {
for _, v := range []string{mcpServerTypeSSE, mcpServerTypeStreamableHTTP} {
if !isValidMCPServerType(v) {
t.Errorf("expected %q to be a valid MCP server type", v)
}
}
for _, v := range []string{"", "stdio", "http", "SSE"} {
if isValidMCPServerType(v) {
t.Errorf("expected %q to be an invalid MCP server type", v)
}
}
}
func TestServerInputValidation(t *testing.T) {
s := &MCPService{}
// Empty URL is rejected before any connection attempt.
if _, err := s.TestServer("id-1", &TestServerRequest{ServerType: mcpServerTypeSSE}); !errors.Is(err, ErrMCPInvalidURL) {
t.Errorf("expected ErrMCPInvalidURL for empty url, got %v", err)
}
// nil body is treated as empty URL.
if _, err := s.TestServer("id-1", nil); !errors.Is(err, ErrMCPInvalidURL) {
t.Errorf("expected ErrMCPInvalidURL for nil body, got %v", err)
}
// Invalid server type is rejected before connecting.
if _, err := s.TestServer("id-1", &TestServerRequest{URL: "http://example.com/sse", ServerType: "stdio"}); !errors.Is(err, ErrMCPInvalidType) {
t.Errorf("expected ErrMCPInvalidType for bad type, got %v", err)
}
}
func TestImportServersValidationErrors(t *testing.T) {
s := &MCPService{}
// Missing url and type produce an in-band error per entry rather than
// failing the batch.
configs := map[string]map[string]interface{}{
"missing-fields": {"foo": "bar"},
"bad-type": {"url": "http://example.com", "type": "stdio"},
}
results, err := s.ImportServers("tenant-1", configs, 1)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(results) != 2 {
t.Fatalf("expected 2 results, got %d", len(results))
}
for _, r := range results {
if r.Success {
t.Errorf("expected failure result for %q", r.Server)
}
if r.Server == "missing-fields" && !strings.Contains(r.Message, "Missing required fields") {
t.Errorf("unexpected message for missing-fields: %q", r.Message)
}
if r.Server == "bad-type" && !strings.Contains(r.Message, "Unsupported MCP server type") {
t.Errorf("unexpected message for bad-type: %q", r.Message)
}
}
}
func TestPaginateMCPServersNegativeValuesMatchPythonSlice(t *testing.T) {
servers := makeMCPServers(13)
got := paginateMCPServers(servers, -1, -2)
if len(got) != 0 {
t.Fatalf("expected empty page for negative pagination, got %d servers", len(got))
}
}
func TestPaginateMCPServersKeepsUnpagedList(t *testing.T) {
servers := makeMCPServers(3)
got := paginateMCPServers(servers, 0, 0)
if len(got) != len(servers) {
t.Fatalf("expected unpaged list length %d, got %d", len(servers), len(got))
}
}
func TestPaginateMCPServersPositiveValues(t *testing.T) {
servers := makeMCPServers(5)
got := paginateMCPServers(servers, 2, 2)
if len(got) != 2 {
t.Fatalf("expected 2 servers, got %d", len(got))
}
if got[0].ID != "server-3" || got[1].ID != "server-4" {
t.Fatalf("expected second page servers, got %q and %q", got[0].ID, got[1].ID)
}
}
func makeMCPServers(count int) []*entity.MCPServer {
servers := make([]*entity.MCPServer, 0, count)
for i := 1; i <= count; i++ {
servers = append(servers, &entity.MCPServer{ID: fmt.Sprintf("server-%d", i)})
}
return servers
}