Repository navigation
feat: add Go MCP server update API - #15261
Conversation
|
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:
📝 WalkthroughWalkthroughThis PR implements a tenant-scoped MCP server update endpoint, adding DAO query/update methods, service-layer business logic with field validation and JSON coercion, an HTTP handler with response formatting, and wiring the new route into the protected API group. ChangesMCP Server Update Implementation
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 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: 3
🤖 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/service/mcp.go`:
- Around line 53-56: The current check conflates datastore read errors from
s.mcpServerDAO.GetByID with authorization/not-found cases; update the logic so
that if GetByID returns a non-nil err you return an internal/backend error
(e.g., common.CodeInternalError) along with the wrapped read error (include the
original err and mcpID in the message), and only if err == nil but server is nil
or server.TenantID != tenantID return the client-facing not-found/authorization
error (common.CodeDataError) with the existing "Cannot find MCP server" message;
refer to s.mcpServerDAO.GetByID, server.TenantID, tenantID, and the current
CodeDataError usage to locate and split the two branches.
- Around line 129-135: The code treats UpdateMCPServer's boolean 'updated' as an
error when false, which incorrectly fails idempotent/no-op PUTs; instead, do not
return an error when 'updated' is false—either remove the error branch or
convert it to a debug/log message and continue as a successful outcome (i.e.,
treat zero rows affected as a valid no-op). Update the logic around
UpdateMCPServer (the call using mcpID, tenantID, updates and the 'updated'
variable) so that only actual errors from UpdateMCPServer cause a server error
return, while !updated is handled as success (or handled by returning the
current resource) rather than returning CodeDataError.
- Around line 148-151: The helper optionalString incorrectly treats an explicit
JSON "null" payload as present (ok=true), which can clear fields; update
optionalString (used with UpdateMCPServerRequest) so that when raw is present
but bytes.TrimSpace(raw) equals []byte("null") you treat it as not provided
(return "", false, nil) instead of returning ok=true—i.e., change the branch
that checks for "null" to set ok=false and return nil error so callers won't
overwrite fields with null.
🪄 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: 42aabe5b-5159-4227-aaf2-664f8a2fd5cb
📒 Files selected for processing (5)
cmd/server_main.gointernal/dao/mcp.gointernal/handler/mcp.gointernal/router/router.gointernal/service/mcp.go
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
internal/service/mcp.go (1)
147-149:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPreserve server errors on the post-update re-read.
If the write succeeds and the follow-up fetch hits a transient datastore error, this still returns
CodeDataErroreven though the update may already be committed. Split not-found from backend failures here the same way as the initial lookup.🤖 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 147 - 149, After re-reading the server with s.mcpServerDAO.GetByIDAndTenant(mcpID, tenantID) assign the result to updatedServer, detect whether the error represents a "not found" case versus a backend/transient failure (same checks used in the initial lookup), and return the corresponding status code for not-found (e.g., CodeNotFound) separately from backend errors (CodeDataError); in other words, split the error path so a transient fetch error after a successful update returns a data/backend error while a true missing record returns the not-found code, using the same error-identification logic as the first GetByIDAndTenant call.
🤖 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/service/mcp.go`:
- Around line 68-75: The code treats an explicit empty "server_type" as provided
and later checks serverType != "" which misses this case; change the validation
to check serverTypeProvided (the flag set by optionalString) when deciding to
validate with isValidMCPServerType(serverType) so that an explicitly supplied
empty string is rejected, i.e., replace the condition "if serverType != "" &&
!isValidMCPServerType(serverType)" with a check that uses serverTypeProvided &&
!isValidMCPServerType(serverType); apply the same fix to the analogous block
around the second occurrence (the code at the later MCP handling near lines
132-133).
- Around line 92-99: The URL acceptance logic in mcp.go currently trusts
optionalString and only checks serverURL == "", so values like " " slip
through; update the handling around optionalString/ serverURL/ serverURLProvided
to trim whitespace (e.g., use strings.TrimSpace on the returned value) and
validate that the trimmed string is non-empty before assigning serverURL and
serverURLProvided, returning the same data error (errors.New("Invalid url."))
when the trimmed value is empty.
---
Duplicate comments:
In `@internal/service/mcp.go`:
- Around line 147-149: After re-reading the server with
s.mcpServerDAO.GetByIDAndTenant(mcpID, tenantID) assign the result to
updatedServer, detect whether the error represents a "not found" case versus a
backend/transient failure (same checks used in the initial lookup), and return
the corresponding status code for not-found (e.g., CodeNotFound) separately from
backend errors (CodeDataError); in other words, split the error path so a
transient fetch error after a successful update returns a data/backend error
while a true missing record returns the not-found code, using the same
error-identification logic as the first GetByIDAndTenant call.
🪄 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: 890458a3-30b3-4240-9763-1490d6cf4b0d
📒 Files selected for processing (1)
internal/service/mcp.go
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
internal/service/mcp.go (2)
91-103:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winTrim the stored URL before the final emptiness check.
Line 102 only rejects an exact empty string. If an existing row already contains
" "and this request updates some other field, the update still succeeds with an unusable endpoint.Proposed fix
- serverURL := server.URL + serverURL := strings.TrimSpace(server.URL) serverURLProvided := false if value, ok, err := optionalString(req, "url"); err != nil { return nil, common.CodeDataError, err } else if ok { serverURL = strings.TrimSpace(value)🤖 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 91 - 103, The final emptiness check uses serverURL as-is, so an existing DB value of only whitespace (e.g. " ") will bypass validation; before the final check (the if serverURL == "" block) trim serverURL with strings.TrimSpace(serverURL) so whitespace-only values become empty and are rejected. Refer to the serverURL variable and serverURLProvided flag and perform the TrimSpace call just prior to the emptiness check that returns CodeDataError.
107-116:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReject malformed
headers/variablesinstead of coercing them to{}.
safeJSONMapcurrently turns wrong-shaped or unparsable payloads into an empty map, and Lines 107-116 persist that result whenever the key is present. A request like{"headers":[]}or{"variables":"{\"bad\":}"}will silently wipe existing config instead of failing validation.Proposed fix
- if raw, ok := req["headers"]; ok { - headers = safeJSONMap(raw) + if raw, ok := req["headers"]; ok { + parsed, err := safeJSONMap(raw, "headers") + if err != nil { + return nil, common.CodeDataError, err + } + headers = parsed } @@ - if raw, ok := req["variables"]; ok { - variables = safeJSONMap(raw) + if raw, ok := req["variables"]; ok { + parsed, err := safeJSONMap(raw, "variables") + if err != nil { + return nil, common.CodeDataError, err + } + variables = parsed } @@ -func safeJSONMap(raw json.RawMessage) entity.JSONMap { +func safeJSONMap(raw json.RawMessage, key string) (entity.JSONMap, error) { raw = bytes.TrimSpace(raw) if len(raw) == 0 || bytes.Equal(raw, []byte("null")) { - return entity.JSONMap{} + return entity.JSONMap{}, nil } var value map[string]interface{} if err := json.Unmarshal(raw, &value); err == nil && value != nil { - return entity.JSONMap(value) + return entity.JSONMap(value), nil } var textValue string - if err := json.Unmarshal(raw, &textValue); err != nil || textValue == "" { - return entity.JSONMap{} + if err := json.Unmarshal(raw, &textValue); err != nil || strings.TrimSpace(textValue) == "" { + return nil, fmt.Errorf("%s must be a JSON object", key) } - if err := json.Unmarshal([]byte(textValue), &value); err != nil || value == nil { - return entity.JSONMap{} + if err := json.Unmarshal([]byte(textValue), &value); err != nil || value == nil { + return nil, fmt.Errorf("%s must be a JSON object", key) } - return entity.JSONMap(value) + return entity.JSONMap(value), nil }Also applies to: 201-220
🤖 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 107 - 116, The handler currently uses safeJSONMap to coerce malformed "headers" or "variables" into an empty map whenever the key exists, wiping server defaults; change the logic so that if req contains "headers" or "variables" and safeJSONMap returns nil/invalid, the request is rejected with an error instead of silently assigning {} — locate the blocks referencing req["headers"], req["variables"], the variables := server.Variables assignment and the headers variable, and replace the coercion with explicit validation: if the key is present but safeJSONMap fails, return a validation error (same error path used by the handler), otherwise use the returned map; apply the same change to the other occurrence mentioned (lines around 201-220).
🤖 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.
Outside diff comments:
In `@internal/service/mcp.go`:
- Around line 91-103: The final emptiness check uses serverURL as-is, so an
existing DB value of only whitespace (e.g. " ") will bypass validation; before
the final check (the if serverURL == "" block) trim serverURL with
strings.TrimSpace(serverURL) so whitespace-only values become empty and are
rejected. Refer to the serverURL variable and serverURLProvided flag and perform
the TrimSpace call just prior to the emptiness check that returns CodeDataError.
- Around line 107-116: The handler currently uses safeJSONMap to coerce
malformed "headers" or "variables" into an empty map whenever the key exists,
wiping server defaults; change the logic so that if req contains "headers" or
"variables" and safeJSONMap returns nil/invalid, the request is rejected with an
error instead of silently assigning {} — locate the blocks referencing
req["headers"], req["variables"], the variables := server.Variables assignment
and the headers variable, and replace the coercion with explicit validation: if
the key is present but safeJSONMap fails, return a validation error (same error
path used by the handler), otherwise use the returned map; apply the same change
to the other occurrence mentioned (lines around 201-220).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 3322f3ca-0c9b-4606-b2cb-4059a204e16c
📒 Files selected for processing (1)
internal/service/mcp.go
## 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
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
hi, @Helios531
Could u help fix these compatibility issues in the Go MCP update endpoint?
| "code": common.CodeSuccess, | ||
| "message": "success", | ||
| "data": result, | ||
| }) |
There was a problem hiding this comment.
Returning the raw entity.MCPServer also makes the date format incompatible with the Python API.
The Go API currently returns create_date / update_date as RFC3339 strings with timezone, for example:
"create_date": "2026-05-28T10:30:20+08:00"The Python API returns these fields without timezone:
"create_date": "2026-05-28T10:30:20"
Please format these fields explicitly in a response DTO before returning the response, for example with t.Format("2006-01-02T15:04:05").
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": common.CodeSuccess, | ||
| "message": "success", | ||
| "data": result, |
There was a problem hiding this comment.
Hi, @Helios531
Please avoid returning entity.MCPServer directly here.
When description is updated to null, the Python API keeps the field in the response:
"description": nullBut the Go API omits description entirely because the raw entity uses:
Description *string json:"description,omitempty"
Since Description is nil, omitempty removes the field during JSON serialization. To keep this endpoint compatible with
Python, please return a dedicated response DTO instead of the raw entity, and keep nullable fields such as description in
the JSON response.
For example:
type MCPServerResponse struct {
ID string `json:"id"`
Name string `json:"name"`
TenantID string `json:"tenant_id"`
URL string `json:"url"`
ServerType string `json:"server_type"`
Description *string `json:"description"`
Variables map[string]interface{} `json:"variables"`
Headers map[string]interface{} `json:"headers"`
CreateTime *int64 `json:"create_time"`
CreateDate string `json:"create_date"`
UpdateTime *int64 `json:"update_time"`
UpdateDate string `json:"update_date"`
}Then return the DTO here instead of result.
|
Actionable comments posted: 0 |
|
Hi, @Hz-186, can you review my PR, plz? |
d83c417 to
4d61858
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
internal/dao/mcp.go (1)
45-52: ⚡ Quick winConsider whether GetByID is necessary.
The service layer calls
GetByIDand then separately validates tenant ownership. Since the service returns the same error message for both "server not found" and "wrong tenant" cases, this two-step pattern could be simplified to a singleGetByIDAndTenantcall, which would:
- Reduce query count by one
- Enforce tenant isolation at the DAO layer
- Simplify the service logic
If
GetByIDis only used in the update flow and not needed elsewhere, consider removing this method and updating the service to useGetByIDAndTenantdirectly.🤖 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/dao/mcp.go` around lines 45 - 52, Replace the two-step lookup with a tenant-scoped DAO call: add or use a method on MCPServerDAO named GetByIDAndTenant(id, tenantID) that queries DB.Where("id = ? AND tenant_id = ?", id, tenantID).First(&server) and returns the server or not-found error, update the service code paths (including the update flow) to call GetByIDAndTenant instead of GetByID plus a separate tenant check, and remove GetByID if it is no longer used to avoid duplicate queries and ensure tenant isolation at the DAO layer.
🤖 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/dao/mcp.go`:
- Around line 45-52: Replace the two-step lookup with a tenant-scoped DAO call:
add or use a method on MCPServerDAO named GetByIDAndTenant(id, tenantID) that
queries DB.Where("id = ? AND tenant_id = ?", id, tenantID).First(&server) and
returns the server or not-found error, update the service code paths (including
the update flow) to call GetByIDAndTenant instead of GetByID plus a separate
tenant check, and remove GetByID if it is no longer used to avoid duplicate
queries and ensure tenant isolation at the DAO layer.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: e56eaff3-ec3a-4dbc-a304-ad863f94470c
📒 Files selected for processing (5)
internal/dao/mcp.gointernal/handler/mcp.gointernal/handler/mcp_test.gointernal/router/router.gointernal/service/mcp.go
💤 Files with no reviewable changes (4)
- internal/handler/mcp_test.go
- internal/handler/mcp.go
- internal/router/router.go
- internal/service/mcp.go
|
hi, @Hz-186 , can you review my PR, pls? |
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.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15261 +/- ##
=======================================
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 Sentry. 🚀 New features to boost your workflow:
|
|
@Helios531 would you please fix the conflicts? |
tmimmanuel
left a comment
There was a problem hiding this comment.
@JinHai-CN This is ready.
…server # Conflicts: # internal/dao/mcp.go # internal/handler/mcp.go # internal/router/router.go # internal/service/mcp.go
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.
|
@Helios531 @web-dev0521 Would you please resolve the conflicts? |
…server # Conflicts: # internal/dao/mcp.go # internal/handler/mcp.go # internal/router/router.go # internal/service/mcp.go
What
#15240
implementation for PUT /api/v1/mcp/servers/:mcp_id
Changes
PUT /api/v1/mcp/servers/:mcp_id.headers/variablesnormalization, and tool metadata scrubbing.Validation
gofmtgit diff --checkgo test ./internal/dao -run TestDoesNotExist -count=1go test ./internal/handler -run TestDoesNotExist -count=1 -vet=offgo test ./internal/router -run TestDoesNotExist -count=1 -vet=off