Repository navigation
feat(go-api): implement MCP server management endpoints - #15281
Conversation
Port the MCP (Model Context Protocol) server management endpoints that power the user-setting MCP page from Python (api/apps/restful_apis/mcp_api.py) to Go. There were no MCP routes in the Go server before this change. New endpoints under /api/v1: - GET /mcp/servers list tenant servers (keyword/order/paginate) - POST /mcp/servers create - GET /mcp/servers/:mcp_id get one (mode=download exports config) - PUT /mcp/servers/:mcp_id update - DELETE /mcp/servers/:mcp_id delete - POST /mcp/import bulk import from JSON config - POST /mcp/servers/:mcp_id/test connect + list tools (see note) Layering follows the existing handler -> service -> dao pattern: - entity: add MCPServerType constants + IsValidMCPServerType over the existing MCPServer model - dao: new MCPServerDAO with tenant-scoped CRUD, keyword filter, and a whitelisted order-column map (guards against SQL injection) - service: new MCPService with list/get/export/create/update/delete/import/ test, mirroring MCPServerService and the mcp_api request validation - handler: new MCPHandler with the seven handlers and Python-compatible response codes - router/server_main: register the /mcp group and wire the handler Deviations from Python (documented in code): - Bulk import is served 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. - create/update/import persist variables/headers but do NOT run live tool discovery (Python's get_mcp_tools over SSE/streamable-HTTP); variables.tools is left unpopulated. - /test validates the request shape and returns a data error (ErrMCPTestUnsupported) until a Go MCP client lands. Per the issue, the live connection path is scoped as a follow-up. Refs infiniflow#15275
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds SSRF-safe URL validation and a pinned HTTP client, an MCP client (streamable-HTTP and SSE), service-layer bulk import and per-server testing with sentinel errors and timeouts, HTTP handlers for import/test, router wiring, and tests across these layers. ChangesMCP Server Management Extended
Sequence Diagram(s)sequenceDiagram
participant Client as Caller (Handler/Service)
participant URLCheck as AssertURLSafe
participant PinnedClient as PinnedHTTPClient
participant MCPServer as Remote MCP (streamable-http / SSE)
Client->>URLCheck: Validate raw URL
URLCheck-->>Client: hostname, resolvedIP or error
Client->>PinnedClient: hostname, resolvedIP, timeout
PinnedClient-->>Client: http.Client (pinned)
alt streamable-http
Client->>MCPServer: POST initialize + tools/list (JSON-RPC)
MCPServer-->>Client: tools result
else sse
Client->>MCPServer: GET SSE handshake
MCPServer-->>Client: endpoint event
Client->>MCPServer: POST initialize + tools/list
MCPServer-->>Client: tools result via SSE/json
end
Client-->>Client: parse and return tools[]
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/dao/mcp.go`:
- Around line 111-114: DeleteByID on MCPServerDAO currently deletes by id only,
leaving a TOCTOU tenant isolation gap; add a tenant-scoped delete method (e.g.,
DeleteByIDForTenant or DeleteByIDWithTenant) on MCPServerDAO that issues
DB.Where("id = ? AND tenant_id = ?", id,
tenantID).Delete(&entity.MCPServer{}).Error so the DAO enforces tenant scoping,
update all service/caller sites that previously used DeleteByID to call the new
tenant-scoped method (and remove or deprecate the old DeleteByID to avoid
misuse).
In `@internal/service/mcp.go`:
- Around line 306-313: In ImportServers update the existing presence checks for
url and type (variables url, stype in function ImportServers) to enforce
non-empty URL values and validate that stype is one of the supported server
types before persisting; when url == "" or stype is not in the allowed set
return an ImportResult{Server: serverName, Success:false, Message: "..."} with a
clear message, and also ensure the same stricter validation is applied to the
other import branch referenced around the second occurrence (the block around
the later checks). Use the existing ImportResult, serverName and mcpNameMaxBytes
checks and fail early for invalid/unsupported values rather than allowing them
through.
- Around line 223-225: The update validation currently only checks for oversized
names; ensure empty names are rejected too by changing the validation around the
name variable (the existing if that references mcpNameMaxBytes) to also fail
when name == "" and return ErrMCPInvalidName; update the conditional that uses
mcpNameMaxBytes so it checks (name == "" || len([]byte(name)) > mcpNameMaxBytes)
and returns ErrMCPInvalidName to match create behavior and Python parity.
- Around line 282-287: The current code checks ownership via s.mcpDAO.GetByID
and then calls s.mcpDAO.DeleteByID, which is not atomic; change to use a
tenant-scoped delete on the DAO (e.g., add/use DeleteByIDAndTenant(mcpID,
tenantID) or DeleteByIDWithTenant) so the delete itself enforces tenant
ownership and returns not-found if no row is deleted; update the caller in this
function to call that tenant-scoped delete and return ErrMCPNotFound when the
DAO indicates no matching record was deleted, removing the separate GetByID
ownership check.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 55a73732-dc33-4d02-a177-e4121e569033
📒 Files selected for processing (7)
cmd/server_main.gointernal/dao/mcp.gointernal/entity/mcp.gointernal/handler/mcp.gointernal/router/router.gointernal/service/mcp.gointernal/service/mcp_test.go
| url, hasURL := config["url"].(string) | ||
| stype, hasType := config["type"].(string) | ||
| if !hasType || !hasURL { | ||
| results = append(results, ImportResult{Server: serverName, Success: false, Message: "Missing required fields (type or url)"}) | ||
| continue | ||
| } | ||
| if serverName == "" || len([]byte(serverName)) > mcpNameMaxBytes { | ||
| results = append(results, ImportResult{Server: serverName, Success: false, Message: fmt.Sprintf("Invalid MCP name or length is %d which is large than 255.", len(serverName))}) |
There was a problem hiding this comment.
Import path misses server_type and URL-value validation.
ImportServers only checks that type/url keys exist and are strings; it does not reject empty URL or unsupported server types before persisting.
Suggested change
- if !hasType || !hasURL {
+ if !hasType || !hasURL || url == "" {
results = append(results, ImportResult{Server: serverName, Success: false, Message: "Missing required fields (type or url)"})
continue
}
+ if !entity.IsValidMCPServerType(stype) {
+ results = append(results, ImportResult{Server: serverName, Success: false, Message: "Unsupported MCP server type."})
+ continue
+ }Also applies to: 347-353
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/service/mcp.go` around lines 306 - 313, In ImportServers update the
existing presence checks for url and type (variables url, stype in function
ImportServers) to enforce non-empty URL values and validate that stype is one of
the supported server types before persisting; when url == "" or stype is not in
the allowed set return an ImportResult{Server: serverName, Success:false,
Message: "..."} with a clear message, and also ensure the same stricter
validation is applied to the other import branch referenced around the second
occurrence (the block around the later checks). Use the existing ImportResult,
serverName and mcpNameMaxBytes checks and fail early for invalid/unsupported
values rather than allowing them through.
|
Hi, @Hz-186 , |
## Summary - Add Go REST support for `GET /api/v1/system/healthz`. - Return Python-compatible `ok`/`nok` dependency fields for DB, Redis, document engine, and storage. - Return HTTP 200 only when all checks pass; otherwise return HTTP 500 with `_meta` failure details. - Add focused service coverage for the unhealthy dependency response when Go dependencies are not initialized. ## Scope This is a small, isolated slice of #15240. It avoids current open connector PRs (#15274, #15300, #15265, #15264), tenant/member PRs (#15295, #15301, #15276), MCP PRs (#15281, #15253, #15254, #15260, #15261, #15262), and the memory-message PR (#15256). Refs #15240
Upstream merged PR infiniflow#15260 (Go MCP server create API) which adds skeleton MCP files at the same paths our branch already added with full CRUD/list/ test/import logic. Five conflicting files reconciled as follows: - internal/dao/mcp.go, internal/handler/mcp.go, internal/service/mcp.go: add/add conflicts. Our versions are strict supersets of upstream's (handler 329 vs 65 lines, service 383 vs 154, dao 114 vs 43), so `git checkout --ours` keeps the full management implementation. - cmd/server_main.go: drop the duplicate `mcpService := service.NewMCPService()` and the upstream's NewMCPHandler(mcpService) call; keep our NewMCPHandler(mcpService, userService) form. Keep upstream's agentHandler wiring alongside. - internal/router/router.go: drop the duplicate mcpHandler field and parameter introduced by upstream's PR infiniflow#15260 (the original mcpHandler field/parameter our branch defined now refers to the same handler). Remove the upstream stub mcp group (just POST /servers) since our full mcp group covers it. Keep agentHandler from upstream's parallel PR. All MCP routes our PR added remain wired: GET /mcp/servers ListMCPServers POST /mcp/servers CreateMCPServer POST /mcp/import ImportMCPServers GET /mcp/servers/:mcp_id GetMCPServer PUT /mcp/servers/:mcp_id UpdateMCPServer DELETE /mcp/servers/:mcp_id DeleteMCPServer POST /mcp/servers/:mcp_id/test TestMCPServer
|
Actionable comments posted: 0 |
|
Hi, @Haruko386 , |
| { | ||
| mcp.GET("/servers", r.mcpHandler.ListMCPServers) | ||
| mcp.POST("/servers", r.mcpHandler.CreateMCPServer) | ||
| mcp.POST("/import", r.mcpHandler.ImportMCPServers) |
There was a problem hiding this comment.
hi, @web-dev0521
I think this PR overlaps with several other open MCP PRs, so please coordinate the scope instead of reimplementing all endpoints here:
GET /api/v1/mcp/serversis covered by feat: add Go MCP server list API #15253GET /api/v1/mcp/servers/:mcp_idis covered by feat: add Go MCP server get mcpid API #15254PUT /api/v1/mcp/servers/:mcp_idis covered by feat: add Go MCP server update API #15261DELETE /api/v1/mcp/servers/:mcp_idis covered by feat: add Go MCP server delete API #15262POST /api/v1/mcp/serversalready landed in main via feat: add Go MCP server create API #15260
The remaining useful scope should be POST /api/v1/mcp/servers/import and POST /api/v1/mcp/servers/:mcp_id/test.
A few issues with those two endpoints:
-
Import route is currently registered as
/api/v1/mcp/import, but Python uses/api/v1/mcp/servers/import. Please keep the compatible
path. -
Import does not validate
server_type, does not run URL safety checks, and does not fetch/store MCP tools like the Python implementation
does. -
The test route path is correct, but the logic is incomplete: it ignores
mcp_idand always returns “not implemented” for valid requests
instead of connecting to the MCP server and returning tools.
Please narrow this PR to the non-overlapping endpoints and align their behavior with api/apps/restful_apis/mcp_api.py.
Address review feedback on infiniflow#15281: per-server CRUD lives in the dedicated PRs (infiniflow#15253 list, infiniflow#15254 get, infiniflow#15260 create — merged, infiniflow#15261 update, infiniflow#15262 delete), so drop those handlers/services here and ship only the non-overlapping endpoints. POST /api/v1/mcp/servers/import bulk import from a JSON config POST /api/v1/mcp/servers/:mcp_id/test live tool-list probe Behavior is aligned with api/apps/restful_apis/mcp_api.py: - Import path corrected from /mcp/import to /mcp/servers/import. Gin v1.9.1's tree supports the static + param siblings under /servers/, so the prior workaround is no longer needed. - Both endpoints validate server_type, SSRF-guard the URL via utility.AssertURLSafe (new port of common/ssrf_guard.assert_url_is_safe with IPv4-mapped-IPv6 normalisation, link-local / private / CGNAT / doc-range checks), and DNS-pin the resolved IP into the HTTP client to close the rebinding window. - Tool discovery uses a new internal/mcpclient that implements the MCP handshake (initialize → notifications/initialized → tools/list) over both streamable-HTTP (single-endpoint JSON-RPC with optional inline SSE responses, Mcp-Session-Id propagation) and the legacy SSE transport (waits for the "endpoint" event, then POSTs JSON-RPC to the session URL while a goroutine dispatches SSE responses by id). - Import persists the discovered tools under variables.tools keyed by name, matching the Python create/import shape. - Test endpoint now uses mcp_id for log correlation, then opens a real session and returns the tools array; the previous "not implemented" response is gone. Tests cover the SSRF guard (loopback / CGNAT / IPv4-mapped IPv6 / doc-net / link-local / disallowed-scheme), MCP client (streamable-HTTP JSON, streamable-HTTP error, SSE round-trip, unsupported type, empty URL, ${var} substitution, JSON-RPC id normalisation), and the import / test input-validation paths.
|
Hi, @Hz-186 , |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/mcpclient/client_test.go`:
- Around line 51-59: The test HTTP handler inside httptest.NewServer (used in
TestFetchToolsStreamableHTTPJSON and TestFetchToolsSSE) calls t.Fatalf/t.Fatal
from the handler goroutine, which is unsafe; change those handler-side fatal
calls to signal errors back to the test goroutine or use t.Errorf plus immediate
return. Concretely, in the httptest.NewServer/HandleFunc handlers where you
currently call t.Fatalf (e.g., on JSON unmarshal error), replace that with
sending the error over a dedicated error channel (or calling t.Errorf and then
return from the handler) and then in the main test goroutine read that channel
and call t.Fatalf/fail the test there (or assert no error after the server
interaction). Update references in TestFetchToolsStreamableHTTPJSON and
TestFetchToolsSSE to use the channel or check for handler-side errors after the
request completes.
In `@internal/mcpclient/client.go`:
- Around line 337-350: The SSE-provided endpoint (variable endpoint/postURL)
must be re-validated before issuing POSTs to prevent SSRF bounces: inside
postOnce (and the POST retry paths for 403–429) run the same AssertURLSafe (or
the same host pinning logic used for the initial URL) against the resolved
postURL/endpoint and ensure the host (and scheme/port) matches the originally
allowed host(s) before creating the http.Request; update
waitForEndpoint/postOnce to perform this check and return an error if validation
fails.
In `@internal/service/mcp.go`:
- Around line 337-348: The current error return from mcpclient.FetchTools masks
URL-validation errors (so mcpErrorResponse treats them as 500s); when handling
the error from mcpclient.FetchTools in the block around mcpclient.FetchTools and
mcpID, detect URL validation failures (using errors.Is/As against the client’s
sentinel or validation error type from mcpclient) and return them as
ErrMCPInvalidURL (or wrap with %w) instead of formatting with %v; ensure the
returned error uses fmt.Errorf("Test MCP error (id=%s): %w", mcpID,
ErrMCPInvalidURL) or equivalent so mcpErrorResponse can classify it, referencing
mcpclient.FetchTools, ErrMCPInvalidURL, mcpErrorResponse and mcpID to locate the
change.
- Around line 223-247: The import loop currently skips config["headers"] and
only extracts a top-level authorization_token, causing custom headers to be lost
before calling mcpclient.FetchTools; update the logic so that you parse
config["headers"] (expected to be map[string]interface{} or similar) into
headerVals and stringVars (convert header values to strings into stringVars) and
merge them into the headers map passed to FetchTools while still
preserving/adding authorization_token for backward compatibility; ensure the
variables/header deletion for "tools" remains, and that the mcpclient.FetchTools
call uses the merged stringVars and headers/headerVals so tool discovery and
subsequent saving retain the custom headers.
In `@internal/utility/ssrf.go`:
- Around line 169-176: PinnedHTTPClient's transport currently uses Proxy:
http.ProxyFromEnvironment which allows requests to go through environment
proxies and bypass the DNS-pinning; update the transport configuration used in
PinnedHTTPClient (the transport variable with DialContext) to disable
environment proxies by setting Proxy to nil (or a no-op function) so that
DialContext's host/port substitution using hostname and resolvedIP always
controls the outbound connection via dialer.DialContext; ensure the change is
applied where transport is constructed and referenced so HTTPS tunneling or
proxying cannot override resolvedIP.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 253a3593-80a4-4b0d-8c11-d9b341b5f493
📒 Files selected for processing (8)
internal/handler/mcp.gointernal/mcpclient/client.gointernal/mcpclient/client_test.gointernal/router/router.gointernal/service/mcp.gointernal/service/mcp_test.gointernal/utility/ssrf.gointernal/utility/ssrf_test.go
| errors.Is(err, service.ErrMCPInvalidName), | ||
| errors.Is(err, service.ErrMCPInvalidURL): | ||
| c.JSON(http.StatusOK, gin.H{"code": common.CodeDataError, "data": nil, "message": mcpErrorMessage(err)}) | ||
| default: |
There was a problem hiding this comment.
MCP test failures should match Python’s DATA_ERROR response. Python returns Test MCP error: ... when get_tools fails, but the Go handler maps these fetch errors to SERVER_ERROR/HTTP 500. Please map connection/tool-list failures to the same data-error response.
| // from the URL path is threaded through to the connect call for log | ||
| // correlation; the connection itself is opened from the request body so the | ||
| // user can preview unsaved edits — matching Python's test_mcp. | ||
| type TestServerRequest struct { |
There was a problem hiding this comment.
The test endpoint should accept the same request body formats as Python. Python parses headers and variables with safe_json_parse, so JSON strings are accepted, and timeout can be a numeric string via get_float. The Go struct binding rejects those requests before reaching the service. Please add equivalent flexible parsing for these fields.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15281 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…op, test classification Address the five follow-up findings on the narrowed PR: - internal/utility/ssrf.go: PinnedHTTPClient was wired with Proxy: http.ProxyFromEnvironment, so an HTTP(S)_PROXY env var would route the connection through the proxy host instead of the pinned resolvedIP, defeating the whole DNS-pinning guard. Set Proxy: nil so the custom DialContext is the only path to the network. - internal/mcpclient/client.go (SSE): the initial SSE URL is SSRF-checked, but the "endpoint" event can replace it with an arbitrary absolute URL and postOnce was using that URL verbatim. A malicious public SSE server could bounce the POST phase to 127.0.0.1 / any internal host. Re-run utility.AssertURLSafe against the resolved postURL; when the host differs from the original SSE host, build a fresh PinnedHTTPClient so the dial-time IP override still applies. - internal/service/mcp.go (ImportServers): the import loop was skipping config["headers"] and only forwarding the top-level authorization_token. Any Python-shaped MCP entry that relies on custom headers would (a) fail tool discovery and (b) be persisted without the header set. Read headers from config["headers"] first, preserving them into both the live FetchTools call and the persisted entity.MCPServer; the authorization_token shortcut still fills in if the explicit map omitted it. - internal/service/mcp.go (TestServer): pre-validate the request URL with utility.AssertURLSafe and surface failures as ErrMCPInvalidURL so mcpErrorResponse classifies bad user input as a data error rather than a 500. FetchTools repeats the SSRF check internally; the duplicate call is cheap and keeps the classification honest. - internal/mcpclient/client_test.go: testing.T's Fatal* must run on the test goroutine. The streamable-HTTP and SSE handlers were calling t.Fatalf / t.Fatal from inside the httptest server goroutine, which would race with the test's own t.Cleanup path. Switch the in-handler calls to t.Errorf + http.Error so the failures surface but the goroutine stays well-behaved.
|
Hi, @Hz-186 , |
Resolve conflicts with the MCP delete PR (infiniflow#15262) that just landed on main. Both PRs add to the same MCP handler/router surface: internal/handler/mcp.go upstream added DeleteMCPServer at the position our ImportMCPServers / TestMCPServer / mcpErrorResponse block already lived. Auto-merge produced interleaved hunks; restored both: DeleteMCPServer first, then our import/test handlers and their helpers. internal/router/router.go upstream introduced a second mcp group at the old position with POST /servers and DELETE /servers/:mcp_id, while our PR had consolidated all MCP routes into a single group later in the file. Dropped the duplicate group (registering POST /servers twice would panic gin at startup) and folded the new DELETE /servers/:mcp_id into our consolidated group; bumped the comment to note infiniflow#15262 has also merged. internal/service/mcp.go auto-merged cleanly. DeleteMCPServer service + dao methods land via the upstream PR; no overlap with our import / test surface. DAO already exposes DeleteMCPServer(id, tenantID); the handler call through service.DeleteMCPServer(user.ID, mcp_id) compiles against the merged code without further changes.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
internal/service/mcp.go (1)
242-245: ⚡ Quick winReport name-resolution failures per server instead of aborting the batch.
A DAO error from
nextAvailableMCPNamereturnsnil, errfor the whole call, discarding theImportResults for servers already created in earlier iterations and leaving the caller blind to that partial state. This is inconsistent with theFetchTools/CreateMCPServerfailures below, which append a failed result and continue.♻️ Make name-resolution errors per-server
- baseName := serverName - newName, err := s.nextAvailableMCPName(baseName, tenantID) - if err != nil { - return nil, err - } + baseName := serverName + newName, err := s.nextAvailableMCPName(baseName, tenantID) + if err != nil { + results = append(results, ImportResult{Server: serverName, Success: false, Message: "Failed to resolve a unique MCP name."}) + continue + }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/service/mcp.go` around lines 242 - 245, The call to s.nextAvailableMCPName currently returns nil, err which aborts the entire import and discards prior ImportResult entries; change the behavior to treat name-resolution failures like the other per-server errors: inside the loop where newName, err := s.nextAvailableMCPName(baseName, tenantID) is called, do not return on error — instead append an ImportResult for that specific server indicating failure (include the error and server identity), and continue to the next iteration; this mirrors how FetchTools and CreateMCPServer failures are handled and preserves reporting of already-created servers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Nitpick comments:
In `@internal/service/mcp.go`:
- Around line 242-245: The call to s.nextAvailableMCPName currently returns nil,
err which aborts the entire import and discards prior ImportResult entries;
change the behavior to treat name-resolution failures like the other per-server
errors: inside the loop where newName, err := s.nextAvailableMCPName(baseName,
tenantID) is called, do not return on error — instead append an ImportResult for
that specific server indicating failure (include the error and server identity),
and continue to the next iteration; this mirrors how FetchTools and
CreateMCPServer failures are handled and preserves reporting of already-created
servers.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: cb7781f1-35cc-4b48-8bdf-bfe699e90183
📒 Files selected for processing (3)
internal/handler/mcp.gointernal/router/router.gointernal/service/mcp.go
🚧 Files skipped from review as they are similar to previous changes (1)
- internal/handler/mcp.go
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
Hi, @web-dev0521
I tested only the two new MCP endpoints against both Python and Go with curl: POST /api/v1/mcp/servers/import and POST /api/v1/mcp/servers/:mcp_id/test.
Most import/test validation paths match, but there are two API compatibility gaps:
POST /mcp/servers/importwith a missingmcpServerskey returns Pythoncode: 101(required argument are missing: mcpServers;)while Go returnscode: 102(No MCP servers provided.).POST /mcp/servers/:mcp_id/testcollapses URL validation errors toInvalid url.in Go, while Python returnsInvalid MCP url.forempty URLs and preserves the detailed SSRF validation message for unsafe URLs.
Please keep the fix scoped to these MCP import/test handler behaviors and avoid expanding this PR into unrelated MCP CRUD changes.
Python: {"code":101,"data":null,"message":"required argument are missing: mcpServers; "}
Go: {"code":102,"data":null,"message":"No MCP servers provided."}
test empty url:
Python: {"code":102,"message":"Invalid MCP url."}
Go: {"code":102,"data":null,"message":"Invalid url."}
test unsafe localhost url:
Python: {"code":102,"message":"URL resolves to a non-public address (127.0.0.1), which is not allowed."}
Go: {"code":102,"data":null,"message":"Invalid url."}
Address the two API-compatibility gaps Hz-186 found by curl-comparing
the Go and Python endpoints:
1. POST /mcp/servers/import with a MISSING mcpServers key now returns
code 101 (ARGUMENT_ERROR) with message
"required argument are missing: mcpServers; " — matching Python's
@validate_request("mcpServers") decorator output, including the
trailing "; " separator. A mcpServers key that is PRESENT but empty
still returns 102 with "No MCP servers provided." per Python's
handler body. The handler now reads the raw body into
map[string]json.RawMessage so the two cases can be distinguished.
2. POST /mcp/servers/:mcp_id/test now surfaces the SSRF guard's
per-failure detail verbatim instead of collapsing every URL
failure to "Invalid url.":
empty URL -> "Invalid MCP url." (Python parity)
disallowed scheme -> guard detail (e.g. "Disallowed URL scheme: 'ftp'. ...")
non-public addr -> guard detail ("URL resolves to a non-public address (...).")
service.TestServer already wraps these as
fmt.Errorf("%w: <detail>", ErrMCPInvalidURL); the handler's
mcpErrorMessage now strips the sentinel prefix and returns the
detail when present, falling back to the Python-default
"Invalid url." only when the bare sentinel arrives with no wrapped
message.
Scope: this PR continues to touch ONLY the import + test handler
behavior, not any of the MCP CRUD endpoints owned by infiniflow#15253 / infiniflow#15254 /
infiniflow#15261 / infiniflow#15262.
|
Hi, @Hz-186 , |
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
POST /api/v1/mcp/servers/test-id/test
Body:
{"server_type":"streamable-http","url":"http://1.1.1.1/","timeout":3}
py: {"code":102,"message":"Test MCP error: Timeout when fetching tools from MCP server: test-id (timeout=3.0)"}
go: {"code":500,"data":null,"message":"Test MCP error (id=test-id): parse MCP response: invalid character '<' looking for beginning of value"}
The validation mismatches for import/test are fixed, but POST /mcp/servers/:mcp_id/test still differs when the URL is reachable but not a valid MCP server.
With body {"server_type":"streamable-http","url":"http://1.1.1.1/","timeout":3}, Python returns HTTP 200 with code: 102 and a Test MCP error: ... message, while Go returns HTTP 500 / code: 500.
Please keep the fix scoped to the MCP test endpoint: MCP connection/protocol/tool-fetch failures should be returned as data errors (code: 102) to match Python, instead of falling through to the handler's generic server-error branch.
by the way, "data":null part is not your problem, you dont have to deal with it
|
@Hz-186 , Please review this again. |
There was a problem hiding this comment.
@web-dev0521
Most import/test cases are aligned with Python now, including invalid type, empty URL, SSRF-blocked URLs, and fetch failures returning code: 102.
One small parity gap remains for POST /api/v1/mcp/servers/{mcp_id}/test: when url or server_type is missing from the JSON body, Python's @validate_request("url", "server_type") returns code: 101, while Go currently falls through to service validation and returns code: 102. Please add a handler-level required-field check to match Python.
|
@Hz-186 , Fixied! |
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
@web-dev0521, LGTM ! ! !
|
Hi, @JinHai-CN , |
|
@web-dev0521 would you please resolve the conflicts? |
|
@web-dev0521, would you please resolve the conflicts? |
Resolve MCP overlap with upstream's per-server CRUD/list endpoints (infiniflow#15253-infiniflow#15262). Kept both feature sets as a union: - handler/mcp.go: keep upstream ListMCPServers + page/getMCPIDs helpers alongside this PR's import/test handlers and error mapping; merged the import set (encoding/json, errors, fmt, io, net/http, strconv, strings). - router.go: collapse the two mcp groups into one; add GET /servers (ListMCPServers) to this PR's group that already had create/delete/ import/test. - service/mcp.go: keep both consts (defaultMCPFetchTimeoutSec, mcpServerDateFormat); keep import/test service code and upstream's date/pagination helpers used by ListMCPServers. - service/mcp_test.go: union of imports (errors, fmt, strings, testing, entity) and both test groups (validation + pagination).
Resolve overlap with upstream's new MCP update endpoint: - handler/mcp.go: keep this PR's import/test handlers + error helpers alongside upstream's newMCPServerResponse / formatMCPServerDate helpers (used by UpdateMCPServer). entity/time imports auto-merged. - router.go: collapse duplicate mcp groups into one; add upstream's PUT /servers/:mcp_id (UpdateMCPServer) to the group that already has create/list/delete/import/test. - service/mcp.go: import union (keep mcpclient + utility for import/test; add gorm used by UpdateMCPServer); bodies auto-merged.
…491 passed, 1 teardown error from a 30s DELETE /datasets timeout unrelated to MCP changes. Go build, unit, and Infinity SDK steps all passed.
|
Hi, @yingfeng , |
|
Hi, @yingfeng , |
|
@yingfeng, Thank you! |
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)/mcp/servers/mcp/servers/mcp/servers/{mcp_id}?mode=downloadexports config)/mcp/servers/{mcp_id}/mcp/servers/{mcp_id}/mcp/import/mcp/servers/{mcp_id}/testImplementation
Follows the existing
handler → service → daolayering (per PR #14790):internal/entity/mcp.go): addedMCPServerTypeconstants andIsValidMCPServerTypeover the existingMCPServermodel.internal/dao/mcp.go): newMCPServerDAOwith tenant-scoped CRUD, a keyword filter, and a whitelisted order-column map (guards against SQL injection via the caller-suppliedorderby).internal/service/mcp.go): newMCPService— list/get/export/create/update/delete/import/test — mirroringMCPServerServiceand themcp_apirequest validation, with sentinel errors for clean code mapping.internal/handler/mcp.go): newMCPHandlerwith the seven handlers and Python-compatible response codes./mcpgroup and wired the handler.Deviations from Python (documented in code)
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/importwould collide with/mcp/servers/:mcp_idand panic at startup. The frontend should call/mcp/import.get_mcp_toolsover SSE / streamable-HTTP and storesvariables.tools. The Go server has no MCP client yet, so these persistvariables/headersbut leavevariables.toolsunpopulated./testreturns 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 validatesurl+server_type.Testing
internal/service/mcp_test.gocoveringIsValidMCPServerTypeand theTestServervalidation/short-circuit paths (no DB required).go build ./.../go vet ./...verification is left to CI.Follow-ups
/testbehavior./mcp/importvs/mcp/servers/importpath with the frontend.