Skip to content

feat(go-api): implement MCP server management endpoints - #15281

Merged
yingfeng merged 12 commits into
infiniflow:mainfrom
Lobster-0429:feat/go-api-mcp-management
Jun 5, 2026
Merged

yingfeng merged 12 commits into
infiniflow:mainfrom
Lobster-0429:feat/go-api-mcp-management

Conversation

@Lobster-0429

Copy link
Copy Markdown
Contributor

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.

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
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label May 27, 2026
@coderabbitai

coderabbitai Bot commented May 27, 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

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

Changes

MCP Server Management Extended

Layer / File(s) Summary
SSRF prevention and URL safety
internal/utility/ssrf.go, internal/utility/ssrf_test.go
Implements AssertURLSafe (scheme allowlist, DNS hook, global-IP checks) and PinnedHTTPClient (pins hostname to resolved IP); includes table-driven tests covering loopback/private/CGNAT/IPv6/documentation ranges.
MCP client library (streamable-HTTP and SSE)
internal/mcpclient/client.go, internal/mcpclient/client_test.go
Exports FetchTools(ctx, opts), Tool, and FetchOptions; implements header templating, JSON-RPC envelopes, response correlation/ID normalization, streamable-HTTP and legacy SSE transports, SSE parsing/dispatch, and tests for both transports and helpers.
MCP service: import and test
internal/service/mcp.go, internal/service/mcp_test.go
Adds sentinel errors (ErrMCPInvalidType/Name/URL), ImportResult, ImportServers (per-entry validation, name de-duplication, header/variable migration, per-server fetch with timeout, persist), and TestServer (live tool discovery with optional timeout); includes validation-focused unit tests.
HTTP handlers and routing
internal/handler/mcp.go, internal/router/router.go
Adds MCP-specific error mapping, ImportMCPRequest, handlers ImportMCPServers and TestMCPServer (auth, JSON binding), and router wiring for POST /api/v1/mcp/servers, POST /api/v1/mcp/servers/import, and POST /api/v1/mcp/servers/:mcp_id/test.

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[]
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#15260: Adjusts MCP routing and handler wiring; directly related to router changes in this PR.
  • infiniflow/ragflow#15262: Also modifies MCP routing/delete behavior and may overlap on handler/service changes.
  • infiniflow/ragflow#14317: Implements similar MCP REST endpoints (import and per-server test) and overlaps on routing/handler responsibilities.

Suggested labels

size:L

Suggested reviewers

  • Hz-186
  • Haruko386

"🐰 I hopped through code with careful paws,
Checked hosts and headers and backed up the laws,
Fetching tools both by stream and by SSE,
Imported servers now dance in the tree! 🥕"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.73% 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 'feat(go-api): implement MCP server management endpoints' clearly and accurately summarizes the main change: porting and implementing MCP server management endpoints in the Go API.
Description check ✅ Passed The PR description is comprehensive and well-structured, covering the problem statement, type of change (New Feature), implementation details, deviations from Python, testing approach, and follow-ups. It follows the template structure with clear sections.
Linked Issues check ✅ Passed The PR successfully addresses all coding requirements from issue #15275: implements all seven endpoints (list/get/create/update/delete/import/test) with proper handler→service→dao layering, adds MCPServerType validation, implements tenant-scoped CRUD with keyword filtering and safe ordering, and provides bulk import functionality with appropriate short-circuiting until Go MCP client is available.
Out of Scope Changes check ✅ Passed All changes are narrowly scoped to MCP server management endpoints: new files for entity constants, dao, service, and handler; router updates to register MCP routes; and comprehensive tests. No unrelated modifications detected. The addition of SSRF utility and MCP client libraries are foundational infrastructure directly supporting the endpoint implementation.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 187dc8a and 10353e4.

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

Comment thread internal/dao/mcp.go Resolved
Comment thread internal/service/mcp.go Resolved
Comment thread internal/service/mcp.go Resolved
Comment thread internal/service/mcp.go
Comment on lines +306 to +313
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))})

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @Hz-186 ,
Could you please review this?

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
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
@coderabbitai

coderabbitai Bot commented May 28, 2026

Copy link
Copy Markdown
Contributor

Actionable comments posted: 0

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @Haruko386 ,
Could you please review this PR?

Comment thread internal/router/router.go Outdated
{
mcp.GET("/servers", r.mcpHandler.ListMCPServers)
mcp.POST("/servers", r.mcpHandler.CreateMCPServer)
mcp.POST("/import", r.mcpHandler.ImportMCPServers)

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, @web-dev0521
I think this PR overlaps with several other open MCP PRs, so please coordinate the scope instead of reimplementing all endpoints here:

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:

  1. Import route is currently registered as /api/v1/mcp/import, but Python uses /api/v1/mcp/servers/import. Please keep the compatible
    path.

  2. Import does not validate server_type, does not run URL safety checks, and does not fetch/store MCP tools like the Python implementation
    does.

  3. The test route path is correct, but the logic is incomplete: it ignores mcp_id and 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.
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels May 29, 2026
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @Hz-186 ,
I just updated based on your review.
Please review this again.

@Haruko386 Haruko386 added the ci Continue Integration label May 29, 2026
@Haruko386
Haruko386 marked this pull request as draft May 29, 2026 02:57
@Haruko386
Haruko386 marked this pull request as ready for review May 29, 2026 02:58
@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label May 29, 2026

@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: 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3be5c8c and 7f6b211.

📒 Files selected for processing (8)
  • internal/handler/mcp.go
  • internal/mcpclient/client.go
  • internal/mcpclient/client_test.go
  • internal/router/router.go
  • internal/service/mcp.go
  • internal/service/mcp_test.go
  • internal/utility/ssrf.go
  • internal/utility/ssrf_test.go

Comment thread internal/mcpclient/client_test.go Resolved
Comment thread internal/mcpclient/client.go Resolved
Comment thread internal/service/mcp.go Resolved
Comment thread internal/service/mcp.go Resolved
Comment thread internal/utility/ssrf.go Resolved
Comment thread internal/handler/mcp.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:

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.

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.

Comment thread internal/service/mcp.go
// 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 {

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.

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

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 (e627f5d) to head (aaa4a2d).

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

…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.
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @Hz-186 ,
Could you please review my PR again?

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.

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

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

242-245: ⚡ Quick win

Report name-resolution failures per server instead of aborting the batch.

A DAO error from nextAvailableMCPName returns nil, err for the whole call, discarding the ImportResults for servers already created in earlier iterations and leaving the caller blind to that partial state. This is inconsistent with the FetchTools/CreateMCPServer failures 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

📥 Commits

Reviewing files that changed from the base of the PR and between 9b0458d and 83fc9fd.

📒 Files selected for processing (3)
  • internal/handler/mcp.go
  • internal/router/router.go
  • internal/service/mcp.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/handler/mcp.go

@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, @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:

  1. POST /mcp/servers/import with a missing mcpServers key returns Python code: 101 (required argument are missing: mcpServers;)while Go returns code: 102 (No MCP servers provided.).
  2. POST /mcp/servers/:mcp_id/test collapses URL validation errors to Invalid url. in Go, while Python returns Invalid 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.
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @Hz-186 ,
I just updated based on your review.

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

  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

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

@Hz-186 , Please review this again.

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

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

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

@Hz-186 , Fixied!

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

@web-dev0521, LGTM ! ! !

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN ,
Could you please review this PR?

@JinHai-CN

Copy link
Copy Markdown
Member

@web-dev0521 would you please resolve the conflicts?

@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

@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.
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng ,
Could you please review this PR?
I think the CI failure is not related to my PR.

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @yingfeng ,
Could you please review this PR?
All CI tests are successfully passed.
Thank you!

@yingfeng
yingfeng merged commit b8db200 into infiniflow:main Jun 5, 2026
1 check passed
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

@yingfeng, Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Subtask]: Go API — MCP server management for the user-setting MCP page

5 participants