Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

server.py 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. #
  2. # Copyright 2025 The InfiniFlow Authors. All Rights Reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. #
  16. import json
  17. from collections.abc import AsyncIterator
  18. from contextlib import asynccontextmanager
  19. import requests
  20. from starlette.applications import Starlette
  21. from starlette.middleware import Middleware
  22. from starlette.middleware.base import BaseHTTPMiddleware
  23. from starlette.responses import JSONResponse
  24. from starlette.routing import Mount, Route
  25. from strenum import StrEnum
  26. import mcp.types as types
  27. from mcp.server.lowlevel import Server
  28. from mcp.server.sse import SseServerTransport
  29. class LaunchMode(StrEnum):
  30. SELF_HOST = "self-host"
  31. HOST = "host"
  32. BASE_URL = "http://127.0.0.1:9380"
  33. HOST = "127.0.0.1"
  34. PORT = "9382"
  35. HOST_API_KEY = ""
  36. MODE = ""
  37. class RAGFlowConnector:
  38. def __init__(self, base_url: str, version="v1"):
  39. self.base_url = base_url
  40. self.version = version
  41. self.api_url = f"{self.base_url}/api/{self.version}"
  42. def bind_api_key(self, api_key: str):
  43. self.api_key = api_key
  44. self.authorization_header = {"Authorization": "{} {}".format("Bearer", self.api_key)}
  45. def _post(self, path, json=None, stream=False, files=None):
  46. if not self.api_key:
  47. return None
  48. res = requests.post(url=self.api_url + path, json=json, headers=self.authorization_header, stream=stream, files=files)
  49. return res
  50. def _get(self, path, params=None, json=None):
  51. res = requests.get(url=self.api_url + path, params=params, headers=self.authorization_header, json=json)
  52. return res
  53. def list_datasets(self, page: int = 1, page_size: int = 1000, orderby: str = "create_time", desc: bool = True, id: str | None = None, name: str | None = None):
  54. res = self._get("/datasets", {"page": page, "page_size": page_size, "orderby": orderby, "desc": desc, "id": id, "name": name})
  55. if not res:
  56. raise Exception([types.TextContent(type="text", text=res.get("Cannot process this operation."))])
  57. res = res.json()
  58. if res.get("code") == 0:
  59. result_list = []
  60. for data in res["data"]:
  61. d = {"description": data["description"], "id": data["id"]}
  62. result_list.append(json.dumps(d, ensure_ascii=False))
  63. return "\n".join(result_list)
  64. return ""
  65. def retrieval(
  66. self, dataset_ids, document_ids=None, question="", page=1, page_size=30, similarity_threshold=0.2, vector_similarity_weight=0.3, top_k=1024, rerank_id: str | None = None, keyword: bool = False
  67. ):
  68. if document_ids is None:
  69. document_ids = []
  70. data_json = {
  71. "page": page,
  72. "page_size": page_size,
  73. "similarity_threshold": similarity_threshold,
  74. "vector_similarity_weight": vector_similarity_weight,
  75. "top_k": top_k,
  76. "rerank_id": rerank_id,
  77. "keyword": keyword,
  78. "question": question,
  79. "dataset_ids": dataset_ids,
  80. "document_ids": document_ids,
  81. }
  82. # Send a POST request to the backend service (using requests library as an example, actual implementation may vary)
  83. res = self._post("/retrieval", json=data_json)
  84. if not res:
  85. raise Exception([types.TextContent(type="text", text=res.get("Cannot process this operation."))])
  86. res = res.json()
  87. if res.get("code") == 0:
  88. chunks = []
  89. for chunk_data in res["data"].get("chunks"):
  90. chunks.append(json.dumps(chunk_data, ensure_ascii=False))
  91. return [types.TextContent(type="text", text="\n".join(chunks))]
  92. raise Exception([types.TextContent(type="text", text=res.get("message"))])
  93. class RAGFlowCtx:
  94. def __init__(self, connector: RAGFlowConnector):
  95. self.conn = connector
  96. @asynccontextmanager
  97. async def server_lifespan(server: Server) -> AsyncIterator[dict]:
  98. ctx = RAGFlowCtx(RAGFlowConnector(base_url=BASE_URL))
  99. try:
  100. yield {"ragflow_ctx": ctx}
  101. finally:
  102. pass
  103. app = Server("ragflow-server", lifespan=server_lifespan)
  104. sse = SseServerTransport("/messages/")
  105. @app.list_tools()
  106. async def list_tools() -> list[types.Tool]:
  107. ctx = app.request_context
  108. ragflow_ctx = ctx.lifespan_context["ragflow_ctx"]
  109. if not ragflow_ctx:
  110. raise ValueError("Get RAGFlow Context failed")
  111. connector = ragflow_ctx.conn
  112. if MODE == LaunchMode.HOST:
  113. api_key = ctx.session._init_options.capabilities.experimental["headers"]["api_key"]
  114. if not api_key:
  115. raise ValueError("RAGFlow API_KEY is required.")
  116. else:
  117. api_key = HOST_API_KEY
  118. connector.bind_api_key(api_key)
  119. dataset_description = connector.list_datasets()
  120. return [
  121. types.Tool(
  122. name="ragflow_retrieval",
  123. description="Retrieve relevant chunks from the RAGFlow retrieve interface based on the question, using the specified dataset_ids and optionally document_ids. Below is the list of all available datasets, including their descriptions and IDs. If you're unsure which datasets are relevant to the question, simply pass all dataset IDs to the function."
  124. + dataset_description,
  125. inputSchema={
  126. "type": "object",
  127. "properties": {"dataset_ids": {"type": "array", "items": {"type": "string"}}, "document_ids": {"type": "array", "items": {"type": "string"}}, "question": {"type": "string"}},
  128. "required": ["dataset_ids", "question"],
  129. },
  130. ),
  131. ]
  132. @app.call_tool()
  133. async def call_tool(name: str, arguments: dict) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
  134. ctx = app.request_context
  135. ragflow_ctx = ctx.lifespan_context["ragflow_ctx"]
  136. if not ragflow_ctx:
  137. raise ValueError("Get RAGFlow Context failed")
  138. connector = ragflow_ctx.conn
  139. if MODE == LaunchMode.HOST:
  140. api_key = ctx.session._init_options.capabilities.experimental["headers"]["api_key"]
  141. if not api_key:
  142. raise ValueError("RAGFlow API_KEY is required.")
  143. else:
  144. api_key = HOST_API_KEY
  145. connector.bind_api_key(api_key)
  146. if name == "ragflow_retrieval":
  147. document_ids = arguments.get("document_ids", [])
  148. return connector.retrieval(dataset_ids=arguments["dataset_ids"], document_ids=document_ids, question=arguments["question"])
  149. raise ValueError(f"Tool not found: {name}")
  150. async def handle_sse(request):
  151. async with sse.connect_sse(request.scope, request.receive, request._send) as streams:
  152. await app.run(streams[0], streams[1], app.create_initialization_options(experimental_capabilities={"headers": dict(request.headers)}))
  153. class AuthMiddleware(BaseHTTPMiddleware):
  154. async def dispatch(self, request, call_next):
  155. if request.url.path.startswith("/sse") or request.url.path.startswith("/messages"):
  156. api_key = request.headers.get("api_key")
  157. if not api_key:
  158. return JSONResponse({"error": "Missing unauthorization header"}, status_code=401)
  159. return await call_next(request)
  160. middleware = None
  161. if MODE == LaunchMode.HOST:
  162. middleware = [Middleware(AuthMiddleware)]
  163. starlette_app = Starlette(
  164. debug=True,
  165. routes=[
  166. Route("/sse", endpoint=handle_sse),
  167. Mount("/messages/", app=sse.handle_post_message),
  168. ],
  169. middleware=middleware,
  170. )
  171. if __name__ == "__main__":
  172. """
  173. Launch example:
  174. self-host:
  175. uv run mcp/server/server.py --host=127.0.0.1 --port=9382 --base_url=http://127.0.0.1:9380 --mode=self-host --api_key=ragflow-xxxxx
  176. host:
  177. uv run mcp/server/server.py --host=127.0.0.1 --port=9382 --base_url=http://127.0.0.1:9380 --mode=host
  178. """
  179. import argparse
  180. import os
  181. import uvicorn
  182. from dotenv import load_dotenv
  183. load_dotenv()
  184. parser = argparse.ArgumentParser(description="RAGFlow MCP Server")
  185. parser.add_argument("--base_url", type=str, default="http://127.0.0.1:9380", help="api_url: http://<host_address>")
  186. parser.add_argument("--host", type=str, default="127.0.0.1", help="RAGFlow MCP SERVER host")
  187. parser.add_argument("--port", type=str, default="9382", help="RAGFlow MCP SERVER port")
  188. parser.add_argument(
  189. "--mode",
  190. type=str,
  191. default="self-host",
  192. help="Launch mode options:\n"
  193. " * self-host: Launches an MCP server to access a specific tenant space. The 'api_key' argument is required.\n"
  194. " * host: Launches an MCP server that allows users to access their own spaces. Each request must include a header "
  195. "indicating the user's identification.",
  196. )
  197. parser.add_argument("--api_key", type=str, default="", help="RAGFlow MCP SERVER HOST API KEY")
  198. args = parser.parse_args()
  199. if args.mode not in ["self-host", "host"]:
  200. parser.error("--mode is only accept 'self-host' or 'host'")
  201. if args.mode == "self-host" and not args.api_key:
  202. parser.error("--api_key is required when --mode is 'self-host'")
  203. BASE_URL = os.environ.get("RAGFLOW_MCP_BASE_URL", args.base_url)
  204. HOST = os.environ.get("RAGFLOW_MCP_HOST", args.host)
  205. PORT = os.environ.get("RAGFLOW_MCP_PORT", args.port)
  206. MODE = os.environ.get("RAGFLOW_MCP_LAUNCH_MODE", args.mode)
  207. HOST_API_KEY = os.environ.get("RAGFLOW_MCP_HOST_API_KEY", args.api_key)
  208. print(
  209. r"""
  210. __ __ ____ ____ ____ _____ ______ _______ ____
  211. | \/ |/ ___| _ \ / ___|| ____| _ \ \ / / ____| _ \
  212. | |\/| | | | |_) | \___ \| _| | |_) \ \ / /| _| | |_) |
  213. | | | | |___| __/ ___) | |___| _ < \ V / | |___| _ <
  214. |_| |_|\____|_| |____/|_____|_| \_\ \_/ |_____|_| \_\
  215. """,
  216. flush=True,
  217. )
  218. print(f"MCP launch mode: {MODE}", flush=True)
  219. print(f"MCP host: {HOST}", flush=True)
  220. print(f"MCP port: {PORT}", flush=True)
  221. print(f"MCP base_url: {BASE_URL}", flush=True)
  222. uvicorn.run(
  223. starlette_app,
  224. host=HOST,
  225. port=int(PORT),
  226. )