Repository navigation
feat: add Go MCP server delete API - #15262
Conversation
|
Caution Review failedFailed to post review comments 📝 WalkthroughWalkthroughThe 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. ChangesMCP Server Deletion Endpoint
CI Test Infrastructure: Dynamic Port Allocation
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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
📒 Files selected for processing (5)
cmd/server_main.gointernal/dao/mcp.gointernal/handler/mcp.gointernal/router/router.gointernal/service/mcp.go
| 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) | ||
| } |
There was a problem hiding this comment.
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.
## Summary - Add Go REST support for `GET /api/v1/system/healthz`. - Return Python-compatible `ok`/`nok` dependency fields for DB, Redis, document engine, and storage. - Return HTTP 200 only when all checks pass; otherwise return HTTP 500 with `_meta` failure details. - Add focused service coverage for the unhealthy dependency response when Go dependencies are not initialized. ## Scope This is a small, isolated slice of #15240. It avoids current open connector PRs (#15274, #15300, #15265, #15264), tenant/member PRs (#15295, #15301, #15276), MCP PRs (#15281, #15253, #15254, #15260, #15261, #15262), and the memory-message PR (#15256). Refs #15240
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
hi, @Helios531, LGTM
|
@Helios531 The CI is failing. Could you please take a look and fix it? |
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
|
Hi, @Hz-186, can you review again, plz? |
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.
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.
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.
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).
What
#15240
Implementation for DELETE /api/v1/mcp/servers/:mcp_id
Changes
DELETE /api/v1/mcp/servers/:mcp_id.Validation
gofmtgit diff --checkgo test ./internal/dao -run TestDoesNotExist -count=1go test ./internal/handler -run TestDoesNotExist -count=1 -vet=offgo test ./internal/router -run TestDoesNotExist -count=1 -vet=off