Repository navigation
feat: add Go MCP server list API - #15253
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a tenant-scoped MCP servers listing endpoint with DAO query (filtering, ordering, pagination), service DTO mapping/formatting, HTTP handler parsing, and router registration; CI workflow port-probing logic updated. ChangesMCP Servers Listing Feature
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related issues
Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 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/dao/mcp.go`:
- Around line 81-89: mcpServerOrderColumn currently mixes *_time and *_date
names causing SQL unknown-column errors; update the function so all cases return
the *_date variants (return "update_date" for "update_time", return
"create_date" for "create_time") and change the default return to "create_date"
to match the rest of the query path and handler defaults; modify the switch in
mcpServerOrderColumn to consistently map any time/date keys to the corresponding
*_date column names.
🪄 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: 8873d4d9-499f-4e6d-ae73-8a5cbd0574cf
📒 Files selected for processing (5)
cmd/server_main.gointernal/dao/mcp.gointernal/handler/mcp.gointernal/router/router.gointernal/service/mcp.go
|
hi, @JinHai-CN, could you review my PR, plz? |
|
MCP server discovery and listing is becoming a key infrastructure piece as the ecosystem grows. Having a standardized API to enumerate available servers makes it much easier for host applications to compose multi-step workflows. In our work building AI Workdeck — an open-source workspace for document-heavy legal workflows — we rely on MCP servers as pluggable tools. A server list API like this would help us dynamically discover and connect to new document processing capabilities (OCR, NER, clause extraction, etc.) at runtime. Quick question: are you planning to include metadata like tool schemas and capability tags in the listing response? That would enable automatic workflow composition — the host app could match incoming document types to the right server without manual configuration. Nice contribution to the MCP tooling landscape! |
ec4b412 to
5d36133
Compare
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/handler/mcp.go`:
- Line 57: The call to h.mcpService.ListMCPServers currently passes user.ID but
the DAO filters by tenant_id; change the argument to the authenticated user's
tenant identifier (replace user.ID with the appropriate tenant field such as
user.TenantID or user.CurrentTenant.ID) so the call becomes
h.mcpService.ListMCPServers(tenantID, mcpIDs, keywords, page, pageSize, orderby,
desc); ensure the tenantID variable is sourced from the authenticated user's
current tenant and matches the expected parameter type.
🪄 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: f5d2b972-a9aa-4303-a5d3-ae8b3a26f01d
📒 Files selected for processing (5)
cmd/server_main.gointernal/dao/mcp.gointernal/handler/mcp.gointernal/router/router.gointernal/service/mcp.go
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 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/handler/mcp.go`:
- Around line 84-92: The currentTenantID function incorrectly hardcodes role
"owner" and returns tenants[0]; change it to use the actual authenticated tenant
ID instead of the owner-filtered first match: obtain the current tenant id from
the request/auth context available to MCPHandler (rather than calling
GetByUserIDAndRole("owner")), then verify the user is a member of that tenant
via userTenantDAO (e.g., call a role-agnostic lookup like GetByUserID or
GetByUserIDAndRole with the resolved tenant id) and return that tenant id; if no
authenticated tenant is present, fall back to validating that the user has
exactly one tenant and return it, otherwise return a clear "tenant not found /
not authorized" error.
- Around line 60-61: The pagination parsing currently allows page/page_size to
be zero and accepts arbitrarily large page_size; update the handling around page
:= parsePositiveInt(c.Query("page")) and pageSize :=
parsePositiveInt(c.Query("page_size")) to enforce defaults and a maximum: if
page <= 0 set page = 1, if pageSize <= 0 set pageSize = <default (e.g. 20)>, and
if pageSize > <max (e.g. 100)> set pageSize = <max>; ensure these guarded values
are the ones passed into the DAO so LIMIT/OFFSET is always applied and oversized
reads are prevented.
🪄 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: 3fd57796-484e-4288-af5c-c718caa201f8
📒 Files selected for processing (1)
internal/handler/mcp.go
| page := parsePositiveInt(c.Query("page")) | ||
| pageSize := parsePositiveInt(c.Query("page_size")) |
There was a problem hiding this comment.
Guard pagination defaults and cap page_size to avoid unbounded reads.
Line 60 and Line 61 allow page/page_size to remain 0, and the DAO skips LIMIT in that case; very large page_size is also accepted as-is. This creates an easy path to full-table or oversized responses.
Proposed hardening
+const (
+ defaultPage = 1
+ defaultPageSize = 30
+ maxPageSize = 200
+)
+
page := parsePositiveInt(c.Query("page"))
pageSize := parsePositiveInt(c.Query("page_size"))
+if page == 0 {
+ page = defaultPage
+}
+if pageSize == 0 {
+ pageSize = defaultPageSize
+} else if pageSize > maxPageSize {
+ pageSize = maxPageSize
+}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| page := parsePositiveInt(c.Query("page")) | |
| pageSize := parsePositiveInt(c.Query("page_size")) | |
| const ( | |
| defaultPage = 1 | |
| defaultPageSize = 30 | |
| maxPageSize = 200 | |
| ) | |
| page := parsePositiveInt(c.Query("page")) | |
| pageSize := parsePositiveInt(c.Query("page_size")) | |
| if page == 0 { | |
| page = defaultPage | |
| } | |
| if pageSize == 0 { | |
| pageSize = defaultPageSize | |
| } else if pageSize > maxPageSize { | |
| pageSize = maxPageSize | |
| } |
🤖 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/handler/mcp.go` around lines 60 - 61, The pagination parsing
currently allows page/page_size to be zero and accepts arbitrarily large
page_size; update the handling around page := parsePositiveInt(c.Query("page"))
and pageSize := parsePositiveInt(c.Query("page_size")) to enforce defaults and a
maximum: if page <= 0 set page = 1, if pageSize <= 0 set pageSize = <default
(e.g. 20)>, and if pageSize > <max (e.g. 100)> set pageSize = <max>; ensure
these guarded values are the ones passed into the DAO so LIMIT/OFFSET is always
applied and oversized reads are prevented.
| func (h *MCPHandler) currentTenantID(userID string) (string, error) { | ||
| tenants, err := h.userTenantDAO.GetByUserIDAndRole(userID, "owner") | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| if len(tenants) == 0 || tenants[0].TenantID == "" { | ||
| return "", errors.New("tenant not found") | ||
| } | ||
| return tenants[0].TenantID, nil |
There was a problem hiding this comment.
Use current authenticated tenant, not owner-filtered first match.
Line 85 hard-filters to "owner", and Line 92 picks tenants[0]. This can block valid non-owner users and can select the wrong tenant for users with multiple tenant relations, breaking tenant scoping semantics.
🤖 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/handler/mcp.go` around lines 84 - 92, The currentTenantID function
incorrectly hardcodes role "owner" and returns tenants[0]; change it to use the
actual authenticated tenant ID instead of the owner-filtered first match: obtain
the current tenant id from the request/auth context available to MCPHandler
(rather than calling GetByUserIDAndRole("owner")), then verify the user is a
member of that tenant via userTenantDAO (e.g., call a role-agnostic lookup like
GetByUserID or GetByUserIDAndRole with the resolved tenant id) and return that
tenant id; if no authenticated tenant is present, fall back to validating that
the user has exactly one tenant and return it, otherwise return a clear "tenant
not found / not authorized" error.
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
The list API behavior mostly works, but the Go response is not fully compatible with Python because it returns raw entity fields, changes timestamp formatting, and handles invalid query/auth errors differently.
|
|
||
| // ListMCPServersResponse is the response payload for listing MCP servers. | ||
| type ListMCPServersResponse struct { | ||
| MCPServers []*entity.MCPServer `json:"mcp_servers"` |
There was a problem hiding this comment.
Hi, @Helios531.
Please avoid returning tenant_id in the MCP list response. The Python endpoint does not include it, and the current Go response exposes an empty tenant_id because the list query does not select that column while returning the raw entity.
| if err != nil || parsed <= 0 { | ||
| return 0 | ||
| } | ||
| return parsed |
There was a problem hiding this comment.
Hi, @Helios531.
Invalid pagination parameters behave differently from Python. Python returns an error for values like page_size=abc, while Go silently treats them as 0 and returns success. Please either match Python behavior or document this intentional difference.
| case "create_time", "create_date": | ||
| return "create_date" | ||
| default: | ||
| return "create_date" |
There was a problem hiding this comment.
Hi, @Helios531.
GET /api/v1/mcp/servers?orderby=bad_column&desc=true
Python:
{
"code": 100,
"message": "AttributeError(\"type object 'MCPServer' has no attribute 'bad_column'\")"
}
Go:
{
"code": 0,
"message": "success"
}
Invalid orderby behavior differs from Python. Python returns an error for an unknown field, while Go silently falls back to create_date. Please match the Python behavior or make this compatibility difference explicit.
## 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
7ce8a63 to
8a5a1b0
Compare
|
Actionable comments posted: 0 |
|
hi, @Hz-186 , can you review my PR, pls? |
|
@Helios531, The CI is failing. Could you please take a look and fix it? |
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.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
.github/workflows/tests.yml (1)
204-211: TOCTOU window between probing and binding.The probe selects a free block here, but the ports are not bound until
docker compose ... up -druns much later (Line 276). On a shared self-hosted runner a concurrent job can claim a probed port in that gap, so this reduces—but does not eliminate—collisions. The inline comment already acknowledges this; just flagging that the bring-up steps should treat a bind failure as retryable rather than assuming the probed block is guaranteed free.🤖 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 @.github/workflows/tests.yml around lines 204 - 211, The current probe-and-then-bind approach (loop computing CANDIDATE_PORT_OFFSET with ports_available_for_offset and setting SELECTED_PORT_OFFSET) has a TOCTOU race because binding happens later during the docker compose up -d step; update the bring-up logic so docker compose failures due to port binding are treated as transient and retried: wrap the docker compose up command that uses SELECTED_PORT_OFFSET in a retry loop (with backoff and a limit), detect bind-related errors from the compose output/exit code, and on such errors re-run the port selection (call ports_available_for_offset again or pick a new CANDIDATE_PORT_OFFSET) before retrying; ensure symbols referenced are ports_available_for_offset, SELECTED_PORT_OFFSET, CANDIDATE_PORT_OFFSET and the docker compose up invocation so the retry handles genuine bind conflicts instead of assuming the earlier probe guarantee.
🤖 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 @.github/workflows/tests.yml:
- Around line 183-186: The port_is_available() probe is using ss with the
combined flags "-Htanl" which includes "-a/--all" and causes non-listening
sockets to be returned; update the ss invocation inside port_is_available() to
drop the "-a" flag so it only queries listening sockets (e.g., use "-Htnl" or
equivalent) and keep the rest of the logic (sudo ss ... | grep -q .) unchanged
so the function correctly reports listening ports as "in use".
---
Nitpick comments:
In @.github/workflows/tests.yml:
- Around line 204-211: The current probe-and-then-bind approach (loop computing
CANDIDATE_PORT_OFFSET with ports_available_for_offset and setting
SELECTED_PORT_OFFSET) has a TOCTOU race because binding happens later during the
docker compose up -d step; update the bring-up logic so docker compose failures
due to port binding are treated as transient and retried: wrap the docker
compose up command that uses SELECTED_PORT_OFFSET in a retry loop (with backoff
and a limit), detect bind-related errors from the compose output/exit code, and
on such errors re-run the port selection (call ports_available_for_offset again
or pick a new CANDIDATE_PORT_OFFSET) before retrying; ensure symbols referenced
are ports_available_for_offset, SELECTED_PORT_OFFSET, CANDIDATE_PORT_OFFSET and
the docker compose up invocation so the retry handles genuine bind conflicts
instead of assuming the earlier probe guarantee.
🪄 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: 36146f41-9e01-4912-847b-9835135b6f49
📒 Files selected for processing (1)
.github/workflows/tests.yml
…rvers # Conflicts: # .github/workflows/tests.yml # internal/dao/mcp.go # internal/handler/mcp.go # internal/router/router.go # internal/service/mcp.go
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15253 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
tmimmanuel
left a comment
There was a problem hiding this comment.
@JinHai-CN This is ready.
|
hi, @Hz-186 , can you review again, plz? |
…rvers # Conflicts: # web/src/locales/zh.ts
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.
Harry-Hz-Zhang
left a comment
There was a problem hiding this comment.
bro...... @Helios531
Please split the unrelated changes out of this PR before merge.
The MCP list API review should not include CI workflow rewrites or frontend locale formatting changes.
If the failure is caused by CI infrastructure, please split the workflow fix into a separate CI PR first. After that lands, this MCP list API PR can rebase on main and rerun CI.
Keeping the CI workflow rewrite in this feature PR makes the review scope too broad and mixes infrastructure behavior with API behavior.
If the CI failure is caused by the MCP list API itself, then the fix should stay here; otherwise the .github/workflows/tests.yml change should be separated.
Also, any changes to zh.ts should go in a separate PR — it'll help avoid merge conflicts down the line.
There was a problem hiding this comment.
The normal list cases match Python, but two edge cases still differ.
For orderby=bad_field, Python returns HTTP 200 with code: 100, while Go returns HTTP 500 with code: 500. Please map this error path to the same response shape as Python.
For negative pagination such as page=-1&page_size=-2, Python returns an empty mcp_servers list with the original total, but Go normalizes the values to the default page/page_size and returns the full first page. Please align the pagination edge-case behavior with Python.
{"code":500,"data":null,"message":"type object 'MCPServer' has no attribute 'bad_field'"}
{"code":100,"data":null,"message":"AttributeError(\"type object 'MCPServer' has no attribute 'bad_field'\")"}
{"code":0,"data":{"mcp_servers":[],"total":13},"message":"success"}
and your ci fail again
|
thank you, @JinHai-CN |
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
Implements
GET /api/v1/mcp/serversin the Go API server.Changes
GET /api/v1/mcp/serversunder authenticated/api/v1routes.API Behavior
Matches the Python endpoint behavior:
keywords.mcp_idand repeated/comma-separatedmcp_ids.page,page_size,orderby, anddesc.{ "code": 0, "message": "success", "data": { "mcp_servers": [], "total": 0 } }Verification
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