Skip to content

armgit / dify

Public Imported from GitHub
0

Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.

fix(api): fall back to first server URL when X-Request-Env is set but servers lack env key (#42025)

Harsh Kashyapda6a1b01d1a3
diff --git a/api/core/tools/utils/parser.py b/api/core/tools/utils/parser.py
index ba2ec214761..1b224c42933 100644
--- a/api/core/tools/utils/parser.py
+++ b/api/core/tools/utils/parser.py
@@ -46,7 +46,7 @@ class ApiBasedToolSchemaParser:
server_url = openapi["servers"][0]["url"]
request_env = request.headers.get("X-Request-Env") if has_request_context() else None
if request_env:
- matched_servers = [server["url"] for server in openapi["servers"] if server["env"] == request_env]
+ matched_servers = [server["url"] for server in openapi["servers"] if server.get("env") == request_env]
server_url = matched_servers[0] if matched_servers else server_url
# list all interfaces
diff --git a/api/tests/unit_tests/core/tools/utils/test_parser.py b/api/tests/unit_tests/core/tools/utils/test_parser.py
index e9822109481..a6cb9294ca2 100644
--- a/api/tests/unit_tests/core/tools/utils/test_parser.py
+++ b/api/tests/unit_tests/core/tools/utils/test_parser.py
@@ -418,3 +418,45 @@ def test_auto_parse_openapi_swagger_then_plugin():
assert bundles == ["plugin-bundle"]
assert schema_type == ApiProviderSchemaType.OPENAI_PLUGIN
+
+
+def _minimal_openapi(servers: list[dict[str, Any]]) -> dict[str, Any]:
+ return {
+ "openapi": "3.0.0",
+ "info": {"title": "Simple API", "version": "1.0.0"},
+ "servers": servers,
+ "paths": {
+ "/": {
+ "get": {
+ "summary": "Root endpoint",
+ "responses": {"200": {"description": "Successful response"}},
+ }
+ }
+ },
+ }
+
+
+def test_parse_openapi_to_tool_bundle_request_env_without_env_key(app: Flask):
+ # A standard OpenAPI schema has no "env" key on its servers. When the
+ # X-Request-Env header is present, parsing must fall back to the first
+ # server URL instead of raising KeyError.
+ openapi = _minimal_openapi([{"url": "http://localhost:3000"}])
+ with app.test_request_context(headers={"X-Request-Env": "prod"}):
+ tool_bundles = ApiBasedToolSchemaParser.parse_openapi_to_tool_bundle(openapi)
+
+ assert len(tool_bundles) == 1
+ assert tool_bundles[0].server_url == "http://localhost:3000/"
+
+
+def test_parse_openapi_to_tool_bundle_request_env_matches_env_key(app: Flask):
+ openapi = _minimal_openapi(
+ [
+ {"url": "http://localhost:3000", "env": "dev"},
+ {"url": "http://prod.example.com", "env": "prod"},
+ ]
+ )
+ with app.test_request_context(headers={"X-Request-Env": "prod"}):
+ tool_bundles = ApiBasedToolSchemaParser.parse_openapi_to_tool_bundle(openapi)
+
+ assert len(tool_bundles) == 1
+ assert tool_bundles[0].server_url == "http://prod.example.com/"