Skip to content

feat: add Go MCP server delete API - #15262

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Helios531:feat/go-mcp-delete-server
May 29, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Helios531:feat/go-mcp-delete-server

Conversation

@Helios531

@Helios531 Helios531 commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

What

#15240
Implementation for DELETE /api/v1/mcp/servers/:mcp_id

Changes

  • Adds the Go implementation for DELETE /api/v1/mcp/servers/:mcp_id.
  • Wires MCP service and handler into the Go server/router for the delete route.
  • Preserves Python-style behavior for ownership checks, delete failure handling, and boolean success response.

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

Caution

Review failed

Failed to post review comments

📝 Walkthrough

Walkthrough

The PR implements a complete DELETE endpoint for MCP servers with tenant-scoped deletion, spanning data access (DAO), business logic (service), HTTP handling, and routing. A separate change updates CI port allocation to dynamically probe for free port ranges instead of using fixed offsets.

Changes

MCP Server Deletion Endpoint

Layer / File(s) Summary
MCP Server Data Access Layer
internal/dao/mcp.go
MCPServerDAO provides GetByID to fetch an MCP server entity, returning nil when not found, and DeleteMCPServer to remove a server by id and tenant_id with row-affected result.
MCP Server Service and Tenant Validation
internal/service/mcp.go
MCPService.DeleteMCPServer enforces tenant ownership by verifying the loaded server's tenant ID, calls DAO deletion, and returns appropriate error codes (CodeServerError for lookup/deletion faults, CodeDataError for not-found/mismatch).
MCP HTTP Handler
internal/handler/mcp.go
MCPHandler.DeleteMCPServer Gin endpoint extracts the current user, invokes the service with user ID and mcp_id parameter, and returns either error JSON or HTTP 200 success response.
Router Integration
internal/router/router.go
Router registers the protected DELETE /api/v1/mcp/servers/:mcp_id endpoint, delegating to mcpHandler.DeleteMCPServer.

CI Test Infrastructure: Dynamic Port Allocation

Layer / File(s) Summary
Dynamic Host Port Probing
.github/workflows/tests.yml
Port offset calculation now derives a seed from run/runner metadata, probes multiple candidate base ports via shell helper using ss to verify port availability, retries with bounded attempts, and exports the selected offset for downstream port computations.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#15260: The main PR extends the same MCP server stack by adding MCPServerDAO/MCPService delete methods plus corresponding MCPHandler.DeleteMCPServer and DELETE /api/v1/mcp/servers/:mcp_id routing.

Suggested labels

size:L

Suggested reviewers

  • Hz-186

Poem

🐰 A bundle of bytes, a DELETE so fine,
With tenant checks and routes aligned,
Plus CI ports that probe and play,
The MCP servers fade away! 🎉

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description addresses the template's required sections but incompletely: it provides clear context about what the PR solves (the delete endpoint implementation referenced in #15240) and validation details, but does not explicitly check the 'Type of change' checkbox as required by the template. Explicitly select the 'Type of change' checkbox (should be 'New Feature') to fully comply with the repository's description template requirements.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add Go MCP server delete API' clearly and specifically describes the main change—implementing a delete API endpoint for MCP servers in Go.
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: 1

🤖 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 40-43: The current mcpServerDAO.GetByID call conflates
backend/read errors with not-found/ownership mismatches; change the logic in the
block that calls mcpServerDAO.GetByID so that if err != nil you return a
server-side error code (e.g., common.CodeServerError) and the error, but if the
call succeeds and server is nil or server.TenantID != tenantID you return the
data error (common.CodeDataError) and a not-found/ownership error; update the
branch around mcpServerDAO.GetByID, the local variable server, and use
mcpID/tenantID in the not-found message to preserve context.
🪄 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: d59a56f1-d1a4-4835-ba42-e4a4998f02e5

📥 Commits

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

📒 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
Comment on lines +40 to +43
server, err := s.mcpServerDAO.GetByID(mcpID)
if err != nil || server.TenantID != tenantID {
return false, common.CodeDataError, fmt.Errorf("Cannot find MCP server %s for user %s", mcpID, tenantID)
}

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

Separate lookup failure from ownership/not-found failure.

Line 41 currently maps all GetByID failures to common.CodeDataError. Backend read failures should return a server error code, while only not-found/tenant-mismatch should return data error.

🤖 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 40 - 43, The current
mcpServerDAO.GetByID call conflates backend/read errors with not-found/ownership
mismatches; change the logic in the block that calls mcpServerDAO.GetByID so
that if err != nil you return a server-side error code (e.g.,
common.CodeServerError) and the error, but if the call succeeds and server is
nil or server.TenantID != tenantID you return the data error
(common.CodeDataError) and a not-found/ownership error; update the branch around
mcpServerDAO.GetByID, the local variable server, and use mcpID/tenantID in the
not-found message to preserve context.

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, LGTM

@Harry-Hz-Zhang Harry-Hz-Zhang added the ci Continue Integration label May 28, 2026
@Haruko386
Haruko386 marked this pull request as draft May 28, 2026 06:57
@Haruko386
Haruko386 marked this pull request as ready for review May 28, 2026 06:57
@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label May 28, 2026
@Harry-Hz-Zhang

Copy link
Copy Markdown
Contributor

@Helios531 The CI is failing. Could you please take a look and fix it?

@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 28, 2026
@codecov

codecov Bot commented May 28, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (7fc909a) to head (67b59b7).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15262   +/-   ##
=======================================
  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.

@Helios531

Copy link
Copy Markdown
Contributor Author

Hi, @Hz-186, can you review again, plz?

@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

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.
@JinHai-CN
JinHai-CN merged commit faa9c54 into infiniflow:main May 29, 2026
1 check passed
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request May 29, 2026
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.
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.
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request Jun 2, 2026
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).
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:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants