Skip to content

feat: add Go MCP server create API - #15260

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
Helios531:feat/go-mcp-create-server
May 28, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
Helios531:feat/go-mcp-create-server

Conversation

@Helios531

@Helios531 Helios531 commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

What

Implementation for POST /api/v1/mcp/servers
#15240

Changes

  • Adds the Go implementation for POST /api/v1/mcp/servers.
  • Wires MCP service and handler into the Go server/router.
  • Validates MCP server type, name, URL, duplicate tenant-scoped names, tenant existence, and normalizes headers/variables.

Validation

  • 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

📝 Walkthrough

Walkthrough

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

Changes

MCP Server Creation Feature

Layer / File(s) Summary
MCP Service contract, validation, and helpers
internal/service/mcp.go
MCPService defines CreateMCPServerRequest and CreateMCPServerResponse contracts. CreateMCPServer validates server type, enforces name length and URL presence, checks tenant existence, rejects duplicate names per tenant, parses optional variables and headers JSON into safe maps, and normalizes variables.tools to an empty object. Returns common.ErrorCode for validation/data errors. Helpers include isValidMCPServerType for type validation and safeJSONMap for robust JSON parsing that gracefully handles malformed or null input.
MCP data persistence layer
internal/dao/mcp.go
MCPServerDAO provides ExistsByNameAndTenant to count existing server records by name and tenant, and CreateMCPServer to insert new entity.MCPServer records into the database.
MCP HTTP handler endpoint
internal/handler/mcp.go
MCPHandler wraps MCPService and implements CreateMCPServer endpoint: retrieves authenticated user, binds JSON request, invokes service, and returns JSON response with common.CodeSuccess on success or error details via jsonError on failure.
Router dependency and route registration
internal/router/router.go
Router struct extended with mcpHandler field. NewRouter signature updated to accept mcpHandler parameter. Authenticated /api/v1/mcp route group introduced with POST /servers mapped to r.mcpHandler.CreateMCPServer.
Server main wiring and initialization
cmd/server_main.go
startServer creates mcpService, constructs mcpHandler using that service, and updates router.NewRouter call to include mcpHandler in the handler parameter list.

Sequence Diagram

sequenceDiagram
  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)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐇 A protocol flows through the stack so neat,
From handler to service, persistence complete,
The MCP server finds its rightful place,
With validation and JSON wrapped in embrace! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 57.14% 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 PR description covers the problem (implements POST /api/v1/mcp/servers endpoint), changes made (MCP service/handler wiring and validation), and validation performed, but does not explicitly mark the type of change. Add a 'Type of change' section with a checkbox selection (e.g., [x] New Feature) to match the template's required structure.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add Go MCP server create API' directly and clearly summarizes the main change—adding a Go implementation for the MCP server creation endpoint.
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: 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

📥 Commits

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

📒 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/handler/mcp.go
return
}

result, code, err := h.mcpService.CreateMCPServer(user.ID, req)

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

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.

Comment thread internal/service/mcp.go
Comment on lines +82 to +88
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.")
}

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 | 🏗️ Heavy lift

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.

Comment thread internal/service/mcp.go
Comment on lines +90 to +92
if req.URL == "" {
return nil, common.CodeDataError, errors.New("Invalid url.")
}

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

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.

Comment thread internal/service/mcp.go
Comment on lines +114 to +116
if err := s.mcpServerDAO.CreateMCPServer(server); err != nil {
return nil, common.CodeDataError, errors.New("Failed to create MCP server.")
}

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

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.

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.

@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 05:33
@Haruko386
Haruko386 marked this pull request as ready for review May 28, 2026 05:33
@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label 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 (57ddd79) to head (d25a79c).
⚠️ Report is 89 commits behind head on main.

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

@JinHai-CN
JinHai-CN merged commit 32d5bf9 into infiniflow:main May 28, 2026
1 check passed
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request May 28, 2026
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.
Lobster-0429 added a commit to Lobster-0429/ragflow that referenced this pull request May 28, 2026
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
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.
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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants