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.
Files changed (98) hide show
  1. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/METADATA +14 -9
  2. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/RECORD +98 -68
  3. ksadk/__init__.py +2 -1
  4. ksadk/_build_provenance.json +1 -1
  5. ksadk/_mcp_compat.py +305 -0
  6. ksadk/agent.py +29 -0
  7. ksadk/agui/_agent_kernel.py +176 -142
  8. ksadk/agui/agent.py +74 -5
  9. ksadk/agui/hosted.py +343 -0
  10. ksadk/agui/request_identity.py +11 -0
  11. ksadk/agui/routes.py +77 -2
  12. ksadk/builders/code_builder.py +30 -23
  13. ksadk/builders/container_builder.py +5 -5
  14. ksadk/builders/mcp_builder.py +142 -0
  15. ksadk/builders/project_imports.py +66 -0
  16. ksadk/cli/cmd_mcp.py +1 -1
  17. ksadk/cli/cmd_run.py +2 -4
  18. ksadk/cli/cmd_web.py +8 -0
  19. ksadk/cli/runtime_bootstrap.py +4 -1
  20. ksadk/common/cloud_headers.py +33 -6
  21. ksadk/compat/adk_compat.py +2 -0
  22. ksadk/compat/adk_stream.py +35 -0
  23. ksadk/configs/env_registry.py +31 -0
  24. ksadk/conversations/projector.py +6 -0
  25. ksadk/conversations/runtime_observability.py +1 -0
  26. ksadk/detection/mcp_detector.py +80 -22
  27. ksadk/harness/__init__.py +3 -0
  28. ksadk/harness/service_presentation.py +44 -0
  29. ksadk/harness/service_runtime.py +1038 -0
  30. ksadk/interaction/providers/harness.py +9 -4
  31. ksadk/kernel/ingress.py +35 -25
  32. ksadk/kernel/worker.py +2 -2
  33. ksadk/kernel/worker_identity.py +15 -8
  34. ksadk/knowledge_base/client.py +10 -3
  35. ksadk/mcp_runtime/oauth/_agent.py +77 -9
  36. ksadk/mcp_runtime/oauth/langgraph.py +47 -15
  37. ksadk/mcp_runtime/oauth/local/broker.py +23 -1
  38. ksadk/mcp_runtime/oauth/tools.py +46 -8
  39. ksadk/mcp_runtime/oauth/transport.py +19 -2
  40. ksadk/memory/adk/backends/sdk_ltm_backend.py +21 -12
  41. ksadk/memory/scope_ids.py +49 -0
  42. ksadk/plugins/providers/harness.py +65 -28
  43. ksadk/plugins/providers/harness_service.py +198 -0
  44. ksadk/plugins/providers/harness_service_context.py +175 -0
  45. ksadk/plugins/providers/harness_service_hooks.py +168 -0
  46. ksadk/plugins/providers/harness_service_memory.py +479 -0
  47. ksadk/plugins/providers/platform_resources.py +2 -2
  48. ksadk/resource_runtime/langgraph.py +7 -3
  49. ksadk/resource_runtime/mcp_server.py +3 -3
  50. ksadk/resource_runtime/worker.py +19 -4
  51. ksadk/runners/_adk_canonical_stream.py +38 -10
  52. ksadk/runners/_adk_tunnel_history.py +96 -0
  53. ksadk/runners/_langgraph_canonical_stream.py +16 -0
  54. ksadk/runners/_langgraph_factory.py +79 -0
  55. ksadk/runners/_langgraph_runner_streams.py +6 -0
  56. ksadk/runners/_session_identity.py +8 -3
  57. ksadk/runners/adk_runner.py +95 -19
  58. ksadk/runners/langgraph_runner.py +15 -21
  59. ksadk/runtime/factory.py +17 -5
  60. ksadk/runtime/framework_adapters.py +10 -0
  61. ksadk/runtime/langgraph_checkpoint_view.py +28 -7
  62. ksadk/runtime/launch.py +2 -0
  63. ksadk/server/factory.py +55 -0
  64. ksadk/server/routes/common.py +2 -0
  65. ksadk/server/routes/harness_service_view.py +38 -0
  66. ksadk/server/routes/ui_bootstrap.py +16 -2
  67. ksadk/skills/mcp_server/server.py +239 -217
  68. ksadk/studio/contracts.py +8 -0
  69. ksadk/studio/mcp_runtime.py +23 -8
  70. ksadk/studio/native_mcp_disclosure.py +8 -6
  71. ksadk/studio/native_mcp_tool_port.py +3 -1
  72. ksadk/studio/native_memory_context.py +10 -8
  73. ksadk/studio/native_product.py +3 -4
  74. ksadk/studio/plugin_composition.py +8 -1
  75. ksadk/studio/plugin_native_activation.py +4 -2
  76. ksadk/studio/plugin_runtime.py +9 -0
  77. ksadk/studio/service.py +2 -0
  78. ksadk/tracing/setup.py +53 -3
  79. ksadk/tunnel/__init__.py +37 -0
  80. ksadk/tunnel/connector.py +384 -0
  81. ksadk/tunnel/discovery.py +107 -0
  82. ksadk/tunnel/failure.py +168 -0
  83. ksadk/tunnel/http_tools.py +100 -0
  84. ksadk/tunnel/langgraph.py +125 -0
  85. ksadk/tunnel/middleware.py +28 -0
  86. ksadk/tunnel/peers.py +872 -0
  87. ksadk/tunnel/protocol.py +97 -0
  88. ksadk/tunnel/registry.py +306 -0
  89. ksadk/tunnel/runtime.py +147 -0
  90. ksadk/tunnel/server.py +201 -0
  91. ksadk/tunnel/services.py +366 -0
  92. ksadk/tunnel/toolset.py +78 -0
  93. ksadk/version.py +1 -1
  94. ksadk_runtime_common/memory_backend/providers/mem0.py +20 -0
  95. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/WHEEL +0 -0
  96. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/entry_points.txt +0 -0
  97. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/licenses/LICENSE +0 -0
  98. {agentengine_sdk_python-0.8.7.dist-info → agentengine_sdk_python-0.8.8.dist-info}/top_level.txt +0 -0
ksadk/tunnel/server.py ADDED
@@ -0,0 +1,201 @@
1
+ """Authenticated WebSocket ingress; deliberately exposes no HTTP proxy routes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import secrets
7
+ from dataclasses import dataclass, field
8
+ from typing import Mapping
9
+
10
+ from fastapi import FastAPI, WebSocket, WebSocketDisconnect
11
+
12
+ from .protocol import VERSION, TunnelError, TunnelLimits, decode, encode, identifier
13
+ from .registry import ConnectorConnection, TunnelRegistry
14
+
15
+
16
+ @dataclass(frozen=True)
17
+ class TunnelAgentPolicy:
18
+ """A stable deployment identity, secret and explicitly admitted service aliases."""
19
+
20
+ agent_id: str
21
+ token: str = field(repr=False)
22
+ services: tuple[str, ...] | None = ()
23
+
24
+ def __post_init__(self):
25
+ identifier(self.agent_id, "agent_id")
26
+ if not isinstance(self.token, str) or not self.token.strip():
27
+ raise ValueError("a non-empty tunnel token is required")
28
+ if self.services is None:
29
+ return # This deployment accepts service names declared by the authenticated connector.
30
+ if not self.services or len(set(self.services)) != len(self.services):
31
+ raise ValueError("services must be a non-empty unique alias allowlist")
32
+ for service in self.services:
33
+ identifier(service, "service")
34
+
35
+
36
+ def mount_tunnel(
37
+ app: FastAPI,
38
+ *,
39
+ policies: list[TunnelAgentPolicy],
40
+ registry: TunnelRegistry | None = None,
41
+ limits: TunnelLimits | None = None,
42
+ ) -> TunnelRegistry:
43
+ """Mount /tunnel/connect. Caller closes the returned registry at app shutdown.
44
+
45
+ Gateway Authorization belongs to the WS handshake. Application tunnel
46
+ credentials are accepted only in the first register frame, never in a URL.
47
+ """
48
+ if hasattr(app.state, "mcp_tunnel"):
49
+ raise ValueError("MCP tunnel already mounted")
50
+ by_agent: Mapping[str, TunnelAgentPolicy] = {policy.agent_id: policy for policy in policies}
51
+ if not by_agent or len(by_agent) != len(policies):
52
+ raise ValueError("at least one unique tunnel agent policy is required")
53
+ reg = registry if registry is not None else TunnelRegistry()
54
+ if getattr(reg, "_owner_app", None) is not None:
55
+ raise ValueError("MCP tunnel registry already belongs to another app")
56
+ reg._owner_app = app
57
+ bounds = limits or TunnelLimits()
58
+ app.state.mcp_tunnel = reg
59
+
60
+ app.websocket("/tunnel/connect")(_connector_endpoint(by_agent, reg, bounds))
61
+ return reg
62
+
63
+
64
+ def _validate_descriptor(descriptor, bounds):
65
+ if descriptor["protocol"] == "api":
66
+ from mcp.types import Tool
67
+
68
+ if set(descriptor) != {"name", "protocol", "tools"} or not isinstance(
69
+ descriptor["tools"], list
70
+ ):
71
+ raise ValueError("invalid API descriptor")
72
+ tools = [Tool.model_validate(tool) for tool in descriptor["tools"]]
73
+ if len(tools) > bounds.max_tools or len({t.name for t in tools}) != len(tools):
74
+ raise ValueError("invalid API tools")
75
+ elif descriptor["protocol"] != "mcp":
76
+ raise ValueError("invalid service protocol")
77
+ elif set(descriptor) - {"name", "protocol", "tool_filter"}:
78
+ raise ValueError("invalid MCP descriptor")
79
+ filters = descriptor.get("tool_filter")
80
+ if filters is not None and (
81
+ not isinstance(filters, list)
82
+ or len(filters) > bounds.max_tools
83
+ or any(not isinstance(item, str) or not item for item in filters)
84
+ ):
85
+ raise ValueError("invalid MCP tool filter")
86
+
87
+
88
+ def _connector_endpoint(by_agent, reg, bounds):
89
+ async def reject(ws, error, reason):
90
+ # Gateways may drop WS close codes. Send a credential-free rejection
91
+ # before closing so clients can stop retrying permanent registration errors.
92
+ async with asyncio.timeout(bounds.send_timeout):
93
+ await ws.send_text(
94
+ encode(
95
+ {"type": "registration_rejected", "version": VERSION, "error": error}, bounds
96
+ )
97
+ )
98
+ await ws.close(code=4409 if error == "duplicate_service" else 4403, reason=reason)
99
+
100
+ async def connect(ws: WebSocket):
101
+ await ws.accept()
102
+ conn = None
103
+ try:
104
+ async with asyncio.timeout(bounds.registration_timeout):
105
+ frame = decode(await ws.receive_text(), bounds)
106
+ if (
107
+ set(frame) - {"agent_id"} != {"type", "version", "token", "services"}
108
+ or frame.get("type") != "register"
109
+ or frame.get("version") != VERSION
110
+ ):
111
+ raise ValueError("invalid registration")
112
+ if "agent_id" in frame:
113
+ agent = identifier(frame["agent_id"], "agent_id")
114
+ elif len(by_agent) == 1:
115
+ agent = next(iter(by_agent))
116
+ else:
117
+ raise ValueError("agent_id required for a multi-agent host")
118
+ policy = by_agent.get(agent)
119
+ token = frame["token"]
120
+ if (
121
+ policy is None
122
+ or not isinstance(token, str)
123
+ or not secrets.compare_digest(token.encode(), policy.token.encode())
124
+ ):
125
+ await reject(ws, "unauthorized", "unauthorized")
126
+ return
127
+ services = frame["services"]
128
+ if (
129
+ not isinstance(services, list)
130
+ or not services
131
+ or len(services) > bounds.max_services
132
+ ):
133
+ await reject(ws, "unauthorized", "invalid services")
134
+ return
135
+ descriptors = {}
136
+ for descriptor in services:
137
+ name = identifier(descriptor["name"], "service")
138
+ if name in descriptors or (
139
+ policy.services is not None and name not in policy.services
140
+ ):
141
+ await reject(ws, "unauthorized", "service not authorized")
142
+ return
143
+ _validate_descriptor(descriptor, bounds)
144
+ descriptors[name] = descriptor
145
+ conn = ConnectorConnection(agent, descriptors, ws, bounds)
146
+ reg.add(conn)
147
+ await conn.send(
148
+ {"type": "registered", "version": VERSION, "connector_id": conn.connector_id}
149
+ )
150
+ if reg.peers is not None:
151
+ reg.peers.request_start()
152
+ while True:
153
+ async with asyncio.timeout(bounds.idle_timeout):
154
+ message = decode(await ws.receive_text(), bounds)
155
+ if message == {"type": "heartbeat"}:
156
+ await conn.send({"type": "heartbeat_ack"})
157
+ if reg.peers is not None and reg.peers.owner is None:
158
+ reg.peers.request_start()
159
+ else:
160
+ conn.dispatch(message)
161
+ except WebSocketDisconnect:
162
+ pass
163
+ except TunnelError as exc:
164
+ if exc.code == "duplicate_service":
165
+ await reject(ws, "duplicate_service", "service already connected")
166
+ return
167
+ await ws.close(code=4400, reason="invalid tunnel frame")
168
+ except (ValueError, TypeError, TimeoutError, KeyError, RuntimeError):
169
+ try:
170
+ await ws.close(code=4400, reason="invalid or expired tunnel frame")
171
+ except RuntimeError:
172
+ pass
173
+ finally:
174
+ if conn is not None:
175
+ reg.remove(conn)
176
+
177
+ return connect
178
+
179
+
180
+ def install_connector_fallback(app, deferred):
181
+ """Only an unmatched connector WebSocket may trigger first-use discovery."""
182
+ from starlette._utils import get_route_path
183
+
184
+ default = app.router.default
185
+ ingress = None
186
+
187
+ async def fallback(scope, receive, send):
188
+ nonlocal ingress
189
+ if scope["type"] == "websocket" and get_route_path(scope) == "/tunnel/connect":
190
+ if ingress is None:
191
+ binding = deferred.for_connector()
192
+ if binding is not None:
193
+ ingress = _connector_endpoint(
194
+ {binding.policy.agent_id: binding.policy}, binding.registry, TunnelLimits()
195
+ )
196
+ app.state.mcp_tunnel = binding.registry
197
+ if ingress is not None:
198
+ return await ingress(WebSocket(scope, receive, send))
199
+ return await default(scope, receive, send)
200
+
201
+ app.router.default = fallback
@@ -0,0 +1,366 @@
1
+ """Connector-local HTTP destinations and their public service declarations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from dataclasses import dataclass, field
7
+ from string import Formatter
8
+ from typing import Any
9
+ from urllib.parse import quote, urlsplit, urlunsplit
10
+
11
+ # The transport, response streams and MCP client must use the same backend,
12
+ # even when both httpx packages are installed in a legacy MCP environment.
13
+ from ksadk._mcp_compat import httpx_module
14
+
15
+ httpx = httpx_module()
16
+ from mcp.types import Tool
17
+
18
+ from .protocol import TunnelError, identifier
19
+
20
+ _REQUEST_HEADERS = frozenset(
21
+ {"accept", "content-type", "mcp-session-id", "mcp-protocol-version", "last-event-id"}
22
+ )
23
+ _RESPONSE_HEADERS = frozenset(
24
+ {
25
+ "content-type",
26
+ "mcp-session-id",
27
+ "mcp-protocol-version",
28
+ "last-event-id",
29
+ "cache-control",
30
+ "retry-after",
31
+ "content-language",
32
+ }
33
+ )
34
+
35
+
36
+ def _endpoint(url: str) -> None:
37
+ if not isinstance(url, str):
38
+ raise ValueError("local endpoint must be an absolute http(s) URL")
39
+ parsed = urlsplit(url)
40
+ if (
41
+ parsed.scheme not in {"http", "https"}
42
+ or not parsed.hostname
43
+ or parsed.fragment
44
+ or parsed.username
45
+ or parsed.password
46
+ ):
47
+ raise ValueError(
48
+ "local endpoint must be an absolute http(s) URL without userinfo or fragment"
49
+ )
50
+ try:
51
+ httpx.URL(url)
52
+ except Exception:
53
+ raise ValueError("invalid local endpoint URL") from None
54
+
55
+
56
+ def _names(value, field_name: str) -> tuple[str, ...]:
57
+ if (
58
+ not isinstance(value, (tuple, list))
59
+ or any(not isinstance(name, str) or not name for name in value)
60
+ or len(set(value)) != len(value)
61
+ ):
62
+ raise ValueError(f"{field_name} must contain unique non-empty names")
63
+ return tuple(value)
64
+
65
+
66
+ def _schema(schema: dict) -> None:
67
+ from jsonschema import Draft202012Validator
68
+
69
+ try:
70
+ if not isinstance(schema, dict):
71
+ raise ValueError
72
+ Draft202012Validator.check_schema(schema)
73
+ except Exception:
74
+ raise ValueError("input_schema must be a valid JSON Schema object") from None
75
+
76
+
77
+ def validate_arguments(schema: dict, arguments: dict) -> None:
78
+ """Validate locally; external schema references never perform network I/O."""
79
+ from jsonschema import Draft202012Validator
80
+ from referencing import Registry
81
+
82
+ try:
83
+ valid = Draft202012Validator(schema, registry=Registry()).is_valid(arguments)
84
+ except Exception:
85
+ raise TunnelError("local_service_error") from None
86
+ if not valid:
87
+ raise TunnelError("invalid_request")
88
+
89
+
90
+ def _headers(headers: dict[str, str]) -> dict[str, str]:
91
+ try:
92
+ if not isinstance(headers, dict) or any(
93
+ not isinstance(k, str) or not isinstance(v, str) for k, v in headers.items()
94
+ ):
95
+ raise ValueError
96
+ return dict(httpx.Headers(headers))
97
+ except Exception:
98
+ raise ValueError("headers must map header names to string values") from None
99
+
100
+
101
+ def response_headers(headers: httpx.Headers) -> dict[str, str]:
102
+ """Forward protocol metadata, excluding cookies, auth, redirects and encoding.
103
+
104
+ The connector decodes HTTP content encoding before emitting UTF-8 chunks,
105
+ so Content-Encoding and Content-Length must not cross the transport.
106
+ """
107
+ return {name: value for name, value in headers.items() if name.lower() in _RESPONSE_HEADERS}
108
+
109
+
110
+ @dataclass(frozen=True)
111
+ class LocalMCPService:
112
+ """One fixed Streamable HTTP endpoint; local credentials never register."""
113
+
114
+ name: str
115
+ url: str = field(repr=False)
116
+ headers: dict[str, str] = field(default_factory=dict, repr=False)
117
+ tool_filter: tuple[str, ...] | None = None
118
+
119
+ def __post_init__(self):
120
+ identifier(self.name, "service name")
121
+ _endpoint(self.url)
122
+ object.__setattr__(self, "headers", _headers(self.headers))
123
+ if self.tool_filter is not None:
124
+ object.__setattr__(self, "tool_filter", _names(self.tool_filter, "tool_filter"))
125
+
126
+ def descriptor(self) -> dict:
127
+ return {
128
+ "name": self.name,
129
+ "protocol": "mcp",
130
+ "tool_filter": list(self.tool_filter) if self.tool_filter is not None else None,
131
+ }
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class APIOperation:
136
+ """Expose a named HTTP operation as a model-bindable tool.
137
+
138
+ Path fields are inferred from {name} placeholders when path_params is
139
+ omitted. query_params explicitly selects query arguments. body_params=None
140
+ sends remaining arguments as JSON for POST/PUT/PATCH/DELETE; an empty tuple
141
+ sends no arguments in the body. GET arguments must all be mapped to the
142
+ path or query. No caller argument can change the destination or method.
143
+ """
144
+
145
+ name: str
146
+ method: str
147
+ path: str = field(repr=False)
148
+ input_schema: dict
149
+ description: str = ""
150
+ path_params: tuple[str, ...] = ()
151
+ query_params: tuple[str, ...] = ()
152
+ body_params: tuple[str, ...] | None = None
153
+
154
+ def __post_init__(self):
155
+ identifier(self.name, "operation name")
156
+ if not isinstance(self.method, str) or self.method.upper() not in {
157
+ "GET",
158
+ "POST",
159
+ "PUT",
160
+ "PATCH",
161
+ "DELETE",
162
+ }:
163
+ raise ValueError("operation method must be GET, POST, PUT, PATCH or DELETE")
164
+ object.__setattr__(self, "method", self.method.upper())
165
+ if (
166
+ not isinstance(self.path, str)
167
+ or not self.path.startswith("/")
168
+ or self.path.startswith("//")
169
+ or any(char in self.path for char in "\\%?#\r\n\x00")
170
+ or any(part in {".", ".."} for part in self.path.split("/"))
171
+ ):
172
+ raise ValueError(
173
+ "operation path must be a fixed absolute path without traversal or query"
174
+ )
175
+ try:
176
+ fields = []
177
+ for _, name, spec, conversion in Formatter().parse(self.path):
178
+ if name is None:
179
+ continue
180
+ identifier(name, "path parameter")
181
+ if spec or conversion or name in fields:
182
+ raise ValueError
183
+ fields.append(name)
184
+ except ValueError:
185
+ raise ValueError("operation path must use unique plain {name} parameters") from None
186
+ path_params = _names(self.path_params, "path_params") or tuple(fields)
187
+ if set(path_params) != set(fields):
188
+ raise ValueError("path_params must match operation path placeholders")
189
+ query_params = _names(self.query_params, "query_params")
190
+ body_params = None if self.body_params is None else _names(self.body_params, "body_params")
191
+ mapped = [*path_params, *query_params, *(body_params or ())]
192
+ if len(mapped) != len(set(mapped)):
193
+ raise ValueError("operation argument mappings must not overlap")
194
+ if self.method == "GET" and body_params:
195
+ raise ValueError("GET operations cannot declare body_params")
196
+ if not isinstance(self.description, str):
197
+ raise ValueError("operation description must be a string")
198
+ _schema(self.input_schema)
199
+ object.__setattr__(self, "path_params", path_params)
200
+ object.__setattr__(self, "query_params", query_params)
201
+ object.__setattr__(self, "body_params", body_params)
202
+
203
+ def tool(self) -> dict:
204
+ return Tool(
205
+ name=self.name, description=self.description, inputSchema=self.input_schema
206
+ ).model_dump(by_alias=True, mode="json", exclude_none=True)
207
+
208
+
209
+ @dataclass(frozen=True)
210
+ class LocalAPIService:
211
+ """A local HTTP API with an explicit, finite operation allowlist."""
212
+
213
+ name: str
214
+ base_url: str = field(repr=False)
215
+ operations: tuple[APIOperation, ...]
216
+ headers: dict[str, str] = field(default_factory=dict, repr=False)
217
+
218
+ def __post_init__(self):
219
+ identifier(self.name, "service name")
220
+ _endpoint(self.base_url)
221
+ if (
222
+ not isinstance(self.operations, (list, tuple))
223
+ or not self.operations
224
+ or any(not isinstance(op, APIOperation) for op in self.operations)
225
+ or len({op.name for op in self.operations}) != len(self.operations)
226
+ ):
227
+ raise ValueError("operations must contain uniquely named APIOperation declarations")
228
+ fixed_query = set(httpx.QueryParams(urlsplit(self.base_url).query))
229
+ if any(set(op.query_params) & fixed_query for op in self.operations):
230
+ raise ValueError(
231
+ "operation query parameters must not override configured URL parameters"
232
+ )
233
+ object.__setattr__(self, "operations", tuple(self.operations))
234
+ object.__setattr__(self, "headers", _headers(self.headers))
235
+
236
+ def descriptor(self) -> dict:
237
+ return {
238
+ "name": self.name,
239
+ "protocol": "api",
240
+ "tools": [op.tool() for op in self.operations],
241
+ }
242
+
243
+
244
+ def _empty_query(query: Any) -> bool:
245
+ return query in ("", None) or query == {} or query == []
246
+
247
+
248
+ def _json_arguments(body: str) -> dict:
249
+ try:
250
+
251
+ def reject_constant(_):
252
+ raise ValueError
253
+
254
+ arguments = json.loads(body, parse_constant=reject_constant)
255
+ if not isinstance(arguments, dict):
256
+ raise ValueError
257
+ return arguments
258
+ except (ValueError, TypeError, RecursionError):
259
+ raise TunnelError("invalid_request") from None
260
+
261
+
262
+ def _prepare_mcp_request(service, method, path, forwarded, body) -> httpx.Request:
263
+ if path not in {"", "/"} or method not in {"GET", "POST", "DELETE"}:
264
+ raise TunnelError("forbidden")
265
+ headers = httpx.Headers(
266
+ {k: v for k, v in forwarded.items() if isinstance(k, str) and k.lower() in _REQUEST_HEADERS}
267
+ )
268
+ headers.update(service.headers)
269
+ if method == "POST" and service.tool_filter is not None:
270
+ message = _json_arguments(body)
271
+ if message.get("method") == "tools/call":
272
+ params = message.get("params")
273
+ if not isinstance(params, dict) or params.get("name") not in service.tool_filter:
274
+ raise TunnelError("forbidden")
275
+ return httpx.Request(method, service.url, headers=headers, content=body.encode("utf-8"))
276
+
277
+
278
+ def _api_target(service, operation, arguments) -> httpx.URL:
279
+ path_values = {}
280
+ for name in operation.path_params:
281
+ value = arguments.get(name)
282
+ if (
283
+ not isinstance(value, (str, int, float))
284
+ or isinstance(value, bool)
285
+ or str(value) in {".", ".."}
286
+ or any(char in str(value) for char in "/\\%\r\n\x00")
287
+ ):
288
+ raise TunnelError("invalid_request")
289
+ path_values[name] = quote(str(value), safe="")
290
+ local = urlsplit(service.base_url)
291
+ target = httpx.URL(
292
+ urlunsplit(
293
+ (
294
+ local.scheme,
295
+ local.netloc,
296
+ local.path.rstrip("/") + operation.path.format_map(path_values),
297
+ local.query,
298
+ "",
299
+ )
300
+ )
301
+ )
302
+ query_values = []
303
+ for name in operation.query_params:
304
+ if name not in arguments:
305
+ continue
306
+ values = arguments[name] if isinstance(arguments[name], list) else [arguments[name]]
307
+ for value in values:
308
+ if not isinstance(value, (str, int, float, bool, type(None))):
309
+ raise TunnelError("invalid_request")
310
+ text = (
311
+ ""
312
+ if value is None
313
+ else str(value).lower() if isinstance(value, bool) else str(value)
314
+ )
315
+ query_values.append((name, text))
316
+ return target.copy_merge_params(query_values) if query_values else target
317
+
318
+
319
+ def _prepare_api_request(service, method, path, body) -> httpx.Request:
320
+ if method != "POST":
321
+ raise TunnelError("forbidden")
322
+ operation = next((op for op in service.operations if op.name == path), None)
323
+ if operation is None:
324
+ raise TunnelError("forbidden")
325
+ arguments = _json_arguments(body)
326
+ validate_arguments(operation.input_schema, arguments)
327
+ target = _api_target(service, operation, arguments)
328
+ remaining = set(arguments) - set(operation.path_params) - set(operation.query_params)
329
+ body_names = (
330
+ remaining
331
+ if operation.body_params is None
332
+ else set(operation.body_params) & arguments.keys()
333
+ )
334
+ if remaining - body_names or (operation.method == "GET" and body_names):
335
+ raise TunnelError("invalid_request")
336
+ headers = httpx.Headers(service.headers)
337
+ if body_names or operation.method in {"POST", "PUT", "PATCH"}:
338
+ payload = {name: arguments[name] for name in body_names}
339
+ return httpx.Request(operation.method, target, headers=headers, json=payload)
340
+ return httpx.Request(operation.method, target, headers=headers)
341
+
342
+
343
+ def prepare_request(service: LocalMCPService | LocalAPIService, frame: dict) -> httpx.Request:
344
+ """Resolve the synthetic request using only connector-owned destinations."""
345
+ try:
346
+ method, path, query, forwarded, body = (
347
+ frame[key] for key in ("method", "path", "query", "headers", "body")
348
+ )
349
+ if (
350
+ not isinstance(method, str)
351
+ or not isinstance(path, str)
352
+ or not isinstance(body, str)
353
+ or not isinstance(forwarded, dict)
354
+ or not _empty_query(query)
355
+ ):
356
+ raise TunnelError("invalid_request")
357
+ if isinstance(service, LocalMCPService):
358
+ return _prepare_mcp_request(service, method, path, forwarded, body)
359
+ if isinstance(service, LocalAPIService):
360
+ return _prepare_api_request(service, method, path, body)
361
+ raise TunnelError("forbidden")
362
+ except TunnelError:
363
+ raise
364
+ except Exception:
365
+ # Never expose URLs, configured headers, schema values or HTTP errors.
366
+ raise TunnelError("invalid_request") from None
@@ -0,0 +1,78 @@
1
+ """ADK integration, loaded only when the application requests ADK tools."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from ksadk._mcp_compat import tool_input_schema
6
+
7
+ from typing import Any
8
+
9
+ from ksadk.compat.adk_compat import BaseTool, BaseToolset
10
+ from ksadk.compat.adk_compat import genai_types as types
11
+
12
+ from .discovery import TunnelToolHandle, discover_tools
13
+ from .discovery import tool_name as _tool_name
14
+ from .protocol import identifier
15
+ from .registry import TunnelRegistry
16
+
17
+
18
+ class TunnelTool(BaseTool):
19
+ def __init__(self, *, agent_id, service, connector_id, descriptor, registry, owner=None):
20
+ super().__init__(
21
+ name=_tool_name(service, descriptor.name), description=descriptor.description or ""
22
+ )
23
+ self._agent_id = agent_id
24
+ self._service = service
25
+ self._connector_id = connector_id
26
+ self._descriptor = descriptor
27
+ self._registry = registry
28
+ self._owner = owner
29
+
30
+ def _get_declaration(self):
31
+ return types.FunctionDeclaration(
32
+ name=self.name,
33
+ description=self.description,
34
+ parameters_json_schema=tool_input_schema(self._descriptor),
35
+ )
36
+
37
+ async def run_async(self, *, args: dict[str, Any], tool_context: Any) -> dict:
38
+ return await TunnelToolHandle(
39
+ self._agent_id,
40
+ self._service,
41
+ self._connector_id,
42
+ self._descriptor,
43
+ self._registry,
44
+ self._owner,
45
+ ).call(args)
46
+
47
+
48
+ class TunnelToolset(BaseToolset):
49
+ """Read the app registry every ADK discovery; no loopback HTTP or tool cache."""
50
+
51
+ def __init__(self, agent_id: str, registry: TunnelRegistry):
52
+ super().__init__()
53
+ self.agent_id = identifier(agent_id, "agent_id")
54
+ self._registry = registry
55
+ self._closed = False
56
+ # New ADK releases optionally cache an invocation; the tunnel deliberately
57
+ # re-reads online registrations on every discovery in both ADK versions.
58
+ if hasattr(self, "_use_invocation_cache"):
59
+ self._use_invocation_cache = False
60
+
61
+ async def get_tools(self, readonly_context=None):
62
+ if self._closed:
63
+ return []
64
+
65
+ return [
66
+ TunnelTool(
67
+ agent_id=self.agent_id,
68
+ service=tool.service,
69
+ connector_id=tool.connector_id,
70
+ descriptor=tool.descriptor,
71
+ registry=self._registry,
72
+ owner=tool.owner,
73
+ )
74
+ for tool in await discover_tools(self.agent_id, self._registry)
75
+ ]
76
+
77
+ async def close(self):
78
+ self._closed = True
ksadk/version.py CHANGED
@@ -1,4 +1,4 @@
1
1
  """KsADK 版本信息"""
2
2
 
3
- VERSION = "0.8.7"
3
+ VERSION = "0.8.8"
4
4
  __version__ = VERSION
@@ -26,6 +26,16 @@ def _require_env_value(name: str) -> str:
26
26
  return str(os.getenv(name) or "").strip()
27
27
 
28
28
 
29
+ def _resolve_traffic_source() -> str:
30
+ """Resolve X-Traffic-Source header value, matching ksadk build_cloud_headers."""
31
+ return str(os.getenv("KSADK_TRAFFIC_SOURCE", "agentkit") or "agentkit").strip() or "agentkit"
32
+
33
+
34
+ def _resolve_component_env() -> str:
35
+ """Resolve KSADK_COMPONENT_ENV for the memory preproduction route."""
36
+ return str(os.getenv("KSADK_COMPONENT_ENV", "") or "").strip()
37
+
38
+
29
39
  class Mem0Provider:
30
40
  """Provider for the mem0 memory backend."""
31
41
 
@@ -47,6 +57,9 @@ class Mem0Provider:
47
57
  user_id = _require_env_value(user_id_env)
48
58
  base_url = _require_env_value(base_url_env)
49
59
 
60
+ traffic_source = _resolve_traffic_source()
61
+ component_env = _resolve_component_env()
62
+
50
63
  config_patch: dict[str, Any] = {
51
64
  "plugins": {
52
65
  "slots": {
@@ -60,6 +73,13 @@ class Mem0Provider:
60
73
  "apiKey": api_key,
61
74
  "baseUrl": base_url,
62
75
  "userId": user_id,
76
+ "extraHeaders": {
77
+ "X-Traffic-Source": traffic_source,
78
+ **(
79
+ {"X-KSC-CUSTOM-SOURCE": "pre"}
80
+ if component_env.lower() == "pre" else {}
81
+ ),
82
+ },
63
83
  },
64
84
  },
65
85
  },