Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

refactor(mcp): centralize configuration and transport wiring (#20011)

Sbaaoui Idriss05b167e966a0
diff --git a/cmd/ragflow_server.go b/cmd/ragflow_server.go
index 0066958ec7..2b11f0299e 100644
--- a/cmd/ragflow_server.go
+++ b/cmd/ragflow_server.go
@@ -39,7 +39,6 @@ import (
"ragflow/internal/handler"
"ragflow/internal/ingestion/knowledge_compile"
ingestion "ragflow/internal/ingestion/service"
- "ragflow/internal/mcp"
"ragflow/internal/rag/agentic-rag"
agenticruntime "ragflow/internal/rag/agentic-rag/runtime"
"ragflow/internal/router"
@@ -90,14 +89,7 @@ type serverArgs struct {
adminPort *int // Used by api, ingestor, syncer, deepdoc for heartbeat, "ip:port"
name *string // server name
enablePProf bool // enable pprof
- mcpEnabled bool
- mcpHost string
- mcpPort int
- mcpMode string
- mcpAPIKey string
- mcpSSE bool
- mcpStreamable bool
- mcpJSON bool
+
}
// engineDocEngine is the small slice of the engine surface the doc-chunk pager
@@ -189,14 +181,7 @@ func (p *docChunkPager) DocChunks(ctx context.Context, req agenticruntime.DocChu
}
func parseArgs() (*serverArgs, error) {
- args := &serverArgs{
- mcpHost: "127.0.0.1",
- mcpPort: 9382,
- mcpMode: "self-host",
- mcpSSE: true,
- mcpStreamable: true,
- mcpJSON: true,
- }
+ args := &serverArgs{}
var serverMode string
var configPath string
@@ -210,24 +195,9 @@ func parseArgs() (*serverArgs, error) {
}
args.logLevel = &value
continue
- case "--mcp-host":
- args.mcpHost = value
- continue
- case "--mcp-port":
- port, err := parsePort(value, "MCP")
- if err != nil {
- return nil, err
- }
- args.mcpPort = port
- continue
- case "--mcp-mode":
- args.mcpMode = value
- continue
- case "--mcp-host-api-key":
- args.mcpAPIKey = value
- continue
}
}
+
switch arg {
case "--admin":
serverMode = "admin"
@@ -240,20 +210,6 @@ func parseArgs() (*serverArgs, error) {
case "--api":
serverMode = "api"
args.mode = &serverMode
- case "--enable-mcpserver":
- args.mcpEnabled = true
- case "--transport-sse-enabled":
- args.mcpSSE = true
- case "--no-transport-sse-enabled":
- args.mcpSSE = false
- case "--transport-streamable-http-enabled":
- args.mcpStreamable = true
- case "--no-transport-streamable-http-enabled":
- args.mcpStreamable = false
- case "--json-response":
- args.mcpJSON = true
- case "--no-json-response":
- args.mcpJSON = false
case "--syncer":
serverMode = "syncer"
args.mode = &serverMode
@@ -325,12 +281,6 @@ func parseArgs() (*serverArgs, error) {
}
}
- if err := applyMCPEnv(args); err != nil {
- return nil, err
- }
- if err := validateMCPArgs(args); err != nil {
- return nil, err
- }
if args.migrateDB && args.mode != nil {
return nil, errors.New("--migrate cannot be combined with a server mode")
}
@@ -357,76 +307,6 @@ func selectedLogLevel(args *serverArgs, configured string) string {
return level
}
-func applyMCPEnv(args *serverArgs) error {
- if value, ok := os.LookupEnv("RAGFLOW_MCP_HOST"); ok {
- args.mcpHost = value
- }
- if value, ok := os.LookupEnv("RAGFLOW_MCP_PORT"); ok {
- port, err := parsePort(value, "MCP")
- if err != nil {
- return err
- }
- args.mcpPort = port
- }
- if value, ok := os.LookupEnv("RAGFLOW_MCP_LAUNCH_MODE"); ok {
- args.mcpMode = value
- }
- if value, ok := os.LookupEnv("RAGFLOW_MCP_HOST_API_KEY"); ok {
- args.mcpAPIKey = value
- }
- if value, ok := os.LookupEnv("RAGFLOW_MCP_ENABLED"); ok {
- args.mcpEnabled = parseMCPBool(value)
- }
- if value, ok := os.LookupEnv("RAGFLOW_MCP_TRANSPORT_SSE_ENABLED"); ok {
- args.mcpSSE = parseMCPBool(value)
- }
- if value, ok := os.LookupEnv("RAGFLOW_MCP_TRANSPORT_STREAMABLE_ENABLED"); ok {
- args.mcpStreamable = parseMCPBool(value)
- }
- if value, ok := os.LookupEnv("RAGFLOW_MCP_JSON_RESPONSE"); ok {
- args.mcpJSON = parseMCPBool(value)
- }
- return nil
-}
-
-func validateMCPArgs(args *serverArgs) error {
- if args.mcpMode != "self-host" && args.mcpMode != "host" {
- return fmt.Errorf("invalid MCP mode: %s", args.mcpMode)
- }
- if !args.mcpStreamable && args.mcpJSON {
- args.mcpJSON = false
- }
- if !args.mcpSSE && !args.mcpStreamable {
- args.mcpStreamable = true
- }
- if args.mcpEnabled && args.mcpMode == "self-host" && args.mcpAPIKey == "" {
- return errors.New("--mcp-host-api-key is required when --mcp-mode=self-host")
- }
- return nil
-}
-
-func parseMCPBool(value string) bool {
- switch strings.ToLower(strings.TrimSpace(value)) {
- case "1", "true", "yes", "on":
- return true
- default:
- return false
- }
-}
-
-func parsePort(value, name string) (int, error) {
- port, err := strconv.Atoi(value)
- if err != nil || port <= 0 || port > 65535 {
- return 0, fmt.Errorf("invalid %s port: %s", name, value)
- }
- return port, nil
-}
-
-// registerNativeDeepDoc wires the in-process (Go) DeepDoc backend as the local
-// fallback used when no external DeepDoc HTTP service is configured. It is
-// compiled into the server built with -tags cgo, which statically links the
-// ONNX Runtime backend (libonnxruntime.a); the unit-test tier builds without
-// cgo and stays free of the onnxruntime dependency.
func printHelp(args *serverArgs) {
switch {
case args.mode == nil:
@@ -451,15 +331,7 @@ func printHelp(args *serverArgs) {
fmt.Fprintf(os.Stderr, " --log-level string\tLog level: debug, info, warn, error (default: warn)\n")
fmt.Fprintf(os.Stderr, " --profile \tEnable pprof server\n")
fmt.Fprintf(os.Stderr, " -h, --help \tShow this help message and exit\n\n")
- fmt.Fprintf(os.Stderr, "API MCP options:\n")
- fmt.Fprintf(os.Stderr, " --enable-mcpserver\tEnable the MCP server\n")
- fmt.Fprintf(os.Stderr, " --mcp-host=string\tMCP bind address (default: 127.0.0.1)\n")
- fmt.Fprintf(os.Stderr, " --mcp-port=int \tMCP port (default: 9382)\n")
- fmt.Fprintf(os.Stderr, " --mcp-mode=self-host|host\tMCP mode (default: self-host)\n")
- fmt.Fprintf(os.Stderr, " --mcp-host-api-key=string\tAPI key required in self-host mode\n")
- fmt.Fprintf(os.Stderr, " --transport-sse-enabled, --no-transport-sse-enabled\tEnable or disable MCP SSE transport (default: enabled)\n")
- fmt.Fprintf(os.Stderr, " --transport-streamable-http-enabled, --no-transport-streamable-http-enabled\tEnable or disable MCP streamable HTTP transport (default: enabled)\n")
- fmt.Fprintf(os.Stderr, " --json-response, --no-json-response\tEnable or disable MCP JSON responses (default: enabled)\n\n")
+ fmt.Fprintln(os.Stderr, "MCP settings: service_conf.yaml mcp section or RAGFLOW_MCP_* environment variables.")
fmt.Fprintf(os.Stderr, "Run '%s --api --help' for API server options.\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Run '%s --admin --help' for admin server options.\n", os.Args[0])
fmt.Fprintf(os.Stderr, "Run '%s --ingestor --help' for ingester options.\n", os.Args[0])
@@ -475,15 +347,7 @@ func printHelp(args *serverArgs) {
fmt.Fprintf(os.Stderr, " --log-level string\tLog level: debug, info, warn, error (default: warn)\n")
fmt.Fprintf(os.Stderr, " --profile \t\tEnable pprof server\n")
fmt.Fprintf(os.Stderr, " -h, --help \tShow this help message and exit\n")
- fmt.Fprintf(os.Stderr, "\nMCP options:\n")
- fmt.Fprintf(os.Stderr, " --enable-mcpserver\tEnable the MCP server\n")
- fmt.Fprintf(os.Stderr, " --mcp-host=string\tMCP bind address (default: 127.0.0.1)\n")
- fmt.Fprintf(os.Stderr, " --mcp-port=int \tMCP port (default: 9382)\n")
- fmt.Fprintf(os.Stderr, " --mcp-mode=self-host|host\tMCP mode (default: self-host)\n")
- fmt.Fprintf(os.Stderr, " --mcp-host-api-key=string\tAPI key required in self-host mode\n")
- fmt.Fprintf(os.Stderr, " --transport-sse-enabled, --no-transport-sse-enabled\tEnable or disable MCP SSE transport (default: enabled)\n")
- fmt.Fprintf(os.Stderr, " --transport-streamable-http-enabled, --no-transport-streamable-http-enabled\tEnable or disable MCP streamable HTTP transport (default: enabled)\n")
- fmt.Fprintf(os.Stderr, " --json-response, --no-json-response\tEnable or disable MCP JSON responses (default: enabled)\n")
+ fmt.Fprintln(os.Stderr, "\nMCP settings: service_conf.yaml mcp section or RAGFLOW_MCP_* environment variables.")
case *args.mode == "admin":
fmt.Fprintf(os.Stderr, "Usage: %s --admin [OPTIONS]\n\n", os.Args[0])
fmt.Fprintf(os.Stderr, "RAGFlow Admin Server\n\n")
@@ -1167,7 +1031,7 @@ func runAPI(ctx context.Context, args *serverArgs) error {
common.Fatal("Failed to initialize query builder", zap.Error(err))
}
- if err := startServer(ctx, args); err != nil {
+ if err := startServer(ctx); err != nil {
return err
}
@@ -1176,7 +1040,7 @@ func runAPI(ctx context.Context, args *serverArgs) error {
return nil
}
-func startServer(ctx context.Context, args *serverArgs) error {
+func startServer(ctx context.Context) error {
globalConfig := server.GetConfig()
serverMode := globalConfig.GetMode()
@@ -1483,17 +1347,7 @@ func startServer(ctx context.Context, args *serverArgs) error {
// MCP server endpoint — exposes RAGFlow capabilities as MCP tools
// (ragflow_retrieval, ragflow_list_datasets, ragflow_list_chats) to
// external AI clients via JSON-RPC over HTTP.
- mcpServerHandler := handler.NewMCPServerHandler(
- func(ctx context.Context, userID string, page, pageSize int, orderBy string, desc bool) ([]map[string]interface{}, int64, error) {
- return handler.MCPListDatasets(ctx, datasetsService, userID, page, pageSize, orderBy, desc)
- },
- func(ctx context.Context, userID string, page, pageSize int, orderBy string, desc bool) ([]map[string]interface{}, int64, error) {
- return handler.MCPListChats(ctx, chatService, userID, page, pageSize, orderBy, desc)
- },
- func(ctx context.Context, userID string, req mcp.RetrievalRequest) (string, error) {
- return handler.MCPRetrieval(ctx, datasetsService, userID, req)
- },
- )
+ mcpServerHandler := handler.NewMCPServerHandler(datasetsService, chatService)
skillSearchHandler := handler.NewSkillSearchHandler(docEngine, documentService)
providerHandler := handler.NewProviderHandler(userService, modelProviderService)
// Install the agent service's Kvrocks-backed run infrastructure
@@ -1682,41 +1536,16 @@ func startServer(ctx context.Context, args *serverArgs) error {
var mcpSrv *http.Server
var mcpCloser interface{ Close() error }
var mcpListener net.Listener
- if args != nil && args.mcpEnabled {
- resolveUser := func(ctx context.Context, authorization string) (string, error) {
- if args.mcpMode == "self-host" {
- authorization = args.mcpAPIKey
- }
- user, err := authHandler.ResolveMCPUser(ctx, authorization)
- if err != nil {
- return "", err
- }
- return user.ID, nil
- }
- if args.mcpMode == "self-host" {
- authCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
- _, err := resolveUser(authCtx, "")
- cancel()
- if err != nil {
- return errors.New("invalid configured MCP API key")
- }
+ mcpConfig := apiServerConfig.MCP
+ if mcpConfig.Enabled {
+ mcpHandler, err := mcpServerHandler.NewStandalone(ctx, authHandler, mcpConfig)
+ if err != nil {
+ return err
}
- mcpHandler := handler.NewStandaloneMCPHandler(
- resolveUser,
- func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
- return handler.MCPListDatasets(ctx, datasetsService, userID, page, pageSize, orderby, desc)
- },
- func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
- return handler.MCPListChats(ctx, chatService, userID, page, pageSize, orderby, desc)
- },
- func(ctx context.Context, userID string, req mcp.RetrievalRequest) (string, error) {
- return handler.MCPRetrieval(ctx, datasetsService, userID, req)
- },
- mcp.Options{SSE: args.mcpSSE, StreamableHTTP: args.mcpStreamable, JSONResponse: args.mcpJSON},
- )
+
mcpCloser = mcpHandler
defer mcpHandler.Close()
- mcpAddr := fmt.Sprintf("%s:%d", args.mcpHost, args.mcpPort)
+ mcpAddr := net.JoinHostPort(strings.Trim(mcpConfig.Host, "[]"), strconv.Itoa(mcpConfig.Port))
mcpListener, err = net.Listen("tcp", mcpAddr)
if err != nil {
return fmt.Errorf("listen MCP server on %s: %w", mcpAddr, err)
diff --git a/cmd/ragflow_server_test.go b/cmd/ragflow_server_test.go
index ae72f5c407..288831c96a 100644
--- a/cmd/ragflow_server_test.go
+++ b/cmd/ragflow_server_test.go
@@ -27,123 +27,6 @@ import (
"ragflow/internal/service"
)
-func withArgsAndEnv(t *testing.T, args []string, env map[string]string, fn func()) {
- t.Helper()
- oldArgs := os.Args
- os.Args = append([]string{"ragflow_server"}, args...)
- t.Cleanup(func() { os.Args = oldArgs })
- keys := []string{
- "RAGFLOW_MCP_HOST",
- "RAGFLOW_MCP_PORT",
- "RAGFLOW_MCP_LAUNCH_MODE",
- "RAGFLOW_MCP_HOST_API_KEY",
- "RAGFLOW_MCP_ENABLED",
- "RAGFLOW_MCP_TRANSPORT_SSE_ENABLED",
- "RAGFLOW_MCP_TRANSPORT_STREAMABLE_ENABLED",
- "RAGFLOW_MCP_JSON_RESPONSE",
- }
- oldEnv := make(map[string]*string, len(keys))
- for _, key := range keys {
- if value, ok := os.LookupEnv(key); ok {
- v := value
- oldEnv[key] = &v
- } else {
- oldEnv[key] = nil
- }
- os.Unsetenv(key)
- }
- t.Cleanup(func() {
- for key, value := range oldEnv {
- if value == nil {
- os.Unsetenv(key)
- continue
- }
- os.Setenv(key, *value)
- }
- })
- for key, value := range env {
- os.Setenv(key, value)
- }
- fn()
-}
-
-func TestParseArgsMCPEnvOverridesCLI(t *testing.T) {
- withArgsAndEnv(t,
- []string{"--api", "--enable-mcpserver", "--mcp-host=cli", "--mcp-port=10001", "--mcp-mode=host", "--mcp-host-api-key=cli-key", "--no-transport-sse-enabled", "--no-transport-streamable-http-enabled", "--no-json-response"},
- map[string]string{
- "RAGFLOW_MCP_HOST": "env-host",
- "RAGFLOW_MCP_PORT": "10002",
- "RAGFLOW_MCP_LAUNCH_MODE": "self-host",
- "RAGFLOW_MCP_HOST_API_KEY": "env-key",
- "RAGFLOW_MCP_ENABLED": "yes",
- "RAGFLOW_MCP_TRANSPORT_SSE_ENABLED": "true",
- "RAGFLOW_MCP_TRANSPORT_STREAMABLE_ENABLED": "true",
- "RAGFLOW_MCP_JSON_RESPONSE": "true",
- }, func() {
- args, err := parseArgs()
- if err != nil {
- t.Fatalf("parseArgs: %v", err)
- }
- if args.mcpHost != "env-host" || args.mcpPort != 10002 || args.mcpMode != "self-host" || args.mcpAPIKey != "env-key" {
- t.Fatalf("env did not override CLI: %#v", args)
- }
- if !args.mcpEnabled || !args.mcpSSE || !args.mcpStreamable || !args.mcpJSON {
- t.Fatalf("env bools did not resolve true: %#v", args)
- }
- })
-}
-
-func TestParseArgsMCPTransportFallbackMatchesPython(t *testing.T) {
- withArgsAndEnv(t,
- []string{"--api", "--enable-mcpserver", "--mcp-mode=host", "--no-transport-sse-enabled", "--no-transport-streamable-http-enabled"},
- nil, func() {
- args, err := parseArgs()
- if err != nil {
- t.Fatalf("parseArgs: %v", err)
- }
- if args.mcpSSE {
- t.Fatal("SSE should stay disabled")
- }
- if !args.mcpStreamable {
- t.Fatal("streamable HTTP should be re-enabled when both transports are disabled")
- }
- if args.mcpJSON {
- t.Fatal("JSON response should be false because Python disables JSON before both-disabled fallback")
- }
- })
-}
-
-func TestParseArgsMCPValidation(t *testing.T) {
- t.Run("invalid mode", func(t *testing.T) {
- withArgsAndEnv(t, []string{"--api", "--mcp-mode=bogus"}, nil, func() {
- if _, err := parseArgs(); err == nil {
- t.Fatal("expected invalid mode error")
- }
- })
- })
- t.Run("invalid port", func(t *testing.T) {
- withArgsAndEnv(t, []string{"--api", "--mcp-port=0"}, nil, func() {
- if _, err := parseArgs(); err == nil {
- t.Fatal("expected invalid port error")
- }
- })
- })
- t.Run("missing self-host key only when enabled", func(t *testing.T) {
- withArgsAndEnv(t, []string{"--api", "--enable-mcpserver"}, nil, func() {
- if _, err := parseArgs(); err == nil {
- t.Fatal("expected missing self-host key error")
- }
- })
- })
- t.Run("self-host key not required while disabled", func(t *testing.T) {
- withArgsAndEnv(t, []string{"--api"}, nil, func() {
- if _, err := parseArgs(); err != nil {
- t.Fatalf("parseArgs: %v", err)
- }
- })
- })
-}
-
func kb(embdID string, tenantEmbdID string) *entity.Knowledgebase {
kb := &entity.Knowledgebase{EmbdID: embdID}
if tenantEmbdID != "" {
@@ -357,6 +240,20 @@ func TestParseArgsModeResetsMigrate(t *testing.T) {
}
}
+func TestParseArgsKeepsMCPOutOfCLI(t *testing.T) {
+ t.Setenv("RAGFLOW_MCP_PORT", "invalid")
+ for _, mode := range []string{"--api", "--admin", "--ingestor", "--syncer", "--migrate", "--help", "--version"} {
+ if _, err := parseArgsForTest(t, mode); err != nil {
+ t.Fatalf("%s depends on MCP environment: %v", mode, err)
+ }
+ }
+ for _, flag := range []string{"--enable-mcpserver", "--mcp-host=localhost", "--mcp-port=9382", "--mcp-mode=host", "--mcp-host-api-key=unused", "--transport-sse-enabled", "--no-transport-sse-enabled", "--transport-streamable-http-enabled", "--no-transport-streamable-http-enabled", "--json-response", "--no-json-response"} {
+ if _, err := parseArgsForTest(t, "--api", flag); err == nil {
+ t.Fatalf("obsolete MCP flag accepted: %s", flag)
+ }
+ }
+}
+
// errStubEncode stands in for a provider-side embedding failure.
var errStubEncode = errors.New("stub encode failure")
diff --git a/conf/service_conf.yaml b/conf/service_conf.yaml
index ed4e86360c..f2ae7e5c35 100644
--- a/conf/service_conf.yaml
+++ b/conf/service_conf.yaml
@@ -9,6 +9,21 @@ ragflow:
# replaces that default, so keep the loopback entries when adding the address
# or CIDR of a further proxy in front of nginx; an empty list trusts none.
# trusted_proxies: ['127.0.0.0/8', '::1/128']
+
+# Optional standalone MCP listener for the Go API server. Uncomment to enable.
+# RAGFLOW_MCP_* environment variables override these settings.
+# mcp:
+# enabled: true
+# host: 127.0.0.1
+# port: 9382
+# launch_mode: host # Each client supplies its own RAGFlow API key.
+# # self-host gives every client the same identity; use only on trusted networks.
+# # Set host_api_key below or, preferably, RAGFLOW_MCP_HOST_API_KEY.
+# host_api_key: ''
+# transport_sse_enabled: true # /sse and /messages/
+# transport_streamable_enabled: true # /mcp
+# json_response: true # false streams Streamable HTTP responses.
+
admin:
host: 0.0.0.0
http_port: 9381
diff --git a/docker/.env-go b/docker/.env-go
index c03488a511..26078c60d7 100644
--- a/docker/.env-go
+++ b/docker/.env-go
@@ -419,3 +419,12 @@ DISABLE_PASSWORD_LOGIN=false
# Docker image for the OSS deepdoc service. CPU-only; uses ONNX Runtime.
# DEEPDOC_IMAGE=deepdoc_oss:latest
+
+# -----------------------------------------------------------------------------
+# Native Go MCP listener settings
+# -----------------------------------------------------------------------------
+# RAGFLOW_MCP_ENABLED=true
+# RAGFLOW_MCP_HOST=0.0.0.0
+# RAGFLOW_MCP_PORT=9382
+# RAGFLOW_MCP_LAUNCH_MODE=self-host
+# RAGFLOW_MCP_HOST_API_KEY=
\ No newline at end of file
diff --git a/docker/entrypoint-go.sh b/docker/entrypoint-go.sh
index a1a85579dd..aeb147d1da 100755
--- a/docker/entrypoint-go.sh
+++ b/docker/entrypoint-go.sh
@@ -14,7 +14,6 @@ function usage() {
echo " --disable-webserver Disables the web server (nginx + ragflow_server)."
echo " --disable-taskexecutor Disables task executor workers."
echo " --disable-datasync Disables synchronization of datasource workers."
- echo " --enable-mcpserver Enables the MCP server."
echo " --enable-adminserver Enables the Admin server."
echo " --init-model-provider-tables Run model provider table migrations and exit."
echo " --init-superuser Initializes the superuser (needs --enable-adminserver)."
@@ -22,21 +21,13 @@ function usage() {
echo " --consumer-no-end=<num> End range for consumers (if using range-based)."
echo " --workers=<num> Number of task executors to run (if range is not used)."
echo " --host-id=<string> Unique ID for the host (defaults to \`hostname\`)."
- echo " --mcp-host=<string> Address the MCP server binds to (default: 127.0.0.1)."
- echo " --mcp-port=<num> Port the MCP server listens on (default: 9382)."
- echo " --mcp-mode=<self-host|host> MCP server mode (default: self-host)."
- echo " --mcp-host-api-key=<string> API key required when --mcp-mode=self-host."
- echo " --no-transport-sse-enabled Disables the MCP SSE transport."
- echo " --no-transport-streamable-http-enabled Disables the MCP streamable HTTP transport. Disabling"
- echo " both transports re-enables this one, since the server"
- echo " requires at least one."
- echo " --no-json-response Disables JSON responses from the MCP server."
+ echo
+ echo "MCP: configure service_conf.yaml or RAGFLOW_MCP_* environment variables."
echo
echo "Examples:"
echo " $0 --disable-taskexecutor"
echo " $0 --disable-webserver --consumer-no-beg=0 --consumer-no-end=5"
echo " $0 --disable-webserver --workers=2 --host-id=myhost123"
- echo " $0 --enable-mcpserver"
echo " $0 --enable-adminserver"
echo " $0 --enable-adminserver --init-superuser"
exit 1
@@ -45,7 +36,6 @@ function usage() {
ENABLE_WEBSERVER=1 # Default to enable web server
ENABLE_TASKEXECUTOR=1 # Default to enable task executor
ENABLE_DATASYNC=1
-ENABLE_MCP_SERVER=0
ENABLE_ADMIN_SERVER=0 # Default close admin server
INIT_SUPERUSER_ARGS="" # Default to not initialize superuser
INIT_MODEL_PROVIDER_TABLES=0
@@ -53,14 +43,6 @@ CONSUMER_NO_BEG=0
CONSUMER_NO_END=0
WORKERS=1
-MCP_HOST="127.0.0.1"
-MCP_PORT=9382
-MCP_MODE="self-host"
-MCP_HOST_API_KEY=""
-MCP_TRANSPORT_SSE_FLAG="--transport-sse-enabled"
-MCP_TRANSPORT_STREAMABLE_HTTP_FLAG="--transport-streamable-http-enabled"
-MCP_JSON_RESPONSE_FLAG="--json-response"
-
# -----------------------------------------------------------------------------
# Host ID logic:
# 1. By default, use the system hostname if length <= 32
@@ -90,10 +72,6 @@ for arg in "$@"; do
ENABLE_DATASYNC=0
shift
;;
- --enable-mcpserver)
- ENABLE_MCP_SERVER=1
- shift
- ;;
--enable-adminserver)
ENABLE_ADMIN_SERVER=1
shift
@@ -106,34 +84,6 @@ for arg in "$@"; do
INIT_SUPERUSER_ARGS="--init-superuser"
shift
;;
- --mcp-host=*)
- MCP_HOST="${arg#*=}"
- shift
- ;;
- --mcp-port=*)
- MCP_PORT="${arg#*=}"
- shift
- ;;
- --mcp-mode=*)
- MCP_MODE="${arg#*=}"
- shift
- ;;
- --mcp-host-api-key=*)
- MCP_HOST_API_KEY="${arg#*=}"
- shift
- ;;
- --transport-sse-enabled|--no-transport-sse-enabled)
- MCP_TRANSPORT_SSE_FLAG="$arg"
- shift
- ;;
- --transport-streamable-http-enabled|--no-transport-streamable-http-enabled)
- MCP_TRANSPORT_STREAMABLE_HTTP_FLAG="$arg"
- shift
- ;;
- --json-response|--no-json-response)
- MCP_JSON_RESPONSE_FLAG="$arg"
- shift
- ;;
--consumer-no-beg=*)
CONSUMER_NO_BEG="${arg#*=}"
shift
@@ -270,24 +220,11 @@ if [[ "${ENABLE_WEBSERVER}" -eq 1 ]]; then
/usr/sbin/nginx -c /etc/nginx/nginx.conf
echo "Starting RAGFlow go server..."
- MCP_ARGS=()
- if [[ "${ENABLE_MCP_SERVER}" -eq 1 ]]; then
- MCP_ARGS=(
- --enable-mcpserver
- --mcp-host="${MCP_HOST}"
- --mcp-port="${MCP_PORT}"
- --mcp-mode="${MCP_MODE}"
- --mcp-host-api-key="${MCP_HOST_API_KEY}"
- "${MCP_TRANSPORT_SSE_FLAG}"
- "${MCP_TRANSPORT_STREAMABLE_HTTP_FLAG}"
- "${MCP_JSON_RESPONSE_FLAG}"
- )
- fi
- run_with_restart "RAGFlow go server" bin/ragflow_server --api "${MCP_ARGS[@]}" &
+ run_with_restart "RAGFlow go server" bin/ragflow_server --api &
fi
-# MCP needs no separate process: --api serves it in-process at POST /mcp on the
-# main API port.
+# MCP configuration comes from service_conf.yaml and RAGFLOW_MCP_* environment
+# variables. The API process owns its optional standalone listener.
# Task execution is the Go ingestor's job. This image ships no Python task
# executor (rag/svr/task_executor.py is not copied), so --ingestor is the only
diff --git a/docker/service_conf.yaml.template b/docker/service_conf.yaml.template
index 4107479f06..788f53ff9e 100644
--- a/docker/service_conf.yaml.template
+++ b/docker/service_conf.yaml.template
@@ -9,6 +9,21 @@ ragflow:
# replaces that default, so keep the loopback entries when adding the address
# or CIDR of a further proxy in front of nginx; an empty list trusts none.
# trusted_proxies: ['127.0.0.0/8', '::1/128']
+
+# Optional standalone MCP listener for the Go API server. Uncomment to enable.
+# RAGFLOW_MCP_* environment variables override these settings.
+# mcp:
+# enabled: true
+# host: 0.0.0.0 # Publish port 9382 in Compose to reach this container.
+# port: 9382
+# launch_mode: host # Each client supplies its own RAGFlow API key.
+# # self-host gives every client the same identity; use only on trusted networks.
+# # Set host_api_key below or, preferably, RAGFLOW_MCP_HOST_API_KEY.
+# host_api_key: ''
+# transport_sse_enabled: true # /sse and /messages/
+# transport_streamable_enabled: true # /mcp
+# json_response: true # false streams Streamable HTTP responses.
+
admin:
host: ${RAGFLOW_HOST:-0.0.0.0}
http_port: 9381
diff --git a/docs/develop/mcp/native_go_mcp.md b/docs/develop/mcp/native_go_mcp.md
index da623e1a2b..d36cfd0d3c 100644
--- a/docs/develop/mcp/native_go_mcp.md
+++ b/docs/develop/mcp/native_go_mcp.md
@@ -11,50 +11,76 @@ sidebar_custom_props: {
The Go API server can host RAGFlow's MCP runtime in-process. It does not launch `mcp/server/server.py` and does not need a RAGFlow base URL because MCP tool calls use Go services directly.
-## Docker
-
-Use the Go entrypoint with MCP enabled:
-
-```bash
-./entrypoint-go.sh --enable-mcpserver \
- --mcp-host=0.0.0.0 \
- --mcp-port=9382 \
- --mcp-mode=self-host \
- --mcp-host-api-key=ragflow-xxxxx
+## Configuration
+
+The Go API process owns the optional standalone MCP listener. Configure it in the
+existing `service_conf.yaml` (selected with `--config`), or use environment
+variables. MCP settings are no longer command-line flags in either
+`ragflow_server` or `entrypoint-go.sh`; replace those flags with the settings below.
+Mode selection, help, version and configuration-file selection remain CLI options.
+
+This example enables the listener for clients that each supply their own credential:
+
+```yaml
+mcp:
+ enabled: true
+ host: 127.0.0.1
+ port: 9382
+ launch_mode: host
+ transport_sse_enabled: true
+ transport_streamable_enabled: true
+ json_response: true
```
-Host mode requires each client request to provide a credential:
-
-```bash
-./entrypoint-go.sh --enable-mcpserver --mcp-mode=host
-```
-
-Host-mode requests accept `Authorization: Bearer <key>`, `api_key`, `X-API-Key`, or `Api-Key`.
-
-## Transport flags
-
-Both legacy SSE (`/sse` and `/messages/`) and streamable HTTP (`/mcp`) are enabled by default. JSON responses for streamable HTTP are also enabled by default.
-
-```bash
---no-transport-sse-enabled # disable legacy SSE
---no-transport-streamable-http-enabled # disable streamable HTTP
---no-json-response # use SSE-style streamable HTTP responses
-```
-
-If both transports are disabled, streamable HTTP is re-enabled and JSON responses stay disabled, matching the Python MCP server's flag resolution.
-
-The same settings can be supplied through environment variables. Environment values override CLI flags:
-
-```bash
-RAGFLOW_MCP_ENABLED=true
-RAGFLOW_MCP_HOST=0.0.0.0
-RAGFLOW_MCP_PORT=9382
-RAGFLOW_MCP_LAUNCH_MODE=self-host
-RAGFLOW_MCP_HOST_API_KEY=ragflow-xxxxx
-RAGFLOW_MCP_TRANSPORT_SSE_ENABLED=true
-RAGFLOW_MCP_TRANSPORT_STREAMABLE_ENABLED=true
-RAGFLOW_MCP_JSON_RESPONSE=true
-```
+Start the binary with `bin/ragflow_server --api --config conf/service_conf.yaml`.
+Uncomment the MCP example in `conf/service_conf.yaml` for a local binary, or in
+`docker/service_conf.yaml.template` for Docker. The Docker entrypoint generates
+`service_conf.yaml` from that template on startup, so edit the template rather
+than the generated file. Alternatively, put the environment settings in
+`docker/.env-go`. Start `entrypoint-go.sh` without MCP flags.
+For access through a published Docker port, set the container bind address to
+`0.0.0.0` and publish `9382`; use host mode for clients outside a trusted network.
+The existing MCP endpoint on the main API remains available independently.
+
+Environment values override YAML, which overrides built-in defaults:
+
+| Environment variable | YAML field under `mcp` | Default |
+| --- | --- | --- |
+| `RAGFLOW_MCP_ENABLED` | `enabled` | `false` |
+| `RAGFLOW_MCP_HOST` | `host` | `127.0.0.1` |
+| `RAGFLOW_MCP_PORT` | `port` | `9382` |
+| `RAGFLOW_MCP_LAUNCH_MODE` | `launch_mode` | `self-host` |
+| `RAGFLOW_MCP_HOST_API_KEY` | `host_api_key` | empty |
+| `RAGFLOW_MCP_TRANSPORT_SSE_ENABLED` | `transport_sse_enabled` | `true` |
+| `RAGFLOW_MCP_TRANSPORT_STREAMABLE_ENABLED` | `transport_streamable_enabled` | `true` |
+| `RAGFLOW_MCP_JSON_RESPONSE` | `json_response` | `true` |
+
+Boolean values `1`, `true`, `yes` and `on` are true (case-insensitive, surrounding
+whitespace ignored); other values are false. Explicitly empty environment values
+override YAML too. An empty host binds all interfaces; use `127.0.0.1` to restrict
+access to the local machine. Invalid ports or launch modes reject startup.
+
+## Authentication
+
+Host mode resolves each request independently. Clients may supply
+`Authorization: Bearer <key>`, `api_key`, `X-API-Key`, or `Api-Key`.
+
+Self-host mode intentionally gives **every connected client the configured user's
+identity**, ignoring client credentials. It is for a trusted local deployment or
+an access-controlled network. Enabling it requires `RAGFLOW_MCP_HOST_API_KEY` or
+`mcp.host_api_key`. The key is checked at startup and on every request, so revocation
+still takes effect. Keep secrets in the deployment environment, out of command
+arguments and committed files. The key is omitted from configuration logs.
+
+## Transports
+
+Both SSE (`/sse` and `/messages/`) and streamable HTTP (`/mcp`) are enabled by
+default. Set `transport_sse_enabled` or `transport_streamable_enabled` to `false`
+to disable one. Set `json_response: false` to stream streamable HTTP responses.
+
+If streamable HTTP is disabled, JSON responses are disabled first. If both
+transports are disabled, streamable HTTP is then re-enabled with JSON responses
+still disabled, preserving the Python server's resolution order.
## Streamable HTTP smoke example
diff --git a/internal/handler/mcp_retrieval.go b/internal/handler/mcp_retrieval.go
index 4c79cc708b..ce9bd82440 100644
--- a/internal/handler/mcp_retrieval.go
+++ b/internal/handler/mcp_retrieval.go
@@ -36,10 +36,10 @@ func validateRetrievalWindow(page, pageSize int) error {
return nil
}
-// MCPRetrieval executes a retrieval request on behalf of the MCP tool handler.
+// mcpRetrieval executes a retrieval request on behalf of the MCP tool handler.
// It translates the mcp.RetrievalRequest into a service.SearchDatasetsRequest
// and calls DatasetService.SearchDatasets. The result is serialized as JSON.
-func MCPRetrieval(ctx context.Context, ds *dataset.DatasetService, userID string, req mcp.RetrievalRequest) (string, error) {
+func mcpRetrieval(ctx context.Context, ds *dataset.DatasetService, userID string, req mcp.RetrievalRequest) (string, error) {
if err := validateRetrievalWindow(req.Page, req.PageSize); err != nil {
return "", err
}
diff --git a/internal/handler/mcp_server.go b/internal/handler/mcp_server.go
index 53633f269b..818db68755 100644
--- a/internal/handler/mcp_server.go
+++ b/internal/handler/mcp_server.go
@@ -18,12 +18,15 @@ package handler
import (
"context"
+ "errors"
+ "time"
"github.com/gin-gonic/gin"
"ragflow/internal/common"
"ragflow/internal/dao"
"ragflow/internal/mcp"
+ "ragflow/internal/server/config"
"ragflow/internal/service"
dataset "ragflow/internal/service/dataset"
)
@@ -36,32 +39,50 @@ type MCPServerHandler struct {
retrievalFunc func(ctx context.Context, userID string, req mcp.RetrievalRequest) (string, error)
}
-// NewStandaloneMCPHandler exposes the native SDK transports.
-func NewStandaloneMCPHandler(
- resolveUser func(context.Context, string) (string, error),
- listDatasetsFunc func(context.Context, string, int, int, string, bool) ([]map[string]interface{}, int64, error),
- listChatsFunc func(context.Context, string, int, int, string, bool) ([]map[string]interface{}, int64, error),
- retrievalFunc func(context.Context, string, mcp.RetrievalRequest) (string, error),
- opts mcp.Options,
-) *mcp.Handler {
+// NewMCPServerHandler shares the service callbacks between API and standalone transports.
+func NewMCPServerHandler(ds *dataset.DatasetService, chats *service.ChatService) *MCPServerHandler {
+ return &MCPServerHandler{
+ listDatasetsFunc: func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
+ return mcpListDatasets(ctx, ds, userID, page, pageSize, orderby, desc)
+ },
+ listChatsFunc: func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
+ return mcpListChats(ctx, chats, userID, page, pageSize, orderby, desc)
+ },
+ retrievalFunc: func(ctx context.Context, userID string, req mcp.RetrievalRequest) (string, error) {
+ return mcpRetrieval(ctx, ds, userID, req)
+ },
+ }
+}
+
+func (h *MCPServerHandler) newTransport(resolveUser func(context.Context, string) (string, error), opts mcp.Options) *mcp.Handler {
return mcp.NewHandler(resolveUser, func(userID string) mcp.Connector {
- return mcp.NewServiceConnector(userID, listDatasetsFunc, listChatsFunc, retrievalFunc)
+ return mcp.NewServiceConnector(userID, h.listDatasetsFunc, h.listChatsFunc, h.retrievalFunc)
}, opts)
}
-// NewMCPServerHandler creates a new MCPServerHandler.
-// The service functions are passed as closures to avoid importing the service
-// package directly from the handler layer.
-func NewMCPServerHandler(
- listDatasetsFunc func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error),
- listChatsFunc func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error),
- retrievalFunc func(ctx context.Context, userID string, req mcp.RetrievalRequest) (string, error),
-) *MCPServerHandler {
- return &MCPServerHandler{
- listDatasetsFunc: listDatasetsFunc,
- listChatsFunc: listChatsFunc,
- retrievalFunc: retrievalFunc,
+// NewStandalone validates the configured identity before creating transport sessions.
+// Self-host mode intentionally gives trusted clients the configured user's identity;
+// host mode resolves each request's credentials independently.
+func (h *MCPServerHandler) NewStandalone(ctx context.Context, auth *AuthHandler, cfg config.MCPConfig) (*mcp.Handler, error) {
+ resolveUser := func(ctx context.Context, authorization string) (string, error) {
+ if cfg.LaunchMode == "self-host" {
+ authorization = cfg.HostAPIKey
+ }
+ user, err := auth.ResolveMCPUser(ctx, authorization)
+ if err != nil {
+ return "", err
+ }
+ return user.ID, nil
+ }
+ if cfg.LaunchMode == "self-host" {
+ authCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
+ _, err := resolveUser(authCtx, "")
+ cancel()
+ if err != nil {
+ return nil, errors.New("invalid configured MCP API key")
+ }
}
+ return h.newTransport(resolveUser, mcp.Options{SSE: cfg.SSE, StreamableHTTP: cfg.StreamableHTTP, JSONResponse: cfg.JSONResponse}), nil
}
// HandleMCP is the Gin handler for the MCP endpoint. It reads the JSON-RPC
@@ -81,7 +102,7 @@ func (h *MCPServerHandler) HandleMCP(c *gin.Context) {
return
}
- hdl := NewStandaloneMCPHandler(func(context.Context, string) (string, error) { return user.ID, nil }, h.listDatasetsFunc, h.listChatsFunc, h.retrievalFunc, mcp.Options{StreamableHTTP: true, JSONResponse: true})
+ hdl := h.newTransport(func(context.Context, string) (string, error) { return user.ID, nil }, mcp.Options{StreamableHTTP: true, JSONResponse: true})
defer hdl.Close()
request := c.Request.Clone(c.Request.Context())
request.URL.Path = "/mcp"
@@ -93,9 +114,9 @@ func (h *MCPServerHandler) HandleMCP(c *gin.Context) {
hdl.ServeHTTP(c.Writer, request)
}
-// MCPListDatasets wraps DatasetService.ListDatasets for the MCP tool handler,
+// mcpListDatasets wraps DatasetService.ListDatasets for the MCP tool handler,
// filling in default values for parameters that the MCP tool does not expose.
-func MCPListDatasets(ctx context.Context, ds *dataset.DatasetService, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
+func mcpListDatasets(ctx context.Context, ds *dataset.DatasetService, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
data, total, _, err := ds.ListDatasets(ctx,
"", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}},
"", nil, "", userID, nil,
@@ -103,9 +124,9 @@ func MCPListDatasets(ctx context.Context, ds *dataset.DatasetService, userID str
return data, total, err
}
-// MCPListChats wraps ChatService.ListChats for the MCP tool handler,
+// mcpListChats wraps ChatService.ListChats for the MCP tool handler,
// converting the typed response into a generic []map[string]interface{}.
-func MCPListChats(ctx context.Context, chatService *service.ChatService, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
+func mcpListChats(ctx context.Context, chatService *service.ChatService, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
resp, err := chatService.ListChats(ctx, userID, "1", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}}, nil)
if err != nil {
return nil, 0, err
diff --git a/internal/handler/mcp_server_test.go b/internal/handler/mcp_server_test.go
new file mode 100644
index 0000000000..60d1d9b570
--- /dev/null
+++ b/internal/handler/mcp_server_test.go
@@ -0,0 +1,81 @@
+package handler
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "ragflow/internal/common"
+ "ragflow/internal/entity"
+ "ragflow/internal/server/config"
+)
+
+func TestStandaloneMCPIdentityAndRevocation(t *testing.T) {
+ for _, mode := range []string{"self-host", "host"} {
+ t.Run(mode, func(t *testing.T) {
+ calls := 0
+ revoked := false
+ lastKey := ""
+ auth := &AuthHandler{userService: &stubUserTokenResolver{getUserByTokenFn: func(ctx context.Context, key string) (*entity.User, common.ErrorCode, error) {
+ calls++
+ lastKey = key
+ if mode == "self-host" && calls == 1 {
+ if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > 60*time.Second {
+ t.Error("missing bounded key preflight")
+ }
+ }
+ if revoked {
+ return nil, common.CodeUnauthorized, errors.New("revoked")
+ }
+ return &entity.User{ID: key}, common.CodeSuccess, nil
+ }}}
+ h, err := (&MCPServerHandler{}).NewStandalone(t.Context(), auth, config.MCPConfig{LaunchMode: mode, HostAPIKey: "configured-key", SSE: true, StreamableHTTP: true, JSONResponse: true})
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer h.Close()
+ warmup := 0
+ if mode == "self-host" {
+ warmup = 1
+ }
+ if calls != warmup {
+ t.Fatalf("startup auth calls=%d want %d", calls, warmup)
+ }
+ for _, key := range []string{"alice", "bob"} {
+ req := httptest.NewRequest(http.MethodGet, "http://localhost/unknown", nil)
+ req.Header.Set("Authorization", "Bearer "+key)
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ want := key
+ if mode == "self-host" {
+ want = "configured-key"
+ }
+ if w.Code != http.StatusNotFound || lastKey != want {
+ t.Fatalf("credential mapping: %d %q", w.Code, lastKey)
+ }
+ }
+ if calls != warmup+2 {
+ t.Fatalf("identity cached: %d calls", calls)
+ }
+ revoked = true
+ req := httptest.NewRequest(http.MethodGet, "http://localhost/mcp", nil)
+ req.Header.Set("Authorization", "Bearer alice")
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, req)
+ if w.Code != http.StatusUnauthorized {
+ t.Fatalf("revoked key accepted: %d", w.Code)
+ }
+ })
+ }
+}
+
+func TestStandaloneMCPRejectsInvalidConfiguredKey(t *testing.T) {
+ auth := &AuthHandler{userService: &stubUserTokenResolver{}}
+ h, err := (&MCPServerHandler{}).NewStandalone(t.Context(), auth, config.MCPConfig{LaunchMode: "self-host", HostAPIKey: "do-not-print-me"})
+ if h != nil || err == nil || err.Error() != "invalid configured MCP API key" {
+ t.Fatalf("invalid preflight result: handler=%v error=%v", h, err)
+ }
+}
diff --git a/internal/mcp/http.go b/internal/mcp/http.go
index f5489f62b3..4f87c4872b 100644
--- a/internal/mcp/http.go
+++ b/internal/mcp/http.go
@@ -4,6 +4,7 @@ import (
"context"
"crypto/rand"
"mime"
+ "net"
"net/http"
"net/url"
"strings"
@@ -105,6 +106,15 @@ func NewHandler(resolve func(context.Context, string) (string, error), connector
})
}
protected := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ // Apply the SDK's localhost protection before authentication on BOTH
+ // transports; the custom SSE transport does not pass through its handler.
+ if local, ok := r.Context().Value(http.LocalAddrContextKey).(*net.TCPAddr); ok && local.IP.IsLoopback() {
+ host := (&url.URL{Host: r.Host}).Hostname()
+ if host != "localhost" && !net.ParseIP(host).IsLoopback() {
+ http.Error(w, "invalid host", http.StatusForbidden)
+ return
+ }
+ }
// Reject cross-origin browser access, including GET streams.
if origin := r.Header.Get("Origin"); origin != "" {
u, err := url.Parse(origin)
diff --git a/internal/mcp/http_test.go b/internal/mcp/http_test.go
index 1e7fa00428..0c78ad2090 100644
--- a/internal/mcp/http_test.go
+++ b/internal/mcp/http_test.go
@@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"io"
+ "net"
"net/http"
"net/http/httptest"
"reflect"
@@ -308,3 +309,45 @@ func TestProtocolErrorsAndCancellation(t *testing.T) {
}
<-done
}
+
+func TestTransportsRejectLoopbackDNSRebinding(t *testing.T) {
+ for _, path := range []string{"/sse", "/messages/", "/mcp"} {
+ for _, tc := range []struct {
+ local, host string
+ blocked bool
+ }{
+ {"127.0.0.1", "attacker.example", true}, {"::1", "localhost.attacker.example", true},
+ {"127.0.0.1", "localhost:9382", false}, {"::1", "[::1]:9382", false},
+ {"127.0.0.1", "127.0.0.2:9382", false}, {"192.0.2.1", "mcp.example", false},
+ } {
+ t.Run(path+tc.local+tc.host, func(t *testing.T) {
+ called := false
+ h := NewHandler(func(context.Context, string) (string, error) { called = true; return "", fmt.Errorf("no credentials") }, nil, Options{true, true, true})
+ defer h.Close()
+ r := httptest.NewRequest(http.MethodGet, "http://"+tc.host+path, nil)
+ r.Header.Set("Origin", "http://"+tc.host)
+ r = r.WithContext(context.WithValue(r.Context(), http.LocalAddrContextKey, &net.TCPAddr{IP: net.ParseIP(tc.local), Port: 9382}))
+ w := httptest.NewRecorder()
+ h.ServeHTTP(w, r)
+ want := http.StatusUnauthorized
+ if tc.blocked {
+ want = http.StatusForbidden
+ }
+ if w.Code != want || called == tc.blocked {
+ t.Fatalf("status=%d authorization called=%v; want status=%d", w.Code, called, want)
+ }
+ })
+ }
+ }
+}
+
+func BenchmarkMCPLoopbackRequest(b *testing.B) {
+ h := NewHandler(func(context.Context, string) (string, error) { return "user", nil }, nil, Options{true, true, true})
+ defer h.Close()
+ r := httptest.NewRequest(http.MethodGet, "http://localhost/unknown", nil)
+ r = r.WithContext(context.WithValue(r.Context(), http.LocalAddrContextKey, &net.TCPAddr{IP: net.ParseIP("127.0.0.1"), Port: 9382}))
+ b.ReportAllocs()
+ for b.Loop() {
+ h.ServeHTTP(httptest.NewRecorder(), r)
+ }
+}
diff --git a/internal/server/config.go b/internal/server/config.go
index 6a63a5c3b3..701cc79091 100644
--- a/internal/server/config.go
+++ b/internal/server/config.go
@@ -279,6 +279,10 @@ func PrintAll() {
}
allSettings := globalViper.AllSettings()
+ // The standalone MCP key grants every self-host client the same identity.
+ if mcp, ok := allSettings["mcp"].(map[string]interface{}); ok {
+ delete(mcp, "host_api_key")
+ }
common.Info("=== All Configurations ===")
for key, value := range allSettings {
common.Info("config", zap.String("key", key), zap.Any("value", value))
diff --git a/internal/server/config/api_server_config.go b/internal/server/config/api_server_config.go
index 2d212de8a3..3ec6f162fe 100644
--- a/internal/server/config/api_server_config.go
+++ b/internal/server/config/api_server_config.go
@@ -24,6 +24,7 @@ type AuthenticationConfig struct {
}
type APIServerConfig struct {
+ MCP MCPConfig
Host string `mapstructure:"host"`
HTTPPort int `mapstructure:"http_port"`
// TrustedProxies lists the IPs / CIDRs whose X-Forwarded-For and
@@ -38,6 +39,10 @@ type APIServerConfig struct {
}
func (c *Config) ParseAPIServerConfig(v *viper.Viper) error {
+ if err := c.parseMCPConfig(v); err != nil {
+ return err
+ }
+
// Default Admin config
c.apiServer.Host = "localhost"
c.apiServer.HTTPPort = 9384
diff --git a/internal/server/config/mcp_config.go b/internal/server/config/mcp_config.go
new file mode 100644
index 0000000000..b4fe6f542c
--- /dev/null
+++ b/internal/server/config/mcp_config.go
@@ -0,0 +1,90 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package config
+
+import (
+ "fmt"
+ "os"
+ "strconv"
+ "strings"
+
+ "github.com/spf13/viper"
+)
+
+// MCPConfig configures the API server's optional standalone MCP listener.
+type MCPConfig struct {
+ Enabled bool
+ Host string
+ Port int
+ LaunchMode string
+ HostAPIKey string
+ SSE bool
+ StreamableHTTP bool
+ JSONResponse bool
+}
+
+func (c *Config) parseMCPConfig(v *viper.Viper) error {
+ // LookupEnv preserves explicitly empty overrides. Viper's AutomaticEnv
+ // ignores them by default; its nested Sub views also lose the root prefix.
+ value := func(key, fallback string) string {
+ if value, ok := os.LookupEnv("RAGFLOW_MCP_" + strings.ToUpper(key)); ok {
+ return value
+ }
+ if v.IsSet("mcp." + key) {
+ return v.GetString("mcp." + key)
+ }
+ return fallback
+ }
+ port, err := strconv.Atoi(value("port", "9382"))
+ if err != nil || port <= 0 || port > 65535 {
+ return fmt.Errorf("invalid MCP port: %s", value("port", "9382"))
+ }
+ mcp := MCPConfig{
+ Enabled: parseMCPBool(value("enabled", "false")),
+ Host: value("host", "127.0.0.1"),
+ Port: port,
+ LaunchMode: value("launch_mode", "self-host"),
+ HostAPIKey: value("host_api_key", ""),
+ SSE: parseMCPBool(value("transport_sse_enabled", "true")),
+ StreamableHTTP: parseMCPBool(value("transport_streamable_enabled", "true")),
+ JSONResponse: parseMCPBool(value("json_response", "true")),
+ }
+ if mcp.LaunchMode != "self-host" && mcp.LaunchMode != "host" {
+ return fmt.Errorf("invalid MCP mode: %s", mcp.LaunchMode)
+ }
+ // Match Python: disable JSON before the both-transports-disabled fallback.
+ if !mcp.StreamableHTTP {
+ mcp.JSONResponse = false
+ }
+ if !mcp.SSE && !mcp.StreamableHTTP {
+ mcp.StreamableHTTP = true
+ }
+ if mcp.Enabled && mcp.LaunchMode == "self-host" && mcp.HostAPIKey == "" {
+ return fmt.Errorf("MCP self-host mode requires mcp.host_api_key or RAGFLOW_MCP_HOST_API_KEY")
+ }
+ c.apiServer.MCP = mcp
+ return nil
+}
+
+func parseMCPBool(value string) bool {
+ switch strings.ToLower(strings.TrimSpace(value)) {
+ case "1", "true", "yes", "on":
+ return true
+ default:
+ return false
+ }
+}
diff --git a/internal/server/config/mcp_config_test.go b/internal/server/config/mcp_config_test.go
new file mode 100644
index 0000000000..e21e8ad76e
--- /dev/null
+++ b/internal/server/config/mcp_config_test.go
@@ -0,0 +1,138 @@
+package config
+
+import (
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+
+ "github.com/spf13/viper"
+)
+
+func clearMCPEnv(t *testing.T) {
+ t.Helper()
+ for _, key := range []string{"ENABLED", "HOST", "PORT", "LAUNCH_MODE", "HOST_API_KEY", "TRANSPORT_SSE_ENABLED", "TRANSPORT_STREAMABLE_ENABLED", "JSON_RESPONSE"} {
+ name := "RAGFLOW_MCP_" + key
+ t.Setenv(name, "")
+ if err := os.Unsetenv(name); err != nil {
+ t.Fatal(err)
+ }
+ }
+}
+
+func parseMCPYAML(t *testing.T, text string) (MCPConfig, error) {
+ t.Helper()
+ v := viper.New()
+ v.SetConfigType("yaml")
+ v.SetEnvPrefix("RAGFLOW")
+ v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
+ v.AutomaticEnv()
+ if err := v.ReadConfig(strings.NewReader(text)); err != nil {
+ t.Fatal(err)
+ }
+ var cfg Config
+ err := cfg.ParseAPIServerConfig(v)
+ return cfg.GetAPIServerConfig().MCP, err
+}
+
+func TestMCPConfiguration(t *testing.T) {
+ clearMCPEnv(t)
+ defaults := MCPConfig{Host: "127.0.0.1", Port: 9382, LaunchMode: "self-host", SSE: true, StreamableHTTP: true, JSONResponse: true}
+ got, err := parseMCPYAML(t, "{}")
+ if err != nil || got != defaults {
+ t.Fatalf("defaults: %+v, %v", got, err)
+ }
+ yaml := `mcp:
+ enabled: true
+ host: yaml-host
+ port: 9999
+ launch_mode: host
+ host_api_key: yaml-key
+ transport_sse_enabled: false
+ transport_streamable_enabled: true
+ json_response: false
+`
+ got, err = parseMCPYAML(t, yaml)
+ want := MCPConfig{Enabled: true, Host: "yaml-host", Port: 9999, LaunchMode: "host", HostAPIKey: "yaml-key", StreamableHTTP: true}
+ if err != nil || got != want {
+ t.Fatalf("YAML: %+v, %v", got, err)
+ }
+ overrides := map[string]string{"ENABLED": "yes", "HOST": "env-host", "PORT": "10002", "LAUNCH_MODE": "self-host", "HOST_API_KEY": "env-key", "TRANSPORT_SSE_ENABLED": "ON", "TRANSPORT_STREAMABLE_ENABLED": "1", "JSON_RESPONSE": " True "}
+ for k, v := range overrides {
+ t.Setenv("RAGFLOW_MCP_"+k, v)
+ }
+ got, err = parseMCPYAML(t, yaml)
+ want = MCPConfig{Enabled: true, Host: "env-host", Port: 10002, LaunchMode: "self-host", HostAPIKey: "env-key", SSE: true, StreamableHTTP: true, JSONResponse: true}
+ if err != nil || !reflect.DeepEqual(got, want) {
+ t.Fatalf("environment precedence: %+v, %v", got, err)
+ }
+ t.Setenv("RAGFLOW_MCP_ENABLED", "")
+ t.Setenv("RAGFLOW_MCP_HOST", "")
+ t.Setenv("RAGFLOW_MCP_HOST_API_KEY", "")
+ got, err = parseMCPYAML(t, yaml)
+ if err != nil || got.Enabled || got.Host != "" || got.HostAPIKey != "" {
+ t.Fatalf("empty overrides ignored: %+v, %v", got, err)
+ }
+}
+
+func TestMCPTransportFallback(t *testing.T) {
+ clearMCPEnv(t)
+ for _, sse := range []bool{false, true} {
+ for _, stream := range []bool{false, true} {
+ for _, json := range []bool{false, true} {
+ v := viper.New()
+ v.Set("mcp.transport_sse_enabled", sse)
+ v.Set("mcp.transport_streamable_enabled", stream)
+ v.Set("mcp.json_response", json)
+ var cfg Config
+ if err := cfg.ParseAPIServerConfig(v); err != nil {
+ t.Fatal(err)
+ }
+ got := cfg.GetAPIServerConfig().MCP
+ if got.SSE != sse || got.StreamableHTTP != (stream || !sse) || got.JSONResponse != (json && stream) {
+ t.Fatalf("%v/%v/%v -> %+v", sse, stream, json, got)
+ }
+ }
+ }
+ }
+}
+
+func TestMCPValidation(t *testing.T) {
+ for _, tc := range []struct{ name, key, value, yaml string }{
+ {"zero port", "PORT", "0", "{}"}, {"negative port", "PORT", "-1", "{}"}, {"large port", "PORT", "65536", "{}"}, {"bad port", "PORT", "bad", "{}"}, {"empty port", "PORT", "", "{}"},
+ {"bad mode", "LAUNCH_MODE", "bogus", "{}"}, {"empty mode", "LAUNCH_MODE", "", "{}"}, {"enabled key missing", "ENABLED", "true", "{}"},
+ {"empty key overrides YAML", "HOST_API_KEY", "", "mcp: {enabled: true, host_api_key: file-key}"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ clearMCPEnv(t)
+ t.Setenv("RAGFLOW_MCP_"+tc.key, tc.value)
+ if _, err := parseMCPYAML(t, tc.yaml); err == nil {
+ t.Fatal("invalid configuration accepted")
+ }
+ })
+ }
+ for _, yaml := range []string{"mcp: {port: 0}", "mcp: {port: 3.14}", "mcp: {launch_mode: bogus}", "mcp: {enabled: true}"} {
+ t.Run(yaml, func(t *testing.T) {
+ clearMCPEnv(t)
+ if _, err := parseMCPYAML(t, yaml); err == nil {
+ t.Fatal("invalid YAML configuration accepted")
+ }
+ })
+ }
+ t.Run("host mode needs no fixed key", func(t *testing.T) {
+ clearMCPEnv(t)
+ if _, err := parseMCPYAML(t, "mcp: {enabled: true, launch_mode: host}"); err != nil {
+ t.Fatal(err)
+ }
+ })
+ for _, value := range []string{"false", "0", "no", "off", "invalid", ""} {
+ t.Run("false-"+value, func(t *testing.T) {
+ clearMCPEnv(t)
+ t.Setenv("RAGFLOW_MCP_ENABLED", value)
+ got, err := parseMCPYAML(t, "{}")
+ if err != nil || got.Enabled {
+ t.Fatalf("existing false spelling changed: %+v, %v", got, err)
+ }
+ })
+ }
+}
diff --git a/internal/server/config_getallconfigs_test.go b/internal/server/config_getallconfigs_test.go
index e7e0530e1c..9525682ac6 100644
--- a/internal/server/config_getallconfigs_test.go
+++ b/internal/server/config_getallconfigs_test.go
@@ -17,8 +17,14 @@
package server
import (
+ "fmt"
+ "go.uber.org/zap"
+ "go.uber.org/zap/zapcore"
+ "go.uber.org/zap/zaptest/observer"
"os"
"path/filepath"
+ "ragflow/internal/common"
+ "strings"
"testing"
)
@@ -62,3 +68,44 @@ kvrocks:
t.Fatalf("Kvrocks config not exported in GetAllConfigs: %#v", allConfigs)
}
}
+
+func TestMCPConfigurationDoesNotLogKey(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "service_conf.yaml")
+ const secret = "test-only-mcp-secret"
+ if err := os.WriteFile(path, []byte("mcp: {host_api_key: "+secret+", launch_mode: host}\n"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ oldConfig, oldViper := globalConfig, globalViper
+ oldLogger := common.Logger
+ t.Cleanup(func() { globalConfig, globalViper = oldConfig, oldViper; common.Logger = oldLogger })
+ core, logs := observer.New(zapcore.InfoLevel)
+ common.Logger = zap.New(core)
+ if err := Init(path); err != nil {
+ t.Fatal(err)
+ }
+ if got := GetConfig().GetAPIServerConfig().MCP.HostAPIKey; got != secret {
+ t.Fatal("key was not loaded")
+ }
+ PrintAll()
+ if strings.Contains(fmt.Sprint(logs.All()), secret) {
+ t.Fatal("MCP key leaked to configuration log")
+ }
+ all, err := GetAllConfigs()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(fmt.Sprint(all), secret) {
+ t.Fatal("MCP key exported")
+ }
+ if globalViper.GetString("mcp.host_api_key") != secret {
+ t.Fatal("logging mutated loaded configuration")
+ }
+ t.Setenv("RAGFLOW_MCP_HOST_API_KEY", "different-test-secret")
+ if err := Init(path); err != nil {
+ t.Fatal(err)
+ }
+ PrintAll()
+ if strings.Contains(fmt.Sprint(logs.All()), "different-test-secret") {
+ t.Fatal("environment key leaked")
+ }
+}