Repository navigation
feat: add Go MCP server create API - #15260
Conversation
📝 WalkthroughWalkthroughThis PR introduces MCP (Model Context Protocol) server creation functionality. It adds a complete feature implementation spanning service-layer validation and business logic, database persistence via a DAO, HTTP request handling, route registration, and server bootstrap wiring. ChangesMCP Server Creation Feature
Sequence DiagramsequenceDiagram
participant Client as HTTP Client
participant Handler as MCPHandler
participant Service as MCPService
participant DAO as MCPServerDAO
participant DB as Database
Client->>Handler: POST /api/v1/mcp/servers
Handler->>Handler: GetUser
Handler->>Handler: Bind JSON request
Handler->>Service: CreateMCPServer(tenantID, req)
Service->>Service: Validate server type
Service->>Service: Validate name/URL/tenant
Service->>DAO: ExistsByNameAndTenant
DAO->>DB: Count query
DB-->>DAO: count
DAO-->>Service: exists bool
Service->>Service: Parse variables/headers JSON
Service->>Service: Normalize variables.tools
Service->>DAO: CreateMCPServer
DAO->>DB: INSERT entity.MCPServer
DB-->>DAO: result
DAO-->>Service: error
Service-->>Handler: CreateMCPServerResponse or ErrorCode
Handler-->>Client: JSON response (200 or error)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes 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: 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/handler/mcp.go`:
- Line 54: The call to h.mcpService.CreateMCPServer is passing user.ID but the
service is tenant-scoped; change the argument to the authenticated tenant
identifier instead (e.g., use user.TenantID or extract tenant ID from the
request context) when calling CreateMCPServer on h.mcpService, and ensure the
value you pass matches the service signature and is validated (non-empty) before
invoking CreateMCPServer.
In `@internal/service/mcp.go`:
- Around line 82-88: The current ExistsByNameAndTenant pre-check plus later
insert is TOCTOU-prone; add a DB-level unique constraint on (tenant_id, name)
and remove reliance on the raceable pre-check as the only guard, then catch
unique-key/duplicate-key errors from the insert and translate them to
common.CodeDataError; specifically, keep or remove the call to
s.mcpServerDAO.ExistsByNameAndTenant but ensure the write path (the insert
method used after the check — e.g.,
s.mcpServerDAO.Insert/Create/InsertMCPServer) handles duplicate-key DB errors by
returning a data error (map DB duplicate key error to common.CodeDataError and a
"Duplicated MCP server name" message) so concurrent creates cannot produce
duplicate rows.
- Around line 90-92: The current check only ensures req.URL is non-empty;
instead parse and validate the URL format before returning; use
url.Parse(req.URL) and ensure parsed.Scheme is http or https and parsed.Host is
non-empty, and if validation fails return the same nil, common.CodeDataError,
errors.New("Invalid url.") (or a slightly more specific message) so callers of
the logic that references req.URL and the error path remain consistent.
- Around line 114-116: The DB create failure in the CreateMCPServer call is
using the wrong error code; update the error handling around
s.mcpServerDAO.CreateMCPServer(server) to return common.CodeServerError (not
common.CodeDataError) for infrastructure/persistence failures—leave any
duplicate-key detection logic to return the existing duplicate-key/code path if
present, otherwise change the returned code on failure to common.CodeServerError
and keep the same error message handling.
🪄 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: 96a86ca4-4876-4b09-b2d7-5a278005e28d
📒 Files selected for processing (5)
cmd/server_main.gointernal/dao/mcp.gointernal/handler/mcp.gointernal/router/router.gointernal/service/mcp.go
| return | ||
| } | ||
|
|
||
| result, code, err := h.mcpService.CreateMCPServer(user.ID, req) |
There was a problem hiding this comment.
Pass tenant ID to the service, not user ID.
Line 54 calls CreateMCPServer(user.ID, req), but the service contract is tenant-scoped. This can cause false “Tenant not found” or create under wrong scope. Pass the authenticated tenant identifier from the user/context instead.
🤖 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` at line 54, The call to h.mcpService.CreateMCPServer
is passing user.ID but the service is tenant-scoped; change the argument to the
authenticated tenant identifier instead (e.g., use user.TenantID or extract
tenant ID from the request context) when calling CreateMCPServer on
h.mcpService, and ensure the value you pass matches the service signature and is
validated (non-empty) before invoking CreateMCPServer.
| exists, err := s.mcpServerDAO.ExistsByNameAndTenant(req.Name, tenantID) | ||
| if err != nil { | ||
| return nil, common.CodeServerError, err | ||
| } | ||
| if exists { | ||
| return nil, common.CodeDataError, errors.New("Duplicated MCP server name.") | ||
| } |
There was a problem hiding this comment.
Name uniqueness check is race-prone under concurrent creates.
The ExistsByNameAndTenant pre-check (Line 82) plus later insert (Line 114) is TOCTOU; two requests can both pass and insert duplicates. Enforce a DB-level unique constraint on (tenant_id, name) and map duplicate-key errors to a data error.
Also applies to: 114-116
🤖 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 82 - 88, The current
ExistsByNameAndTenant pre-check plus later insert is TOCTOU-prone; add a
DB-level unique constraint on (tenant_id, name) and remove reliance on the
raceable pre-check as the only guard, then catch unique-key/duplicate-key errors
from the insert and translate them to common.CodeDataError; specifically, keep
or remove the call to s.mcpServerDAO.ExistsByNameAndTenant but ensure the write
path (the insert method used after the check — e.g.,
s.mcpServerDAO.Insert/Create/InsertMCPServer) handles duplicate-key DB errors by
returning a data error (map DB duplicate key error to common.CodeDataError and a
"Duplicated MCP server name" message) so concurrent creates cannot produce
duplicate rows.
| if req.URL == "" { | ||
| return nil, common.CodeDataError, errors.New("Invalid url.") | ||
| } |
There was a problem hiding this comment.
Validate URL format, not only presence.
Line 90 only rejects empty strings; malformed URLs still pass. Parse and enforce expected scheme/host before persisting.
🤖 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 90 - 92, The current check only ensures
req.URL is non-empty; instead parse and validate the URL format before
returning; use url.Parse(req.URL) and ensure parsed.Scheme is http or https and
parsed.Host is non-empty, and if validation fails return the same nil,
common.CodeDataError, errors.New("Invalid url.") (or a slightly more specific
message) so callers of the logic that references req.URL and the error path
remain consistent.
| if err := s.mcpServerDAO.CreateMCPServer(server); err != nil { | ||
| return nil, common.CodeDataError, errors.New("Failed to create MCP server.") | ||
| } |
There was a problem hiding this comment.
Creation failures are classified with the wrong error code.
On Line 115, DB/persistence failures are returned as common.CodeDataError. Use common.CodeServerError for infrastructure failures (except explicit duplicate-key violations).
🤖 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 114 - 116, The DB create failure in the
CreateMCPServer call is using the wrong error code; update the error handling
around s.mcpServerDAO.CreateMCPServer(server) to return common.CodeServerError
(not common.CodeDataError) for infrastructure/persistence failures—leave any
duplicate-key detection logic to return the existing duplicate-key/code path if
present, otherwise change the returned code on failure to common.CodeServerError
and keep the same error message handling.
## 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
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15260 +/- ##
==========================================
- Coverage 94.53% 93.16% -1.37%
==========================================
Files 10 10
Lines 713 717 +4
Branches 116 118 +2
==========================================
- Hits 674 668 -6
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Resolve the single conflict in cmd/server_main.go: upstream added mcpHandler to the router.NewRouter call (PR infiniflow#15260) while this branch added agentHandler. Both must be passed. internal/router/router.go auto-merged with the union of fields and parameters (memoryHandler, mcpHandler, skillSearchHandler, providerHandler, agentHandler), so the caller in cmd/server_main.go is updated to match that signature.
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
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.
What
Implementation for POST /api/v1/mcp/servers
#15240
Changes
POST /api/v1/mcp/servers.headers/variables.Validation
git 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