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
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
"""Framework-independent discovery and connector-generation-bound tool handles."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import hashlib
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import re
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
|
|
12
|
+
from mcp.types import CallToolResult, ListToolsResult, Tool
|
|
13
|
+
|
|
14
|
+
from .protocol import IncompletePeerDiscovery, TunnelError
|
|
15
|
+
from .registry import TunnelRegistry
|
|
16
|
+
|
|
17
|
+
logger = logging.getLogger(__name__)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def tool_name(service: str, name: str) -> str:
|
|
21
|
+
raw = f"tunnel_{service}__{name}"
|
|
22
|
+
safe = re.sub(r"[^A-Za-z0-9_]", "_", raw)
|
|
23
|
+
digest = hashlib.sha256(json.dumps([service, name]).encode()).hexdigest()[:16]
|
|
24
|
+
return safe[:47] + "_" + digest
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class TunnelToolHandle:
|
|
29
|
+
agent_id: str
|
|
30
|
+
service: str
|
|
31
|
+
connector_id: str
|
|
32
|
+
descriptor: Tool
|
|
33
|
+
registry: TunnelRegistry = field(repr=False)
|
|
34
|
+
owner: dict | None = None
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def name(self) -> str:
|
|
38
|
+
return tool_name(self.service, self.descriptor.name)
|
|
39
|
+
|
|
40
|
+
async def call(self, arguments: dict) -> dict:
|
|
41
|
+
result = await self.registry.call_tool(
|
|
42
|
+
self.agent_id,
|
|
43
|
+
self.service,
|
|
44
|
+
self.descriptor.name,
|
|
45
|
+
arguments,
|
|
46
|
+
connector_id=self.connector_id,
|
|
47
|
+
**({"owner": self.owner} if self.owner is not None else {}),
|
|
48
|
+
)
|
|
49
|
+
try:
|
|
50
|
+
return CallToolResult.model_validate(result).model_dump(by_alias=True, mode="json", exclude_none=True)
|
|
51
|
+
except ValueError:
|
|
52
|
+
raise TunnelError("invalid_result", indeterminate=True) from None
|
|
53
|
+
|
|
54
|
+
def snapshot(self) -> dict:
|
|
55
|
+
"""Only public descriptors and generation IDs enter graph state."""
|
|
56
|
+
return {
|
|
57
|
+
"name": self.name,
|
|
58
|
+
"service": self.service,
|
|
59
|
+
"connector_id": self.connector_id,
|
|
60
|
+
"tool": self.descriptor.model_dump(mode="json", exclude_none=True),
|
|
61
|
+
**({"owner": self.owner} if self.owner is not None else {}),
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
async def discover_tools(agent_id: str, registry: TunnelRegistry) -> list[TunnelToolHandle]:
|
|
66
|
+
async def discover(service, connection):
|
|
67
|
+
try:
|
|
68
|
+
result = await registry.list_tools(
|
|
69
|
+
agent_id,
|
|
70
|
+
service,
|
|
71
|
+
connector_id=connection.connector_id,
|
|
72
|
+
**(
|
|
73
|
+
{"owner": connection.owner}
|
|
74
|
+
if getattr(connection, "owner", None) is not None
|
|
75
|
+
else {}
|
|
76
|
+
),
|
|
77
|
+
)
|
|
78
|
+
tools = ListToolsResult.model_validate(result).tools
|
|
79
|
+
if len(tools) > connection.limits.max_tools or len(
|
|
80
|
+
{tool.name for tool in tools}
|
|
81
|
+
) != len(tools):
|
|
82
|
+
raise ValueError("invalid tool list")
|
|
83
|
+
return [
|
|
84
|
+
TunnelToolHandle(
|
|
85
|
+
agent_id,
|
|
86
|
+
service,
|
|
87
|
+
connection.connector_id,
|
|
88
|
+
tool,
|
|
89
|
+
registry,
|
|
90
|
+
getattr(connection, "owner", None),
|
|
91
|
+
)
|
|
92
|
+
for tool in tools
|
|
93
|
+
]
|
|
94
|
+
except TunnelError as exc:
|
|
95
|
+
logger.warning("MCP tunnel discovery failed (%s)", exc.code)
|
|
96
|
+
return []
|
|
97
|
+
except ValueError:
|
|
98
|
+
logger.warning("MCP tunnel returned an invalid tool list")
|
|
99
|
+
return []
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
connections = await registry.discover_connections(agent_id)
|
|
103
|
+
except IncompletePeerDiscovery:
|
|
104
|
+
# The model can still chat and use its non-tunnel tools during a rollout.
|
|
105
|
+
return []
|
|
106
|
+
batches = await asyncio.gather(*(discover(service, conn) for service, conn in connections))
|
|
107
|
+
return [tool for tools in batches for tool in tools]
|
ksadk/tunnel/failure.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""End a failed tunnel turn with a deterministic answer, without re-entering tools."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
from collections.abc import Callable, Iterable
|
|
7
|
+
from dataclasses import dataclass
|
|
8
|
+
|
|
9
|
+
from .protocol import TunnelError
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
@dataclass(frozen=True)
|
|
13
|
+
class TunnelFailure:
|
|
14
|
+
indeterminate: bool
|
|
15
|
+
result_code: str = "tunnel_tool_failed"
|
|
16
|
+
|
|
17
|
+
def for_unanswered_calls(self, count: int) -> TunnelFailure:
|
|
18
|
+
# Several missing responses cannot be attributed to the one raised
|
|
19
|
+
# exception. A parallel sibling may already have completed a write.
|
|
20
|
+
return TunnelFailure(True, "tool_result_unavailable") if count > 1 else self
|
|
21
|
+
|
|
22
|
+
@property
|
|
23
|
+
def tool_result(self) -> dict:
|
|
24
|
+
return {
|
|
25
|
+
"error": self.result_code,
|
|
26
|
+
"message": self.message,
|
|
27
|
+
"indeterminate": self.indeterminate,
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def message(self) -> str:
|
|
32
|
+
if self.indeterminate:
|
|
33
|
+
return (
|
|
34
|
+
"工具调用中断,结果未知,操作可能已执行。已停止本次操作,未自动重试;"
|
|
35
|
+
"请先核实业务状态,再决定是否重新执行。"
|
|
36
|
+
)
|
|
37
|
+
return "工具调用失败,已停止本次操作,未自动重试。请检查工具服务或连接状态。"
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def metadata(self) -> dict:
|
|
41
|
+
return {
|
|
42
|
+
"tunnel_failure": {
|
|
43
|
+
"outcome": "unknown" if self.indeterminate else "failed",
|
|
44
|
+
"automatic_retry": False,
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def tunnel_failure(exc: BaseException) -> TunnelFailure | None:
|
|
50
|
+
"""Handle only tunnel failures, never mask unrelated errors or cancellation."""
|
|
51
|
+
if isinstance(exc, TunnelError):
|
|
52
|
+
if exc.code == "tool_result_unavailable":
|
|
53
|
+
return TunnelFailure(True, exc.code)
|
|
54
|
+
return TunnelFailure(exc.indeterminate)
|
|
55
|
+
if isinstance(exc, ExceptionGroup):
|
|
56
|
+
failures = [tunnel_failure(error) for error in exc.exceptions]
|
|
57
|
+
if failures and all(failure is not None for failure in failures):
|
|
58
|
+
return TunnelFailure(
|
|
59
|
+
any(failure.indeterminate for failure in failures if failure is not None)
|
|
60
|
+
)
|
|
61
|
+
return None
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def failure_events(
|
|
65
|
+
failure: TunnelFailure,
|
|
66
|
+
*,
|
|
67
|
+
run_id: str,
|
|
68
|
+
scope_id: str,
|
|
69
|
+
source,
|
|
70
|
+
allocate_seq: Callable[[], int],
|
|
71
|
+
open_items: Iterable[tuple[str, str, str]] = (),
|
|
72
|
+
pending_calls: Iterable[tuple[str, str]] = (),
|
|
73
|
+
):
|
|
74
|
+
"""Keep failed items failed; complete only the assistant's failure notification.
|
|
75
|
+
|
|
76
|
+
No graph/model is called, and no native checkpoint continuation is advertised.
|
|
77
|
+
"""
|
|
78
|
+
from ksadk.events.canonical import (
|
|
79
|
+
ErrorInfo,
|
|
80
|
+
ItemCompleted,
|
|
81
|
+
ItemFailed,
|
|
82
|
+
ItemStarted,
|
|
83
|
+
OutputRef,
|
|
84
|
+
RunCompleted,
|
|
85
|
+
)
|
|
86
|
+
from ksadk.events.content import ContentSnapshot, TextContent, ToolResultContent
|
|
87
|
+
from ksadk.events.identity import stable_event_id, stable_item_id
|
|
88
|
+
|
|
89
|
+
pending_calls = tuple(pending_calls)
|
|
90
|
+
failure = failure.for_unanswered_calls(len(pending_calls))
|
|
91
|
+
source = source.model_copy(update={"metadata": {**source.metadata, **failure.metadata}})
|
|
92
|
+
|
|
93
|
+
def envelope(event_type, item_id):
|
|
94
|
+
return dict(
|
|
95
|
+
schema_version=2,
|
|
96
|
+
run_id=run_id,
|
|
97
|
+
scope_id=scope_id,
|
|
98
|
+
source=source,
|
|
99
|
+
event_id=stable_event_id(
|
|
100
|
+
source.framework, scope_id, item_id, event_type, "tunnel-failure", run_id, 0
|
|
101
|
+
),
|
|
102
|
+
seq=allocate_seq(),
|
|
103
|
+
timestamp=time.time(),
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
for item_scope, item_id, kind in open_items:
|
|
107
|
+
fields = envelope("item.failed", item_id)
|
|
108
|
+
fields["scope_id"] = item_scope
|
|
109
|
+
yield ItemFailed(
|
|
110
|
+
**fields,
|
|
111
|
+
item_id=item_id,
|
|
112
|
+
item_kind=kind,
|
|
113
|
+
error=ErrorInfo(
|
|
114
|
+
code="tunnel_tool_failed",
|
|
115
|
+
message=failure.message,
|
|
116
|
+
source=source.framework,
|
|
117
|
+
scope_id=item_scope,
|
|
118
|
+
item_id=item_id,
|
|
119
|
+
),
|
|
120
|
+
)
|
|
121
|
+
for item_scope, call_id in pending_calls:
|
|
122
|
+
item_id = stable_item_id(source.framework, run_id, item_scope, call_id, "tunnel-failure")
|
|
123
|
+
fields = envelope("item.started", item_id)
|
|
124
|
+
fields["scope_id"] = item_scope
|
|
125
|
+
yield ItemStarted(**fields, item_id=item_id, item_kind="tool_result")
|
|
126
|
+
fields = envelope("item.completed", item_id)
|
|
127
|
+
fields["scope_id"] = item_scope
|
|
128
|
+
yield ItemCompleted(
|
|
129
|
+
**fields,
|
|
130
|
+
item_id=item_id,
|
|
131
|
+
item_kind="tool_result",
|
|
132
|
+
snapshot=ContentSnapshot(
|
|
133
|
+
parts=(
|
|
134
|
+
ToolResultContent(
|
|
135
|
+
part_id="result",
|
|
136
|
+
call_id=call_id,
|
|
137
|
+
is_error=True,
|
|
138
|
+
result=failure.tool_result,
|
|
139
|
+
),
|
|
140
|
+
)
|
|
141
|
+
),
|
|
142
|
+
)
|
|
143
|
+
item_id = stable_item_id(source.framework, run_id, "tunnel-failure-answer")
|
|
144
|
+
yield ItemStarted(
|
|
145
|
+
**envelope("item.started", item_id),
|
|
146
|
+
item_id=item_id,
|
|
147
|
+
item_kind="message",
|
|
148
|
+
phase="final_answer",
|
|
149
|
+
)
|
|
150
|
+
yield ItemCompleted(
|
|
151
|
+
**envelope("item.completed", item_id),
|
|
152
|
+
item_id=item_id,
|
|
153
|
+
item_kind="message",
|
|
154
|
+
snapshot=ContentSnapshot(parts=(TextContent(part_id="answer", text=failure.message),)),
|
|
155
|
+
)
|
|
156
|
+
completed = RunCompleted(
|
|
157
|
+
**envelope("run.completed", "run"),
|
|
158
|
+
status="completed",
|
|
159
|
+
output_refs=(OutputRef(scope_id=scope_id, item_id=item_id),),
|
|
160
|
+
)
|
|
161
|
+
if source.framework == "langgraph":
|
|
162
|
+
from ksadk.events.native_checkpoint import NativeCheckpointCompleted
|
|
163
|
+
|
|
164
|
+
# The notification completed; the failed graph did not reach a native
|
|
165
|
+
# terminal snapshot. Never expose its pending tool task as resumable.
|
|
166
|
+
completed = NativeCheckpointCompleted(**completed.model_dump())
|
|
167
|
+
completed._checkpoint_error = True
|
|
168
|
+
yield completed
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""Cloud-side tool operations over the Connector's streaming HTTP transport."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from http import HTTPStatus
|
|
7
|
+
|
|
8
|
+
# The transport, response streams and MCP client must use the same backend,
|
|
9
|
+
# even when both httpx packages are installed in a legacy MCP environment.
|
|
10
|
+
from ksadk._mcp_compat import httpx_module
|
|
11
|
+
|
|
12
|
+
httpx = httpx_module()
|
|
13
|
+
from mcp import ClientSession
|
|
14
|
+
from mcp.types import CallToolResult, TextContent
|
|
15
|
+
|
|
16
|
+
from ksadk._mcp_compat import field, list_tools_page
|
|
17
|
+
from ksadk._mcp_compat import streamable_http
|
|
18
|
+
|
|
19
|
+
from .protocol import TunnelError
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TunnelTransport(httpx.AsyncBaseTransport):
|
|
23
|
+
def __init__(self, connection, service):
|
|
24
|
+
self.connection = connection
|
|
25
|
+
self.service = service
|
|
26
|
+
|
|
27
|
+
async def handle_async_request(self, request):
|
|
28
|
+
return await self.connection.forward(self.service, request)
|
|
29
|
+
|
|
30
|
+
def client(self, headers=None, timeout=None, auth=None):
|
|
31
|
+
return httpx.AsyncClient(transport=self, headers=headers, timeout=timeout, auth=auth)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def api_operation(transport, descriptor, name, arguments):
|
|
35
|
+
tools = descriptor["tools"]
|
|
36
|
+
if name is None:
|
|
37
|
+
return {"tools": tools}
|
|
38
|
+
if name not in {tool["name"] for tool in tools}:
|
|
39
|
+
raise TunnelError("forbidden")
|
|
40
|
+
async with transport.client() as client:
|
|
41
|
+
response = await client.post(f"http://tunnel/{name}", json=arguments)
|
|
42
|
+
status = response.status_code
|
|
43
|
+
if (
|
|
44
|
+
response.is_client_error
|
|
45
|
+
and status in HTTPStatus
|
|
46
|
+
and status != HTTPStatus.REQUEST_TIMEOUT
|
|
47
|
+
):
|
|
48
|
+
# A completed client-error response reaches the model as a tool result.
|
|
49
|
+
# Error bodies can contain internal diagnostics and credentials.
|
|
50
|
+
return CallToolResult(
|
|
51
|
+
isError=True,
|
|
52
|
+
content=[
|
|
53
|
+
TextContent(type="text", text=f"HTTP {status} {HTTPStatus(status).phrase}")
|
|
54
|
+
],
|
|
55
|
+
structuredContent={"status_code": status},
|
|
56
|
+
).model_dump(by_alias=True, mode="json", exclude_none=True)
|
|
57
|
+
response.raise_for_status()
|
|
58
|
+
media_type = response.headers.get("content-type", "").partition(";")[0].lower()
|
|
59
|
+
value = None
|
|
60
|
+
if response.content and (media_type == "application/json" or media_type.endswith("+json")):
|
|
61
|
+
value = json.loads(response.content)
|
|
62
|
+
return CallToolResult(
|
|
63
|
+
content=[TextContent(type="text", text=response.text)] if response.content else [],
|
|
64
|
+
structuredContent=value if isinstance(value, dict) else None,
|
|
65
|
+
).model_dump(by_alias=True, mode="json", exclude_none=True)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
async def mcp_operation(transport, descriptor, name, arguments):
|
|
69
|
+
allowed = descriptor.get("tool_filter")
|
|
70
|
+
if name is not None and allowed is not None and name not in allowed:
|
|
71
|
+
raise TunnelError("forbidden")
|
|
72
|
+
limits = transport.connection.limits
|
|
73
|
+
async with (
|
|
74
|
+
streamable_http(
|
|
75
|
+
"http://tunnel/", httpx_client_factory=transport.client, timeout=limits.request_timeout
|
|
76
|
+
) as (read, write),
|
|
77
|
+
ClientSession(read, write) as session,
|
|
78
|
+
):
|
|
79
|
+
await session.initialize()
|
|
80
|
+
if name is not None:
|
|
81
|
+
result = await session.call_tool(name, arguments)
|
|
82
|
+
return result.model_dump(by_alias=True, mode="json", exclude_none=True)
|
|
83
|
+
tools, cursors = [], set()
|
|
84
|
+
cursor = None
|
|
85
|
+
while True:
|
|
86
|
+
page = await list_tools_page(session, cursor)
|
|
87
|
+
tools.extend(page.tools)
|
|
88
|
+
cursor = field(page, "next_cursor", "nextCursor")
|
|
89
|
+
if len(tools) > limits.max_tools or cursor in cursors:
|
|
90
|
+
raise ValueError("invalid MCP catalog")
|
|
91
|
+
if not cursor:
|
|
92
|
+
break
|
|
93
|
+
cursors.add(cursor)
|
|
94
|
+
return {
|
|
95
|
+
"tools": [
|
|
96
|
+
t.model_dump(by_alias=True, mode="json", exclude_none=True)
|
|
97
|
+
for t in tools
|
|
98
|
+
if allowed is None or t.name in allowed
|
|
99
|
+
]
|
|
100
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Explicit LangGraph tools with serializable discovery snapshots and no ADK imports."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from ksadk._mcp_compat import tool_input_schema
|
|
6
|
+
|
|
7
|
+
import json
|
|
8
|
+
|
|
9
|
+
from langchain_core.messages import ToolMessage
|
|
10
|
+
from langchain_core.tools import BaseTool
|
|
11
|
+
from mcp.types import Tool
|
|
12
|
+
from pydantic import PrivateAttr
|
|
13
|
+
|
|
14
|
+
from .discovery import TunnelToolHandle, discover_tools
|
|
15
|
+
from .protocol import TunnelError, identifier
|
|
16
|
+
from .registry import TunnelRegistry
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class _TunnelLangChainTool(BaseTool):
|
|
20
|
+
"""Keep native tool callbacks and MCP error/artifact semantics together."""
|
|
21
|
+
|
|
22
|
+
_handle: TunnelToolHandle = PrivateAttr()
|
|
23
|
+
|
|
24
|
+
def __init__(self, handle: TunnelToolHandle):
|
|
25
|
+
super().__init__(
|
|
26
|
+
name=handle.name,
|
|
27
|
+
description=handle.descriptor.description or "",
|
|
28
|
+
args_schema=tool_input_schema(handle.descriptor),
|
|
29
|
+
)
|
|
30
|
+
self._handle = handle
|
|
31
|
+
|
|
32
|
+
def _to_args_and_kwargs(self, tool_input, tool_call_id):
|
|
33
|
+
_, arguments = super()._to_args_and_kwargs(tool_input, tool_call_id)
|
|
34
|
+
# Pass the native ToolCall identity outside the MCP argument namespace.
|
|
35
|
+
return (arguments, tool_call_id), {}
|
|
36
|
+
|
|
37
|
+
def _run(self, *args, **kwargs):
|
|
38
|
+
raise NotImplementedError("MCP tunnel tools require async ainvoke")
|
|
39
|
+
|
|
40
|
+
async def _arun(self, arguments, call_id):
|
|
41
|
+
result = await self._handle.call(arguments)
|
|
42
|
+
if call_id is None:
|
|
43
|
+
return result
|
|
44
|
+
return ToolMessage(
|
|
45
|
+
name=self.name,
|
|
46
|
+
tool_call_id=call_id,
|
|
47
|
+
content=json.dumps(result, ensure_ascii=False),
|
|
48
|
+
artifact=result,
|
|
49
|
+
status="error" if result.get("isError") else "success",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class TunnelTools:
|
|
54
|
+
"""App-owned tools for model and ToolNode integration in caller-owned graphs.
|
|
55
|
+
|
|
56
|
+
A model node calls ``catalog = await tunnel_tools.discover()`` and saves
|
|
57
|
+
that JSON catalog in graph state alongside its AIMessage. Bind tools from
|
|
58
|
+
``await tunnel_tools.get_tools(catalog)`` in the model node, and pass tools
|
|
59
|
+
from that same catalog to the execution node. This preserves the original
|
|
60
|
+
connector generation between model selection and execution. No clients,
|
|
61
|
+
closures or credentials enter graph state; never cache a catalog across turns.
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
def __init__(self, agent_id: str, registry: TunnelRegistry):
|
|
65
|
+
self.agent_id = identifier(agent_id, "agent_id")
|
|
66
|
+
self._registry = registry
|
|
67
|
+
|
|
68
|
+
async def discover(self) -> list[dict]:
|
|
69
|
+
return [tool.snapshot() for tool in await discover_tools(self.agent_id, self._registry)]
|
|
70
|
+
|
|
71
|
+
def _handles(self, catalog: list[dict]) -> list[TunnelToolHandle]:
|
|
72
|
+
if not isinstance(catalog, list):
|
|
73
|
+
raise ValueError("tunnel catalog must be a list")
|
|
74
|
+
handles, names = [], set()
|
|
75
|
+
for entry in catalog:
|
|
76
|
+
if not isinstance(entry, dict) or set(entry) - {"owner"} != {
|
|
77
|
+
"name",
|
|
78
|
+
"service",
|
|
79
|
+
"connector_id",
|
|
80
|
+
"tool",
|
|
81
|
+
}:
|
|
82
|
+
raise ValueError("invalid tunnel catalog entry")
|
|
83
|
+
handle = TunnelToolHandle(
|
|
84
|
+
self.agent_id,
|
|
85
|
+
identifier(entry["service"], "service"),
|
|
86
|
+
identifier(entry["connector_id"], "connector_id"),
|
|
87
|
+
Tool.model_validate(entry["tool"]),
|
|
88
|
+
self._registry,
|
|
89
|
+
entry.get("owner"),
|
|
90
|
+
)
|
|
91
|
+
if handle.owner is not None:
|
|
92
|
+
from .peers import validate_owner
|
|
93
|
+
|
|
94
|
+
validate_owner(handle.owner)
|
|
95
|
+
if handle.name != entry["name"] or handle.name in names:
|
|
96
|
+
raise ValueError("invalid or duplicate tunnel tool name")
|
|
97
|
+
names.add(handle.name)
|
|
98
|
+
handles.append(handle)
|
|
99
|
+
return handles
|
|
100
|
+
|
|
101
|
+
def model_tools(self, catalog: list[dict]) -> list[dict]:
|
|
102
|
+
return [
|
|
103
|
+
{
|
|
104
|
+
"type": "function",
|
|
105
|
+
"function": {
|
|
106
|
+
"name": tool.name,
|
|
107
|
+
"description": tool.descriptor.description or "",
|
|
108
|
+
"parameters": tool_input_schema(tool.descriptor),
|
|
109
|
+
},
|
|
110
|
+
}
|
|
111
|
+
for tool in self._handles(catalog)
|
|
112
|
+
]
|
|
113
|
+
|
|
114
|
+
async def call_tool(self, catalog: list[dict], name: str, arguments: dict) -> dict:
|
|
115
|
+
for tool in self._handles(catalog):
|
|
116
|
+
if tool.name == name:
|
|
117
|
+
return await tool.call(arguments)
|
|
118
|
+
raise TunnelError("tool_unavailable")
|
|
119
|
+
|
|
120
|
+
async def get_tools(self, catalog: list[dict] | None = None) -> list[BaseTool]:
|
|
121
|
+
"""Return LangChain tools; absent catalog discovers current online tools."""
|
|
122
|
+
if catalog is None:
|
|
123
|
+
catalog = await self.discover()
|
|
124
|
+
|
|
125
|
+
return [_TunnelLangChainTool(tool) for tool in self._handles(catalog)]
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
"""LangChain create_agent middleware for dynamically registered tunnel tools."""
|
|
2
|
+
|
|
3
|
+
from langchain.agents import AgentState
|
|
4
|
+
from langchain.agents.middleware import AgentMiddleware
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class _TunnelState(AgentState):
|
|
8
|
+
tunnel_catalog: list[dict]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class TunnelMiddleware(AgentMiddleware):
|
|
12
|
+
state_schema = _TunnelState
|
|
13
|
+
|
|
14
|
+
def __init__(self, tunnel_tools):
|
|
15
|
+
self.tunnel_tools = tunnel_tools
|
|
16
|
+
|
|
17
|
+
async def abefore_model(self, state, runtime):
|
|
18
|
+
return {"tunnel_catalog": await self.tunnel_tools.discover()}
|
|
19
|
+
|
|
20
|
+
async def awrap_model_call(self, request, handler):
|
|
21
|
+
tools = await self.tunnel_tools.get_tools(request.state["tunnel_catalog"])
|
|
22
|
+
return await handler(request.override(tools=[*request.tools, *tools]))
|
|
23
|
+
|
|
24
|
+
async def awrap_tool_call(self, request, handler):
|
|
25
|
+
for tool in await self.tunnel_tools.get_tools(request.state["tunnel_catalog"]):
|
|
26
|
+
if tool.name == request.tool_call["name"]:
|
|
27
|
+
return await handler(request.override(tool=tool))
|
|
28
|
+
return await handler(request)
|