Skip to content

feat: add Go MCP server update API - #15261

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
Helios531:feat/go-mcp-update-server
Jun 2, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
Helios531:feat/go-mcp-update-server

Conversation

@Helios531

@Helios531 Helios531 commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

What

#15240
implementation for PUT /api/v1/mcp/servers/:mcp_id

Changes

  • Adds the Go implementation for PUT /api/v1/mcp/servers/:mcp_id.
  • Wires MCP service and handler into the Go server/router for the update route.
  • Preserves Python-style behavior for ownership checks, partial update fields, MCP type/name/URL validation, headers/variables normalization, and tool metadata scrubbing.

Validation

  • gofmt
  • git diff --check
  • go test ./internal/dao -run TestDoesNotExist -count=1
  • go test ./internal/handler -run TestDoesNotExist -count=1 -vet=off
  • go test ./internal/router -run TestDoesNotExist -count=1 -vet=off

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 26, 2026
@coderabbitai

coderabbitai Bot commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This 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.

Changes

MCP Server Update Implementation

Layer / File(s) Summary
MCP Server Persistence Layer
internal/dao/mcp.go
Three new DAO methods: GetByID and GetByIDAndTenant retrieve entity.MCPServer instances by id or id+tenant filtering; UpdateMCPServer persists updates scoped to id+tenant and returns success status based on RowsAffected.
Service Update Logic and Validation
internal/service/mcp.go
Exports UpdateMCPServerRequest as a raw JSON map; implements UpdateMCPServer to fetch existing server, verify tenant ownership, parse optional fields (server_type, name, url, description), validate server_type only when provided, trim and enforce non-empty url, preserve existing headers/variables when absent in request while forcibly resetting variables["tools"] to an empty object, persist via DAO, and re-fetch the updated record; includes helpers for optional JSON field coercion (optionalString, optionalNullableString), not-found detection, and server-type validation.
HTTP Handler and Response Formatting
internal/handler/mcp.go, internal/handler/mcp_test.go
Implements MCPHandler.UpdateMCPServer endpoint: extracts current user, reads mcp_id from route, binds JSON request, calls service, and returns standardized JSON payload or error; adds mcpServerResponse struct with formatted date strings, newMCPServerResponse helper to map entity fields including variable/header maps, and formatMCPServerDate for timestamp formatting; includes unit test validating nil description preservation and date formatting without timezone offsets.
Routing and Server Integration
internal/router/router.go
Adds mcpHandler field to Router struct, updates NewRouter signature with mcpHandler parameter and assignment, and registers PUT /servers/:mcp_id route in the protected /api/v1/mcp group mapped to UpdateMCPServer handler.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

  • infiniflow/ragflow#15260: Creates the MCP server DAO and entity; this PR extends it by adding update, fetch, and tenant-scoped query capabilities alongside HTTP handler and routing.

Suggested labels

💞 feature

Suggested reviewers

  • Hz-186

Poem

🐰 The rabbit hops through handlers bright,
Updates flow from left to right,
Parse the JSON, check the tenant,
Store the MCP—now that's elegant!
Dates format neat, responses true,
Another feature, tried and true! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.08% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: implementing a Go MCP server update API endpoint, which is the core objective of the PR.
Description check ✅ Passed The PR description covers the problem (implementing PUT /api/v1/mcp/servers/:mcp_id), lists changes made, and includes validation steps. However, it does not follow the provided template structure with 'What problem does this PR solve?' and 'Type of change' sections.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f0632c and c70ee03.

📒 Files selected for processing (5)
  • cmd/server_main.go
  • internal/dao/mcp.go
  • internal/handler/mcp.go
  • internal/router/router.go
  • internal/service/mcp.go

Comment thread internal/service/mcp.go Resolved
Comment thread internal/service/mcp.go Resolved
Comment thread internal/service/mcp.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
internal/service/mcp.go (1)

147-149: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve 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 CodeDataError even 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

📥 Commits

Reviewing files that changed from the base of the PR and between c70ee03 and cd394ec.

📒 Files selected for processing (1)
  • internal/service/mcp.go

Comment thread internal/service/mcp.go Resolved
Comment thread internal/service/mcp.go Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Trim 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 win

Reject malformed headers/variables instead of coercing them to {}.

safeJSONMap currently 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

📥 Commits

Reviewing files that changed from the base of the PR and between cd394ec and 4b69762.

📒 Files selected for processing (1)
  • internal/service/mcp.go

JinHai-CN pushed a commit that referenced this pull request May 28, 2026
## 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 Harry-Hz-Zhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

hi, @Helios531

Could u help fix these compatibility issues in the Go MCP update endpoint?

Comment thread internal/handler/mcp.go
"code": common.CodeSuccess,
"message": "success",
"data": result,
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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").

Comment thread internal/handler/mcp.go
c.JSON(http.StatusOK, gin.H{
"code": common.CodeSuccess,
"message": "success",
"data": result,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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": null

But 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.

@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor

Actionable comments posted: 0

@Helios531

Copy link
Copy Markdown
Contributor Author

Hi, @Hz-186, can you review my PR, plz?

@Helios531
Helios531 force-pushed the feat/go-mcp-update-server branch from d83c417 to 4d61858 Compare May 28, 2026 15:42

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
internal/dao/mcp.go (1)

45-52: ⚡ Quick win

Consider whether GetByID is necessary.

The service layer calls GetByID and 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 single GetByIDAndTenant call, which would:

  • Reduce query count by one
  • Enforce tenant isolation at the DAO layer
  • Simplify the service logic

If GetByID is only used in the update flow and not needed elsewhere, consider removing this method and updating the service to use GetByIDAndTenant directly.

🤖 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

📥 Commits

Reviewing files that changed from the base of the PR and between d83c417 and 4d61858.

📒 Files selected for processing (5)
  • internal/dao/mcp.go
  • internal/handler/mcp.go
  • internal/handler/mcp_test.go
  • internal/router/router.go
  • internal/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

@Helios531

Copy link
Copy Markdown
Contributor Author

hi, @Hz-186 , can you review my PR, pls?

@Harry-Hz-Zhang Harry-Hz-Zhang left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@Helios531, LGTM

@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label May 29, 2026
@Haruko386
Haruko386 marked this pull request as draft May 29, 2026 01:45
@Haruko386
Haruko386 marked this pull request as ready for review May 29, 2026 01:45
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request May 29, 2026
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

codecov Bot commented May 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (33ef724) to head (c5ac906).
⚠️ Report is 9 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN

Copy link
Copy Markdown
Member

@Helios531 would you please fix the conflicts?

@tmimmanuel tmimmanuel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@JinHai-CN This is ready.

…server

# Conflicts:
#	internal/dao/mcp.go
#	internal/handler/mcp.go
#	internal/router/router.go
#	internal/service/mcp.go
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request Jun 1, 2026
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.
@JinHai-CN

Copy link
Copy Markdown
Member

@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
@JinHai-CN
JinHai-CN merged commit a98889c into infiniflow:main Jun 2, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants