agentengine-sdk-python 0.8.7__py3-none-any.whl → 0.8.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/METADATA +14 -9
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/RECORD +98 -68
- ksadk/__init__.py +2 -1
- ksadk/_build_provenance.json +1 -1
- ksadk/_mcp_compat.py +305 -0
- ksadk/agent.py +29 -0
- ksadk/agui/_agent_kernel.py +176 -142
- ksadk/agui/agent.py +74 -5
- ksadk/agui/hosted.py +343 -0
- ksadk/agui/request_identity.py +11 -0
- ksadk/agui/routes.py +77 -2
- ksadk/builders/code_builder.py +30 -23
- ksadk/builders/container_builder.py +5 -5
- ksadk/builders/mcp_builder.py +142 -0
- ksadk/builders/project_imports.py +66 -0
- ksadk/cli/cmd_mcp.py +1 -1
- ksadk/cli/cmd_run.py +2 -4
- ksadk/cli/cmd_web.py +8 -0
- ksadk/cli/runtime_bootstrap.py +4 -1
- ksadk/common/cloud_headers.py +33 -6
- ksadk/compat/adk_compat.py +2 -0
- ksadk/compat/adk_stream.py +35 -0
- ksadk/configs/env_registry.py +31 -0
- ksadk/conversations/projector.py +6 -0
- ksadk/conversations/runtime_observability.py +1 -0
- ksadk/detection/mcp_detector.py +80 -22
- ksadk/harness/__init__.py +3 -0
- ksadk/harness/service_presentation.py +44 -0
- ksadk/harness/service_runtime.py +1038 -0
- ksadk/interaction/providers/harness.py +9 -4
- ksadk/kernel/ingress.py +35 -25
- ksadk/kernel/worker.py +2 -2
- ksadk/kernel/worker_identity.py +15 -8
- ksadk/knowledge_base/client.py +10 -3
- ksadk/mcp_runtime/oauth/_agent.py +77 -9
- ksadk/mcp_runtime/oauth/langgraph.py +47 -15
- ksadk/mcp_runtime/oauth/local/broker.py +23 -1
- ksadk/mcp_runtime/oauth/tools.py +46 -8
- ksadk/mcp_runtime/oauth/transport.py +19 -2
- ksadk/memory/adk/backends/sdk_ltm_backend.py +21 -12
- ksadk/memory/scope_ids.py +49 -0
- ksadk/plugins/providers/harness.py +65 -28
- ksadk/plugins/providers/harness_service.py +198 -0
- ksadk/plugins/providers/harness_service_context.py +175 -0
- ksadk/plugins/providers/harness_service_hooks.py +168 -0
- ksadk/plugins/providers/harness_service_memory.py +479 -0
- ksadk/plugins/providers/platform_resources.py +2 -2
- ksadk/resource_runtime/langgraph.py +7 -3
- ksadk/resource_runtime/mcp_server.py +3 -3
- ksadk/resource_runtime/worker.py +19 -4
- ksadk/runners/_adk_canonical_stream.py +38 -10
- ksadk/runners/_adk_tunnel_history.py +96 -0
- ksadk/runners/_langgraph_canonical_stream.py +16 -0
- ksadk/runners/_langgraph_factory.py +79 -0
- ksadk/runners/_langgraph_runner_streams.py +6 -0
- ksadk/runners/_session_identity.py +8 -3
- ksadk/runners/adk_runner.py +95 -19
- ksadk/runners/langgraph_runner.py +15 -21
- ksadk/runtime/factory.py +17 -5
- ksadk/runtime/framework_adapters.py +10 -0
- ksadk/runtime/langgraph_checkpoint_view.py +28 -7
- ksadk/runtime/launch.py +2 -0
- ksadk/server/factory.py +55 -0
- ksadk/server/routes/common.py +2 -0
- ksadk/server/routes/harness_service_view.py +38 -0
- ksadk/server/routes/ui_bootstrap.py +16 -2
- ksadk/skills/mcp_server/server.py +239 -217
- ksadk/studio/contracts.py +8 -0
- ksadk/studio/mcp_runtime.py +23 -8
- ksadk/studio/native_mcp_disclosure.py +8 -6
- ksadk/studio/native_mcp_tool_port.py +3 -1
- ksadk/studio/native_memory_context.py +10 -8
- ksadk/studio/native_product.py +3 -4
- ksadk/studio/plugin_composition.py +8 -1
- ksadk/studio/plugin_native_activation.py +4 -2
- ksadk/studio/plugin_runtime.py +9 -0
- ksadk/studio/service.py +2 -0
- ksadk/tracing/setup.py +53 -3
- ksadk/tunnel/__init__.py +37 -0
- ksadk/tunnel/connector.py +384 -0
- ksadk/tunnel/discovery.py +107 -0
- ksadk/tunnel/failure.py +168 -0
- ksadk/tunnel/http_tools.py +100 -0
- ksadk/tunnel/langgraph.py +125 -0
- ksadk/tunnel/middleware.py +28 -0
- ksadk/tunnel/peers.py +872 -0
- ksadk/tunnel/protocol.py +97 -0
- ksadk/tunnel/registry.py +306 -0
- ksadk/tunnel/runtime.py +147 -0
- ksadk/tunnel/server.py +201 -0
- ksadk/tunnel/services.py +366 -0
- ksadk/tunnel/toolset.py +78 -0
- ksadk/version.py +1 -1
- ksadk_runtime_common/memory_backend/providers/mem0.py +20 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/WHEEL +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/entry_points.txt +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/licenses/LICENSE +0 -0
- {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/top_level.txt +0 -0
ksadk/builders/mcp_builder.py
CHANGED
|
@@ -6,9 +6,13 @@ MCP Builders - FastMCP 代码打包 / 容器构建
|
|
|
6
6
|
- Container 模式: 复用现有 Docker 登录/推送逻辑,但检测/打包走 FastMCP 专属链路
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
|
+
import json
|
|
9
10
|
import os
|
|
10
11
|
import shutil
|
|
11
12
|
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
from dataclasses import replace
|
|
12
16
|
from pathlib import Path
|
|
13
17
|
from typing import List, Optional
|
|
14
18
|
|
|
@@ -73,6 +77,8 @@ class MCPCodeBuilder(CodeBuilder):
|
|
|
73
77
|
self._save_input_fingerprint(zip_path, detection_result)
|
|
74
78
|
zip_size = zip_path.stat().st_size / (1024 * 1024)
|
|
75
79
|
click.secho(f"\n✅ 使用已有构建: {zip_path.name} ({zip_size:.2f} MB)", fg="green")
|
|
80
|
+
# 缓存命中也要探一次——AST 结果可能不准,而工具列表要进平台元数据
|
|
81
|
+
detection_result = self._resolve_tools(detection_result)
|
|
76
82
|
return BuildResult(
|
|
77
83
|
success=True,
|
|
78
84
|
artifact_path=zip_path,
|
|
@@ -99,6 +105,9 @@ class MCPCodeBuilder(CodeBuilder):
|
|
|
99
105
|
if not self._install_dependencies(requirements_path):
|
|
100
106
|
return BuildResult(success=False, error_message="依赖安装失败")
|
|
101
107
|
|
|
108
|
+
# 依赖装完后用**运行时真值**覆盖 AST 猜测(工厂函数注册的工具 AST 扫不到)
|
|
109
|
+
detection_result = self._resolve_tools(detection_result)
|
|
110
|
+
|
|
102
111
|
# Step 3: 打包
|
|
103
112
|
click.echo("\n📦 Step 3/3: 打包 zip...")
|
|
104
113
|
self._package_mcp_zip(zip_path, detection_result)
|
|
@@ -120,6 +129,139 @@ class MCPCodeBuilder(CodeBuilder):
|
|
|
120
129
|
},
|
|
121
130
|
)
|
|
122
131
|
|
|
132
|
+
# 工具探测超时(秒)。导入项目 + 加载 catalog 通常 <5s,60s 足够宽松。
|
|
133
|
+
TOOL_PROBE_TIMEOUT = 60.0
|
|
134
|
+
|
|
135
|
+
def _find_probe_python(self) -> Path | None:
|
|
136
|
+
"""找一个**能 import 项目依赖**的 Python 解释器。
|
|
137
|
+
|
|
138
|
+
## 为什么不能直接用 `sys.executable`
|
|
139
|
+
|
|
140
|
+
构建机上的 ksadk 环境**未必装了项目依赖**,而且版本可能不兼容。
|
|
141
|
+
实测(2026-11-18):ksadk venv 的 fastmcp 版本过旧,import 项目直接报
|
|
142
|
+
`No module named 'fastmcp.server.transforms'`。
|
|
143
|
+
|
|
144
|
+
## 为什么不能用 `deps_dir`
|
|
145
|
+
|
|
146
|
+
`_install_dependencies()` 装的是**目标平台**的 wheel(Linux manylinux),
|
|
147
|
+
在 macOS 构建机上 import 不了。所以只能找**开发者本地环境**。
|
|
148
|
+
|
|
149
|
+
优先级:`<project>/.venv` → `venv` → `env` → `sys.executable`(最后兜底)。
|
|
150
|
+
"""
|
|
151
|
+
for name in (".venv", "venv", "env"):
|
|
152
|
+
candidate = self.project_dir / name / "bin" / "python"
|
|
153
|
+
if candidate.is_file():
|
|
154
|
+
return candidate
|
|
155
|
+
# Windows
|
|
156
|
+
win = self.project_dir / name / "Scripts" / "python.exe"
|
|
157
|
+
if win.is_file():
|
|
158
|
+
return win
|
|
159
|
+
return Path(sys.executable) if sys.executable else None
|
|
160
|
+
|
|
161
|
+
def _probe_tools_runtime(self, detection_result: MCPDetectionResult) -> list[str] | None:
|
|
162
|
+
"""**真调** `list_tools()` 拿工具列表,而不是 AST 猜。
|
|
163
|
+
|
|
164
|
+
## 为什么需要
|
|
165
|
+
|
|
166
|
+
`MCPDetector._extract_tools()` 用 AST 扫入口文件的 `@mcp.tool` 装饰器。
|
|
167
|
+
但只要项目用**工厂函数**注册工具就扫不到:
|
|
168
|
+
|
|
169
|
+
```python
|
|
170
|
+
# mcp_server.py
|
|
171
|
+
from ezone_mcp.server import create_server
|
|
172
|
+
mcp = create_server() # ← 没有装饰器,AST 返回 []
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
后果(2026-11-18 云端实测):`build-metadata.json` 的 `tools` 恒为 `[]`,
|
|
176
|
+
平台「工具」tab 空白,`ksadk mcp status` 显示 `tools: []`。
|
|
177
|
+
|
|
178
|
+
**`list_tools()` 是事实,AST 是猜测。**
|
|
179
|
+
|
|
180
|
+
## 实现
|
|
181
|
+
|
|
182
|
+
起一个**子进程**(避免污染构建进程的 import 缓存),把结果写进临时文件
|
|
183
|
+
(避免 stdout 被日志污染),任何失败都返回 `None` 让调用方回退 AST。
|
|
184
|
+
|
|
185
|
+
Returns:
|
|
186
|
+
工具名列表;探测失败返回 ``None``。
|
|
187
|
+
"""
|
|
188
|
+
python = self._find_probe_python()
|
|
189
|
+
if python is None:
|
|
190
|
+
return None
|
|
191
|
+
|
|
192
|
+
module = detection_result.entry_point.replace("/", ".").replace("\\", ".")
|
|
193
|
+
if module.endswith(".py"):
|
|
194
|
+
module = module[:-3]
|
|
195
|
+
variable = detection_result.mcp_variable or "mcp"
|
|
196
|
+
|
|
197
|
+
with tempfile.TemporaryDirectory(prefix="ksadk-probe-") as tmp:
|
|
198
|
+
out_file = Path(tmp) / "tools.json"
|
|
199
|
+
# 工具枚举 API 在 fastmcp 各大版本间**变过名字**:
|
|
200
|
+
# - fastmcp 4.x / mcp 2.x : `await mcp.list_tools() -> list[Tool]`
|
|
201
|
+
# - fastmcp 2.x : `await mcp.get_tools() -> dict[str, Tool]`
|
|
202
|
+
# 统一在子进程里试两条,任一成功即可。
|
|
203
|
+
script = (
|
|
204
|
+
"import asyncio, json, sys\n"
|
|
205
|
+
"out, root, module, variable = sys.argv[1:5]\n"
|
|
206
|
+
"sys.path.insert(0, root)\n"
|
|
207
|
+
"import importlib\n"
|
|
208
|
+
f"mcp = getattr(importlib.import_module(module), variable)\n"
|
|
209
|
+
"def _names():\n"
|
|
210
|
+
" lister = getattr(mcp, 'list_tools', None)\n"
|
|
211
|
+
" if lister is not None:\n"
|
|
212
|
+
" return [getattr(t, 'name', None) for t in asyncio.run(lister())]\n"
|
|
213
|
+
" getter = getattr(mcp, 'get_tools', None)\n"
|
|
214
|
+
" if getter is None:\n"
|
|
215
|
+
" raise AttributeError('MCP 实例既没有 list_tools 也没有 get_tools')\n"
|
|
216
|
+
" found = asyncio.run(getter())\n"
|
|
217
|
+
" return list(found) if isinstance(found, dict) else [getattr(t, 'name', None) for t in found]\n"
|
|
218
|
+
"json.dump([n for n in _names() if n], open(out, 'w', encoding='utf-8'))\n"
|
|
219
|
+
)
|
|
220
|
+
env = {**os.environ, "PYTHONPATH": str(self.project_dir)}
|
|
221
|
+
try:
|
|
222
|
+
completed = subprocess.run(
|
|
223
|
+
[str(python), "-c", script, str(out_file), str(self.project_dir),
|
|
224
|
+
module, variable],
|
|
225
|
+
cwd=str(self.project_dir),
|
|
226
|
+
capture_output=True,
|
|
227
|
+
text=True,
|
|
228
|
+
timeout=self.TOOL_PROBE_TIMEOUT,
|
|
229
|
+
env=env,
|
|
230
|
+
check=False,
|
|
231
|
+
)
|
|
232
|
+
except (OSError, subprocess.SubprocessError) as exc:
|
|
233
|
+
click.secho(f" ⚠️ 工具探测失败({type(exc).__name__}),回退 AST 结果", fg="yellow")
|
|
234
|
+
return None
|
|
235
|
+
|
|
236
|
+
if completed.returncode != 0 or not out_file.is_file():
|
|
237
|
+
detail = (completed.stderr or "").strip().splitlines()
|
|
238
|
+
hint = detail[-1] if detail else f"exit={completed.returncode}"
|
|
239
|
+
click.secho(f" ⚠️ 工具探测失败({hint}),回退 AST 结果", fg="yellow")
|
|
240
|
+
return None
|
|
241
|
+
|
|
242
|
+
try:
|
|
243
|
+
tools = json.loads(out_file.read_text(encoding="utf-8"))
|
|
244
|
+
except (OSError, json.JSONDecodeError):
|
|
245
|
+
return None
|
|
246
|
+
|
|
247
|
+
if not isinstance(tools, list):
|
|
248
|
+
return None
|
|
249
|
+
return [str(name) for name in tools]
|
|
250
|
+
|
|
251
|
+
def _resolve_tools(self, detection_result: MCPDetectionResult) -> MCPDetectionResult:
|
|
252
|
+
"""用运行时真值覆盖 AST 结果(探测失败则原样返回)。"""
|
|
253
|
+
probed = self._probe_tools_runtime(detection_result)
|
|
254
|
+
if probed is None:
|
|
255
|
+
return detection_result
|
|
256
|
+
if probed == list(detection_result.tools):
|
|
257
|
+
return detection_result
|
|
258
|
+
click.echo(
|
|
259
|
+
f" 工具: 运行时探测到 {len(probed)} 个"
|
|
260
|
+
+ (f"(AST 只扫到 {len(detection_result.tools)} 个)" if detection_result.tools else
|
|
261
|
+
"(AST 扫不到动态注册的工具)")
|
|
262
|
+
)
|
|
263
|
+
return replace(detection_result, tools=probed)
|
|
264
|
+
|
|
123
265
|
def _prepare_mcp_requirements(self, detection_result: MCPDetectionResult) -> Path:
|
|
124
266
|
"""准备 MCP 依赖"""
|
|
125
267
|
base_deps = self._get_mcp_base_requirements()
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Detect optional runtime dependencies without importing user code."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _parse(path: Path) -> ast.Module | None:
|
|
8
|
+
try:
|
|
9
|
+
return ast.parse(path.read_text(encoding="utf-8-sig"), filename=str(path))
|
|
10
|
+
except (OSError, SyntaxError, UnicodeDecodeError):
|
|
11
|
+
return None
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def imports_any(path: Path, module_names: set[str]) -> bool:
|
|
15
|
+
tree = _parse(path)
|
|
16
|
+
if tree is None:
|
|
17
|
+
return False
|
|
18
|
+
for node in ast.walk(tree):
|
|
19
|
+
if isinstance(node, ast.Import):
|
|
20
|
+
names = [alias.name for alias in node.names]
|
|
21
|
+
elif isinstance(node, ast.ImportFrom) and node.module:
|
|
22
|
+
names = [node.module, *(f"{node.module}.{alias.name}" for alias in node.names)]
|
|
23
|
+
else:
|
|
24
|
+
continue
|
|
25
|
+
if any(n == target or n.startswith(target + ".") for n in names for target in module_names):
|
|
26
|
+
return True
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def uses_tunnel(path: Path) -> bool:
|
|
31
|
+
tree = _parse(path)
|
|
32
|
+
if tree is None:
|
|
33
|
+
return False
|
|
34
|
+
|
|
35
|
+
factories = set()
|
|
36
|
+
for node in ast.walk(tree):
|
|
37
|
+
if isinstance(node, ast.Import):
|
|
38
|
+
names = [(a.name, a.asname or a.name) for a in node.names]
|
|
39
|
+
elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
|
|
40
|
+
names = [(f"{node.module}.{a.name}", a.asname or a.name) for a in node.names]
|
|
41
|
+
else:
|
|
42
|
+
continue
|
|
43
|
+
for name, local in names:
|
|
44
|
+
if name == "ksadk.tunnel" or name.startswith("ksadk.tunnel."):
|
|
45
|
+
return True
|
|
46
|
+
if name in {"ksadk.Agent", "ksadk.agent.Agent"}:
|
|
47
|
+
factories.add(local)
|
|
48
|
+
elif name in {"ksadk", "ksadk.agent"}:
|
|
49
|
+
factories.add(f"{local}.Agent")
|
|
50
|
+
if name == "ksadk":
|
|
51
|
+
factories.add(f"{local}.agent.Agent")
|
|
52
|
+
|
|
53
|
+
if not factories:
|
|
54
|
+
return False
|
|
55
|
+
for node in ast.walk(tree):
|
|
56
|
+
if not isinstance(node, ast.Call) or not isinstance(node.func, (ast.Name, ast.Attribute)):
|
|
57
|
+
continue
|
|
58
|
+
if ast.unparse(node.func) not in factories:
|
|
59
|
+
continue
|
|
60
|
+
for kw in node.keywords:
|
|
61
|
+
if kw.arg is None: # **options may enable the tunnel at runtime.
|
|
62
|
+
return True
|
|
63
|
+
if kw.arg == "enable_tunnel":
|
|
64
|
+
if not isinstance(kw.value, ast.Constant) or kw.value.value is not False:
|
|
65
|
+
return True
|
|
66
|
+
return False
|
ksadk/cli/cmd_mcp.py
CHANGED
ksadk/cli/cmd_run.py
CHANGED
|
@@ -181,10 +181,8 @@ def _run_custom(
|
|
|
181
181
|
"""Run one detected project through the canonical RuntimeAdapter composition."""
|
|
182
182
|
|
|
183
183
|
# 初始化 Tracing
|
|
184
|
-
if not no_trace:
|
|
184
|
+
if not no_trace and os.getenv("OTEL_SDK_DISABLED", "").strip().lower() != "true":
|
|
185
185
|
try:
|
|
186
|
-
import os
|
|
187
|
-
|
|
188
186
|
from ksadk.tracing import setup_tracing
|
|
189
187
|
|
|
190
188
|
has_otlp = bool(
|
|
@@ -212,7 +210,7 @@ def _run_custom(
|
|
|
212
210
|
raise SystemExit(2)
|
|
213
211
|
|
|
214
212
|
try:
|
|
215
|
-
runtime_app = create_runtime_web_app(result, agent_path)
|
|
213
|
+
runtime_app = create_runtime_web_app(result, agent_path, auto_tracing=not no_trace)
|
|
216
214
|
except Exception as e:
|
|
217
215
|
print_exception("RuntimeAdapter 初始化失败", e)
|
|
218
216
|
raise SystemExit(1)
|
ksadk/cli/cmd_web.py
CHANGED
|
@@ -251,6 +251,14 @@ def web(agent_dir: str, port: int, host: str, model: str, no_open: bool):
|
|
|
251
251
|
|
|
252
252
|
setup_environment(agent_path)
|
|
253
253
|
|
|
254
|
+
# 托管 Code 包直接启动 web,必须在加载 Agent 前初始化采集与上报。
|
|
255
|
+
try:
|
|
256
|
+
from ksadk.tracing import setup_tracing
|
|
257
|
+
|
|
258
|
+
setup_tracing()
|
|
259
|
+
except Exception as e:
|
|
260
|
+
print_warn(f"Tracing 初始化失败: {e}")
|
|
261
|
+
|
|
254
262
|
# 检测框架
|
|
255
263
|
detector = FrameworkDetector(str(agent_path))
|
|
256
264
|
result = detector.detect()
|
ksadk/cli/runtime_bootstrap.py
CHANGED
|
@@ -33,7 +33,9 @@ def _managed_a2a_card() -> Any:
|
|
|
33
33
|
return build_managed_a2a_card_if_configured()
|
|
34
34
|
|
|
35
35
|
|
|
36
|
-
def create_runtime_web_app(
|
|
36
|
+
def create_runtime_web_app(
|
|
37
|
+
detection: Any, agent_path: Path, *, auto_tracing: bool = True,
|
|
38
|
+
) -> FastAPI:
|
|
37
39
|
"""Compose one detected project around the canonical RuntimeExecutor."""
|
|
38
40
|
|
|
39
41
|
config = dict(getattr(detection, "raw_config", None) or {})
|
|
@@ -88,6 +90,7 @@ def create_runtime_web_app(detection: Any, agent_path: Path) -> FastAPI:
|
|
|
88
90
|
a2a=managed_a2a,
|
|
89
91
|
a2a_runtime_adapter=adapter,
|
|
90
92
|
local_mcp_oauth=not managed_runtime,
|
|
93
|
+
auto_tracing=auto_tracing,
|
|
91
94
|
),
|
|
92
95
|
configure_runtime_app,
|
|
93
96
|
)
|
ksadk/common/cloud_headers.py
CHANGED
|
@@ -7,6 +7,7 @@ from collections.abc import Mapping
|
|
|
7
7
|
|
|
8
8
|
DEFAULT_TRAFFIC_SOURCE = "agentkit"
|
|
9
9
|
TRAFFIC_SOURCE_HEADER = "X-Traffic-Source"
|
|
10
|
+
COMPONENT_ENV_VAR = "KSADK_COMPONENT_ENV"
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
def resolve_traffic_source(value: str | None = None) -> str:
|
|
@@ -19,18 +20,44 @@ def resolve_traffic_source(value: str | None = None) -> str:
|
|
|
19
20
|
return value.strip() or DEFAULT_TRAFFIC_SOURCE
|
|
20
21
|
|
|
21
22
|
|
|
23
|
+
def resolve_component_env() -> str:
|
|
24
|
+
"""Resolve KSADK_COMPONENT_ENV for knowledge and memory routing."""
|
|
25
|
+
return str(os.getenv(COMPONENT_ENV_VAR, "") or "").strip()
|
|
26
|
+
|
|
27
|
+
|
|
22
28
|
def build_cloud_headers(
|
|
23
29
|
headers: Mapping[str, str] | None = None, *, traffic_source: str | None = None
|
|
24
30
|
) -> dict[str, str]:
|
|
25
|
-
"""Copy headers and set
|
|
31
|
+
"""Copy headers and set canonical source attribution before request signing.
|
|
26
32
|
|
|
27
33
|
Source attribution is owned by KSADK_TRAFFIC_SOURCE (or an explicit worker
|
|
28
34
|
snapshot), including when a caller supplies differently cased extra headers.
|
|
29
35
|
"""
|
|
30
|
-
result = {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
if
|
|
34
|
-
|
|
36
|
+
result: dict[str, str] = {}
|
|
37
|
+
for name, value in (headers or {}).items():
|
|
38
|
+
lower = name.lower()
|
|
39
|
+
if lower == TRAFFIC_SOURCE_HEADER.lower():
|
|
40
|
+
continue
|
|
41
|
+
result[name] = value
|
|
42
|
+
|
|
35
43
|
result[TRAFFIC_SOURCE_HEADER] = resolve_traffic_source(traffic_source)
|
|
44
|
+
|
|
45
|
+
return result
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def build_component_headers(
|
|
49
|
+
headers: Mapping[str, str] | None = None,
|
|
50
|
+
*,
|
|
51
|
+
component_env: str,
|
|
52
|
+
traffic_source: str | None = None,
|
|
53
|
+
) -> dict[str, str]:
|
|
54
|
+
"""Add the preproduction route only for knowledge and memory clients."""
|
|
55
|
+
result = build_cloud_headers(headers, traffic_source=traffic_source)
|
|
56
|
+
if component_env.strip().lower() == "pre":
|
|
57
|
+
result = {
|
|
58
|
+
name: value
|
|
59
|
+
for name, value in result.items()
|
|
60
|
+
if name.lower() != "x-ksc-custom-source"
|
|
61
|
+
}
|
|
62
|
+
result["X-KSC-CUSTOM-SOURCE"] = "pre"
|
|
36
63
|
return result
|
ksadk/compat/adk_compat.py
CHANGED
|
@@ -81,6 +81,8 @@ _LAZY_SYMBOLS: dict[str, str] = {
|
|
|
81
81
|
"ListSessionsResponse": "google.adk.sessions.base_session_service",
|
|
82
82
|
# tools
|
|
83
83
|
"FunctionTool": "google.adk.tools",
|
|
84
|
+
"BaseTool": "google.adk.tools.base_tool",
|
|
85
|
+
"BaseToolset": "google.adk.tools.base_toolset",
|
|
84
86
|
"load_memory": "google.adk.tools",
|
|
85
87
|
"McpTool": "google.adk.tools.mcp_tool.mcp_tool",
|
|
86
88
|
"McpToolset": "google.adk.tools.mcp_tool.mcp_toolset",
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"""Compatibility with LiteLLM function calls whose type is empty."""
|
|
2
|
+
|
|
3
|
+
from functools import wraps
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def normalize_tool_call_types(message):
|
|
7
|
+
calls = (
|
|
8
|
+
message.get("tool_calls")
|
|
9
|
+
if isinstance(message, dict)
|
|
10
|
+
else getattr(message, "tool_calls", None)
|
|
11
|
+
)
|
|
12
|
+
for call in calls or ():
|
|
13
|
+
if isinstance(call, dict):
|
|
14
|
+
if call.get("type") in (None, "") and call.get("function") is not None:
|
|
15
|
+
call["type"] = "function"
|
|
16
|
+
elif (
|
|
17
|
+
getattr(call, "type", None) in (None, "")
|
|
18
|
+
and getattr(call, "function", None) is not None
|
|
19
|
+
):
|
|
20
|
+
call.type = "function"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def normalize_tool_delta_types(module):
|
|
24
|
+
convert = getattr(module, "_model_response_to_chunk", None)
|
|
25
|
+
if convert is None or getattr(convert, "_ksadk_tool_delta_types", False):
|
|
26
|
+
return
|
|
27
|
+
|
|
28
|
+
@wraps(convert)
|
|
29
|
+
def convert_stream_chunk(response, *args, **kwargs):
|
|
30
|
+
for choice in response.get("choices") or ():
|
|
31
|
+
normalize_tool_call_types(choice.get("delta") or choice.get("message"))
|
|
32
|
+
yield from convert(response, *args, **kwargs)
|
|
33
|
+
|
|
34
|
+
convert_stream_chunk._ksadk_tool_delta_types = True
|
|
35
|
+
module._model_response_to_chunk = convert_stream_chunk
|
ksadk/configs/env_registry.py
CHANGED
|
@@ -6,6 +6,18 @@ from ksadk.configs.env_registry_studio import STUDIO_ENV_VAR_REGISTRY_ITEMS
|
|
|
6
6
|
from ksadk.configs.env_var_spec import EnvVarSpec
|
|
7
7
|
|
|
8
8
|
_ENV_VAR_REGISTRY_ITEMS: tuple[EnvVarSpec, ...] = (
|
|
9
|
+
EnvVarSpec(
|
|
10
|
+
"KSADK_COMPONENT_ENV",
|
|
11
|
+
"cloud",
|
|
12
|
+
"Opt-in knowledge and Memory component routing; pre adds X-KSC-CUSTOM-SOURCE before signing.",
|
|
13
|
+
"",
|
|
14
|
+
),
|
|
15
|
+
EnvVarSpec("KSADK_CHAT_PREFERRED_TRANSPORT", "agui", "Preferred available chat transport: ag-ui or responses; existing endpoints remain available."),
|
|
16
|
+
EnvVarSpec("KSADK_HARNESS_SERVICE_URL", "harness", "Opt-in external Harness service base URL."),
|
|
17
|
+
EnvVarSpec("KSADK_HARNESS_SERVICE_TOKEN", "harness", "External Harness service access credential.", sensitive=True),
|
|
18
|
+
EnvVarSpec("KSADK_HARNESS_SERVICE_WORKSPACE", "harness", "Existing absolute local workspace mount for the Harness service adapter."),
|
|
19
|
+
EnvVarSpec("KSADK_HARNESS_SERVICE_CA_FILE", "harness", "CA file used to verify the Harness service TLS certificate."),
|
|
20
|
+
EnvVarSpec("KSADK_HARNESS_SERVICE_DURABLE_APPROVALS", "harness", "Enable the external service durable approval contract only when supported.", "0"),
|
|
9
21
|
EnvVarSpec(
|
|
10
22
|
"KSADK_TRAFFIC_SOURCE",
|
|
11
23
|
"cloud",
|
|
@@ -483,6 +495,25 @@ _ENV_VAR_REGISTRY_ITEMS: tuple[EnvVarSpec, ...] = (
|
|
|
483
495
|
EnvVarSpec(
|
|
484
496
|
"KSADK_MCP_SERVERS", "mcp_runtime", "JSON array of MCP server configs.", sensitive=True
|
|
485
497
|
),
|
|
498
|
+
EnvVarSpec(
|
|
499
|
+
"KSADK_TUNNEL_PEER_SECRET",
|
|
500
|
+
"mcp_runtime",
|
|
501
|
+
"Optional peer HMAC secret override, at least 32 bytes; otherwise derived from "
|
|
502
|
+
"the declared tunnel token and runtime ID.",
|
|
503
|
+
sensitive=True,
|
|
504
|
+
),
|
|
505
|
+
EnvVarSpec(
|
|
506
|
+
"KSADK_TUNNEL_PEER_SERVICE",
|
|
507
|
+
"mcp_runtime",
|
|
508
|
+
"Headless service for tunnel peer discovery; defaults to the runtime ID plus -headless.",
|
|
509
|
+
),
|
|
510
|
+
EnvVarSpec(
|
|
511
|
+
"KSADK_TUNNEL_PEER_PORT",
|
|
512
|
+
"mcp_runtime",
|
|
513
|
+
"Internal peer WebSocket listener port.",
|
|
514
|
+
"8092",
|
|
515
|
+
),
|
|
516
|
+
EnvVarSpec("KSADK_TUNNEL_TOKEN", "mcp_runtime", "Required application token for tool tunnel registration.", sensitive=True),
|
|
486
517
|
EnvVarSpec(
|
|
487
518
|
"KSADK_MCP_OAUTH_PROJECTION",
|
|
488
519
|
"configs",
|
ksadk/conversations/projector.py
CHANGED
|
@@ -36,6 +36,7 @@ from ksadk.events.content import (
|
|
|
36
36
|
ToolResultContent,
|
|
37
37
|
)
|
|
38
38
|
from ksadk.events.usage import usage_mode
|
|
39
|
+
from ksadk.harness.service_presentation import engine_presentation, engine_view_hash
|
|
39
40
|
from ksadk.kernel.contracts import SessionEventEnvelope
|
|
40
41
|
|
|
41
42
|
_INTERACTION_EVENT_TYPES = frozenset(
|
|
@@ -334,6 +335,11 @@ def project_conversation_item(
|
|
|
334
335
|
if isinstance(event, (RunCompleted, RunFailed, RunCanceled, RunInterrupted)):
|
|
335
336
|
payload.update(_run_outcome_payload(event.source.metadata))
|
|
336
337
|
payload.update(public_item_presentation(event, kind))
|
|
338
|
+
engine_view = event.source.metadata.get("harness_service_presentation")
|
|
339
|
+
if event.source.framework == "ksadk" and isinstance(engine_view, dict):
|
|
340
|
+
presentation = engine_presentation(engine_view_hash(engine_view), engine_view.get("event"))
|
|
341
|
+
if presentation:
|
|
342
|
+
payload["harnessView"] = presentation
|
|
337
343
|
if kind == "tool_call" and event.source.metadata.get("engine_kind") == "native":
|
|
338
344
|
# Native public results contain a sealed execution status, not arbitrary
|
|
339
345
|
# business output. An approval receipt is nonterminal even in old logs
|
|
@@ -442,6 +442,7 @@ def _set_conversation_span_attributes(
|
|
|
442
442
|
span.set_attribute("langfuse.trace.name", runner_name)
|
|
443
443
|
span.set_attribute("langfuse.session.id", session_id)
|
|
444
444
|
span.set_attribute("session.id", session_id)
|
|
445
|
+
span.set_attribute("gen_ai.conversation.id", session_id)
|
|
445
446
|
span.set_attribute("langfuse.user.id", user_id)
|
|
446
447
|
span.set_attribute("user.id", user_id)
|
|
447
448
|
if model:
|
ksadk/detection/mcp_detector.py
CHANGED
|
@@ -35,15 +35,36 @@ class MCPDetectionResult:
|
|
|
35
35
|
|
|
36
36
|
|
|
37
37
|
class MCPDetector:
|
|
38
|
-
"""MCP 检测器 - 检测 FastMCP 项目"""
|
|
39
|
-
|
|
40
|
-
#
|
|
38
|
+
"""MCP 检测器 - 检测 FastMCP / MCPServer 项目"""
|
|
39
|
+
|
|
40
|
+
# Server 类导入特征。
|
|
41
|
+
#
|
|
42
|
+
# ## 为什么要认三套
|
|
43
|
+
#
|
|
44
|
+
# `mcp` 2.3.0 把 `FastMCP` 改名成 `MCPServer` 并挪了路径,
|
|
45
|
+
# **同时删除** `mcp.server.fastmcp`。反过来,mcp 1.x 没有新路径。
|
|
46
|
+
#
|
|
47
|
+
# 只认一套的后果(2026-11-18 实测):迁移到 mcp 2.x 后
|
|
48
|
+
# `_find_mcp_file()` 返回 `None` → `is_mcp=False` → `ksadk mcp build`
|
|
49
|
+
# 直接报「未检测到 FastMCP 项目」,**构建彻底失败**。
|
|
50
|
+
#
|
|
51
|
+
# 顺序:新的在前(用户装的通常是新版),旧的兜底。
|
|
41
52
|
FASTMCP_PATTERNS = [
|
|
53
|
+
# mcp >= 2.3
|
|
54
|
+
"from mcp.server.mcpserver import",
|
|
55
|
+
"import mcp.server.mcpserver",
|
|
56
|
+
# mcp 2.0 ~ 2.2 的内部路径
|
|
57
|
+
"from mcp.server.mcpserver.server import",
|
|
58
|
+
# mcp 1.x(兼独立 fastmcp 包)
|
|
59
|
+
"from mcp.server.fastmcp import",
|
|
42
60
|
"from fastmcp import FastMCP",
|
|
43
61
|
"from fastmcp import",
|
|
44
62
|
"import fastmcp",
|
|
45
63
|
]
|
|
46
64
|
|
|
65
|
+
# 实例化时的类名(`_find_mcp_variable` 用它定位变量名)
|
|
66
|
+
SERVER_CLASS_NAMES = ("MCPServer", "FastMCP")
|
|
67
|
+
|
|
47
68
|
MCP_DECORATORS = [
|
|
48
69
|
"@mcp.tool",
|
|
49
70
|
"@mcp.resource",
|
|
@@ -110,7 +131,7 @@ class MCPDetector:
|
|
|
110
131
|
# 常见的 MCP 入口文件名
|
|
111
132
|
entry_files = ["server.py", "mcp_server.py", "main.py", "__init__.py"]
|
|
112
133
|
|
|
113
|
-
#
|
|
134
|
+
# 首先在根目录查找(根目录文件不会误判,不需要跳过)
|
|
114
135
|
for entry in entry_files:
|
|
115
136
|
file_path = self.project_dir / entry
|
|
116
137
|
if file_path.exists() and self._is_mcp_file(file_path):
|
|
@@ -119,7 +140,7 @@ class MCPDetector:
|
|
|
119
140
|
# 在子包中查找
|
|
120
141
|
for item in self.project_dir.iterdir():
|
|
121
142
|
if item.is_dir() and (item / "__init__.py").exists():
|
|
122
|
-
if
|
|
143
|
+
if self._should_skip(item):
|
|
123
144
|
continue
|
|
124
145
|
|
|
125
146
|
for entry in entry_files:
|
|
@@ -134,19 +155,55 @@ class MCPDetector:
|
|
|
134
155
|
|
|
135
156
|
# 扫描所有 .py 文件
|
|
136
157
|
for py_file in self.project_dir.rglob("*.py"):
|
|
137
|
-
|
|
138
|
-
if (
|
|
139
|
-
"__pycache__" in path_str
|
|
140
|
-
or "/.agentengine/" in path_str
|
|
141
|
-
or "/.venv/" in path_str
|
|
142
|
-
or "/venv/" in path_str
|
|
143
|
-
):
|
|
158
|
+
if self._should_skip(py_file):
|
|
144
159
|
continue
|
|
145
160
|
if self._is_mcp_file(py_file):
|
|
146
161
|
return py_file
|
|
147
162
|
|
|
148
163
|
return None
|
|
149
164
|
|
|
165
|
+
# 已知非源码目录:入口探测必须跳过它们。
|
|
166
|
+
NON_SOURCE_DIRS = frozenset(
|
|
167
|
+
{
|
|
168
|
+
"tests",
|
|
169
|
+
"test",
|
|
170
|
+
"testing",
|
|
171
|
+
"__pycache__",
|
|
172
|
+
"node_modules",
|
|
173
|
+
"venv",
|
|
174
|
+
"env",
|
|
175
|
+
}
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
def _should_skip(self, path: Path) -> bool:
|
|
179
|
+
"""判断路径是否应被入口探测跳过。
|
|
180
|
+
|
|
181
|
+
## 为什么必须跳过 `tests/`
|
|
182
|
+
|
|
183
|
+
单元测试里经常 `from fastmcp import FastMCP`(为了构造 Server 断言工具面)。
|
|
184
|
+
而 `_is_mcp_file()` 只看这一行导入,于是测试文件会被当成生产入口。
|
|
185
|
+
|
|
186
|
+
实测(ezone-mcp):一个 4310 文件的项目,`rglob("*.py")` 先命中
|
|
187
|
+
`tests/test_agent_surface.py`,生成的 entrypoint 变成
|
|
188
|
+
`from tests.test_agent_surface import mcp` —— **打包能过,运行必崩**
|
|
189
|
+
(模块级没有 `mcp`,且 tests 不在运行路径里)。
|
|
190
|
+
|
|
191
|
+
## 为什么还要跳过点目录
|
|
192
|
+
|
|
193
|
+
`.venv/` / `.agentengine/` / `.worktrees/` / `.git/` / `.tox/` 里可能是
|
|
194
|
+
**完整仓库副本或已安装依赖**。扫描它们既慢(几千个文件),
|
|
195
|
+
又必然把三方包里的 FastMCP 示例当成入口。
|
|
196
|
+
|
|
197
|
+
判断只看**父目录**(`parts[:-1]`)——文件名本身不参与,
|
|
198
|
+
所以 `test_server.py` 这种根目录文件仍会被根目录扫描命中。
|
|
199
|
+
"""
|
|
200
|
+
try:
|
|
201
|
+
parts = path.relative_to(self.project_dir).parts
|
|
202
|
+
except ValueError:
|
|
203
|
+
# 不在项目目录内(理论上不会发生),保守地不跳过
|
|
204
|
+
return False
|
|
205
|
+
return any(part.startswith(".") or part in self.NON_SOURCE_DIRS for part in parts[:-1])
|
|
206
|
+
|
|
150
207
|
def _is_mcp_file(self, file_path: Path) -> bool:
|
|
151
208
|
"""检查文件是否包含 FastMCP 代码"""
|
|
152
209
|
try:
|
|
@@ -212,17 +269,18 @@ class MCPDetector:
|
|
|
212
269
|
)
|
|
213
270
|
|
|
214
271
|
def _find_mcp_variable(self, tree: ast.AST, content: str) -> str:
|
|
215
|
-
"""查找
|
|
216
|
-
# 查找 xxx = FastMCP(...) 模式
|
|
272
|
+
"""查找 server 实例的变量名(`xxx = MCPServer(...)` / `xxx = MCPServer(...)`)。"""
|
|
217
273
|
for node in ast.walk(tree):
|
|
218
|
-
if isinstance(node, ast.Assign):
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
274
|
+
if not isinstance(node, ast.Assign):
|
|
275
|
+
continue
|
|
276
|
+
if not isinstance(node.value, ast.Call):
|
|
277
|
+
continue
|
|
278
|
+
func = node.value.func
|
|
279
|
+
# 兼容 `MCPServer(...)` 与 `fastmcp.MCPServer(...)` 两种写法
|
|
280
|
+
name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", None)
|
|
281
|
+
if name in self.SERVER_CLASS_NAMES:
|
|
282
|
+
if node.targets and isinstance(node.targets[0], ast.Name):
|
|
283
|
+
return node.targets[0].id
|
|
226
284
|
|
|
227
285
|
# 默认返回 mcp
|
|
228
286
|
return "mcp"
|
ksadk/harness/__init__.py
CHANGED
|
@@ -33,6 +33,9 @@ _EXPORTS = {
|
|
|
33
33
|
"StagnationPolicy": ("ksadk.harness.run_control", "StagnationPolicy"),
|
|
34
34
|
"HarnessRuntime": ("ksadk.harness.runtime", "HarnessRuntime"),
|
|
35
35
|
"HarnessRuntimeAdapter": ("ksadk.harness.runtime", "HarnessRuntimeAdapter"),
|
|
36
|
+
"HarnessServiceRuntimeAdapter": (
|
|
37
|
+
"ksadk.harness.service_runtime", "HarnessServiceRuntimeAdapter",
|
|
38
|
+
),
|
|
36
39
|
"HarnessSandboxExecutor": ("ksadk.harness.sandbox", "HarnessSandboxExecutor"),
|
|
37
40
|
"SandboxPolicyDenied": ("ksadk.harness.sandbox", "SandboxPolicyDenied"),
|
|
38
41
|
"ToolDeliverySemantics": (
|