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
@@ -2,6 +2,7 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from ksadk.harness.service_runtime import HarnessServiceRuntimeAdapter
5
6
  from ksadk.interaction.contracts import InteractionRecord, InteractionSubmission
6
7
  from ksadk.interaction.provider import InteractionResolveContext, require_capability
7
8
  from ksadk.runtime.adapter import CancelResult, ResumePayload, ResumeTarget, RunHandle
@@ -20,9 +21,13 @@ class HarnessInteractionProvider:
20
21
  require_capability(context, "resume", provider_id=self.provider_id)
21
22
  require_capability(context, "submit_interaction", provider_id=self.provider_id)
22
23
  native_target = record.native_target or {}
23
- thread_id = str(native_target.get("thread_id") or "")
24
- if not thread_id or thread_id != context.handle.native_ref.get("thread_id"):
25
- raise ValueError("Harness interaction must target its original checkpoint thread")
24
+ if isinstance(context.adapter, HarnessServiceRuntimeAdapter):
25
+ target = ResumeTarget(kind="invocation_id", id=context.handle.run_id)
26
+ else:
27
+ thread_id = str(native_target.get("thread_id") or "")
28
+ if not thread_id or thread_id != context.handle.native_ref.get("thread_id"):
29
+ raise ValueError("Harness interaction must target its original checkpoint thread")
30
+ target = ResumeTarget(kind="thread_id", id=thread_id)
26
31
  if submission.action == "cancel":
27
32
  require_capability(context, "cancel", provider_id=self.provider_id)
28
33
  result = await context.adapter.cancel(context.handle)
@@ -40,7 +45,7 @@ class HarnessInteractionProvider:
40
45
  raise ValueError("Harness approval requires an explicit approve or reject decision")
41
46
  return await context.adapter.resume(
42
47
  context.handle,
43
- ResumeTarget(kind="thread_id", id=thread_id),
48
+ target,
44
49
  ResumePayload(
45
50
  kind="approval_decision" if record.kind == "approval" else "hitl_answer",
46
51
  call_id=str(native_target.get("call_id") or record.interaction_id),
ksadk/kernel/ingress.py CHANGED
@@ -983,32 +983,42 @@ def _build_kernel_router() -> Any:
983
983
  session_id, trusted=trusted, after_seq=after_seq,
984
984
  should_stop=_client_disconnected, timeout=subscribe_timeout,
985
985
  )
986
- async for item in with_heartbeats(source, seconds=heartbeat_seconds()):
987
- if item is None:
986
+ frames = with_heartbeats(source, seconds=heartbeat_seconds())
987
+ try:
988
+ async for item in frames:
988
989
  if hosted_stream:
989
- # Heartbeats do not extend a permit's authorization.
990
- await verifier.verify(trusted.permit, subscription,
991
- "subscribe_events", kernel._clock())
992
- yield ": heartbeat\n\n"
993
- continue
994
- seq, envelope = item
995
-
996
- payload = (
997
- envelope.payload
998
- if isinstance(envelope, dict)
999
- else getattr(envelope, "payload", {})
1000
- ) or {}
1001
- # SSE 消费方(gateway / hosted UI)需要 family/event_type/seq
1002
- # 判别事件流类别,payload 原样内嵌。
1003
- frame = dict(payload)
1004
- frame.setdefault("seq", seq)
1005
- if not isinstance(envelope, dict):
1006
- frame.setdefault("family", getattr(envelope, "family", None))
1007
- frame.setdefault("family_version", getattr(envelope, "family_version", None))
1008
- frame.setdefault("event_type", getattr(envelope, "event_type", None))
1009
- if getattr(envelope, "run_id", None):
1010
- frame.setdefault("run_id", envelope.run_id)
1011
- yield f"id: {seq}\ndata: {json.dumps(frame, ensure_ascii=False)}\n\n"
990
+ try:
991
+ # Neither traffic nor heartbeats extend authority.
992
+ await verifier.verify(trusted.permit, subscription,
993
+ "subscribe_events", kernel._clock())
994
+ except PermitExpiredError:
995
+ # End this read normally. Server/client renews the
996
+ # permit and resumes from its last delivered seq;
997
+ # the durable task and its worker keep running.
998
+ return
999
+ if item is None:
1000
+ yield ": heartbeat\n\n"
1001
+ continue
1002
+ seq, envelope = item
1003
+
1004
+ payload = (
1005
+ envelope.payload
1006
+ if isinstance(envelope, dict)
1007
+ else getattr(envelope, "payload", {})
1008
+ ) or {}
1009
+ # SSE 消费方(gateway / hosted UI)需要 family/event_type/seq
1010
+ # 判别事件流类别,payload 原样内嵌。
1011
+ frame = dict(payload)
1012
+ frame.setdefault("seq", seq)
1013
+ if not isinstance(envelope, dict):
1014
+ frame.setdefault("family", getattr(envelope, "family", None))
1015
+ frame.setdefault("family_version", getattr(envelope, "family_version", None))
1016
+ frame.setdefault("event_type", getattr(envelope, "event_type", None))
1017
+ if getattr(envelope, "run_id", None):
1018
+ frame.setdefault("run_id", envelope.run_id)
1019
+ yield f"id: {seq}\ndata: {json.dumps(frame, ensure_ascii=False)}\n\n"
1020
+ finally:
1021
+ await frames.aclose()
1012
1022
 
1013
1023
  return StreamingResponse(
1014
1024
  generator(), media_type="text/event-stream", headers=response_headers
ksadk/kernel/worker.py CHANGED
@@ -614,7 +614,7 @@ class AgentKernelWorker(WorkerInteractionMixin, WorkerControlMixin):
614
614
  }
615
615
  if approval_mode in approval_overrides:
616
616
  request_config["approval_mode"] = approval_overrides[approval_mode]
617
- effective_user_id, invocation_identity = await prepare_worker_identity(
617
+ effective_user_id, invocation_identity, session_agent_id = await prepare_worker_identity(
618
618
  command=command,
619
619
  defaults=defaults,
620
620
  session_service=self._session_service,
@@ -644,7 +644,7 @@ class AgentKernelWorker(WorkerInteractionMixin, WorkerControlMixin):
644
644
  input=command.payload.get("content"),
645
645
  user_id=effective_user_id,
646
646
  session_id=command.session_id,
647
- agent_id=str(defaults.get("agent_id") or command.agent_instance_id),
647
+ agent_id=session_agent_id,
648
648
  model=selected_model,
649
649
  config=request_config,
650
650
  # durable run_id 优先传给 adapter;adapter 不认时以
@@ -15,9 +15,10 @@ async def prepare_worker_identity(
15
15
  command: AgentControlCommand,
16
16
  defaults: Mapping[str, object],
17
17
  session_service: object | None,
18
- ) -> tuple[str, Mapping[str, Any] | None]:
19
- """Resolve the storage user and retain only an admitted identity payload."""
18
+ ) -> tuple[str, Mapping[str, Any] | None, str]:
19
+ """Resolve storage user, admitted identity and Agent from one owner snapshot."""
20
20
 
21
+ fallback_agent_id = str(defaults.get("agent_id") or command.agent_instance_id)
21
22
  invocation_identity = command.payload.get("invocation_identity")
22
23
  effective_user_id = str(command.tenant_id or "agent-kernel")
23
24
  if command.payload.get("teams_context_ref") is not None:
@@ -34,11 +35,12 @@ async def prepare_worker_identity(
34
35
  raise ValueError("prepared Teams session owner is unavailable")
35
36
  return existing.user_id, (
36
37
  invocation_identity if isinstance(invocation_identity, Mapping) else None
37
- )
38
+ ), fallback_agent_id
38
39
  if not isinstance(invocation_identity, Mapping):
39
40
  existing = (
40
41
  await session_service.get_session_metadata(command.session_id)
41
- if session_service is not None else None
42
+ if session_service is not None
43
+ else None
42
44
  )
43
45
  if existing is not None:
44
46
  # Kernel ingress has authorized this exact session/instance. Tenant
@@ -47,10 +49,10 @@ async def prepare_worker_identity(
47
49
  agent_id = str(defaults.get("agent_id") or command.agent_instance_id)
48
50
  if existing.agent_id != agent_id or not existing.user_id:
49
51
  raise ValueError("prepared session Agent differs from the Kernel Build")
50
- return existing.user_id, None
51
- return effective_user_id, None
52
+ return existing.user_id, None, fallback_agent_id
53
+ return effective_user_id, None, fallback_agent_id
52
54
  if session_service is None:
53
- return identity_native_user_id(invocation_identity), invocation_identity
55
+ return identity_native_user_id(invocation_identity), invocation_identity, fallback_agent_id
54
56
 
55
57
  # Hosted runtimes have two stable identifiers: the platform deployment
56
58
  # instance (used by the Kernel command) and the public AgentId used by
@@ -71,4 +73,9 @@ async def prepare_worker_identity(
71
73
  invocation_identity=invocation_identity,
72
74
  allow_agent_alias=True,
73
75
  )
74
- return canonical_session.user_id, invocation_identity
76
+ # Use the same owner snapshot we just authorized; do not look up the
77
+ # session again after a concurrent deletion/recreation could replace it.
78
+ resolved_agent_id = (
79
+ canonical_session.agent_id if command.source.kind == "agui" else fallback_agent_id
80
+ )
81
+ return canonical_session.user_id, invocation_identity, resolved_agent_id
@@ -44,7 +44,11 @@ from typing import Any, List, Optional
44
44
  from pydantic import BaseModel, ConfigDict, Field, field_validator
45
45
 
46
46
  from ksadk.common.aicp_env import resolve_aicp_connection
47
- from ksadk.common.cloud_headers import build_cloud_headers, resolve_traffic_source
47
+ from ksadk.common.cloud_headers import (
48
+ build_component_headers,
49
+ resolve_component_env,
50
+ resolve_traffic_source,
51
+ )
48
52
 
49
53
  logger = logging.getLogger(__name__)
50
54
 
@@ -94,6 +98,7 @@ class KnowledgeBaseClient(BaseModel):
94
98
  secret_key: str = ""
95
99
  session_token: str = ""
96
100
  traffic_source: str = Field(default_factory=resolve_traffic_source)
101
+ component_env: str = Field(default_factory=resolve_component_env)
97
102
  region: str = "cn-beijing-6"
98
103
  endpoint: str = "aicp.api.ksyun.com"
99
104
  scheme: str = "https"
@@ -198,8 +203,10 @@ class KnowledgeBaseClient(BaseModel):
198
203
  class ObservedAicpClient(aicp_module.AicpClient):
199
204
  def call(self, action, params, options=None):
200
205
  options = dict(options or {})
201
- options["CustomHeaders"] = build_cloud_headers(
202
- options.get("CustomHeaders"), traffic_source=owner.traffic_source
206
+ options["CustomHeaders"] = build_component_headers(
207
+ options.get("CustomHeaders"),
208
+ traffic_source=owner.traffic_source,
209
+ component_env=owner.component_env,
203
210
  )
204
211
  return super().call(action, params, options)
205
212
 
@@ -22,6 +22,8 @@ If an operation is rejected, stop that operation. Never claim success for a fail
22
22
 
23
23
  class _State(McpOAuthState):
24
24
  mcp_call_count: int
25
+ mcp_tunnel_catalog: list[dict]
26
+ mcp_tunnel_unknown: bool
25
27
 
26
28
 
27
29
  class _Agent:
@@ -34,6 +36,7 @@ class _Agent:
34
36
  if not isinstance(prompt, str):
35
37
  raise ValueError("system_prompt must be a string")
36
38
  self.model, self.prompt, self.limit = model, prompt, limit
39
+ self.tunnel_tools = None
37
40
  self.tools = {}
38
41
  for tool in tools:
39
42
  if not isinstance(tool, BaseTool) or tool.name in self.tools:
@@ -43,13 +46,21 @@ class _Agent:
43
46
  raise ValueError("MCP connection tool name collision")
44
47
 
45
48
  def begin(self, state):
46
- return {**self.oauth.reset(state), "mcp_call_count": 0}
49
+ update = {**self.oauth.reset(state), "mcp_call_count": 0}
50
+ if self.tunnel_tools is not None:
51
+ update.update(mcp_tunnel_catalog=[], mcp_tunnel_unknown=False)
52
+ return update
47
53
 
48
54
  async def chat(self, state, config: RunnableConfig):
49
55
  oauth_tools = self.oauth.model_tools(state)
50
- if {t["function"]["name"] for t in oauth_tools} & self.tools.keys():
56
+ tunnel_catalog = await self.tunnel_tools.discover() if self.tunnel_tools is not None else []
57
+ tunnel_tools = (
58
+ self.tunnel_tools.model_tools(tunnel_catalog) if self.tunnel_tools is not None else []
59
+ )
60
+ names = [*self.tools, *(t["function"]["name"] for t in [*oauth_tools, *tunnel_tools])]
61
+ if len(names) != len(set(names)):
51
62
  raise BrokerError("MCP_TOOL_NAME_COLLISION")
52
- definitions: list[Any] = [*self.tools.values(), *oauth_tools]
63
+ definitions: list[Any] = [*self.tools.values(), *oauth_tools, *tunnel_tools]
53
64
  runnable = self.model.bind_tools(definitions) if definitions else self.model
54
65
  response = await runnable.ainvoke(
55
66
  [SystemMessage(content=self.prompt + "\n\n" + _GUIDANCE), *state["messages"]],
@@ -70,7 +81,10 @@ class _Agent:
70
81
  }
71
82
  if any(not value for value in ids) or len(set(ids)) != len(ids) or set(ids) & prior_ids:
72
83
  raise BrokerError("MCP_MODEL_TOOL_CALL_ID_INVALID")
73
- return {"messages": [response]}
84
+ update = {"messages": [response]}
85
+ if self.tunnel_tools is not None:
86
+ update["mcp_tunnel_catalog"] = tunnel_catalog
87
+ return update
74
88
 
75
89
  async def execute(self, state, config: RunnableConfig):
76
90
  call = _pending(state)
@@ -81,6 +95,32 @@ class _Agent:
81
95
  # Preserve the caller's existing LangChain tool implementation.
82
96
  update["messages"] = [await self.tools[call["name"]].ainvoke(call, config=config)]
83
97
  return update
98
+ selected = next(
99
+ (
100
+ entry
101
+ for entry in state.get("mcp_tunnel_catalog", [])
102
+ if entry["name"] == call["name"]
103
+ ),
104
+ None,
105
+ )
106
+ if self.tunnel_tools is not None and selected is not None:
107
+ from ksadk.tunnel.protocol import TunnelError
108
+
109
+ try:
110
+ # Use the same callback path as ordinary tools for the runtime timeline.
111
+ (tool,) = await self.tunnel_tools.get_tools([selected])
112
+ update["messages"] = [await tool.ainvoke(call, config=config)]
113
+ except TunnelError as exc:
114
+ update["messages"] = [
115
+ _reply(
116
+ call, {"error": exc.code, "indeterminate": exc.indeterminate}, error=True
117
+ )
118
+ ]
119
+ if exc.indeterminate:
120
+ # Do not let a model turn an unknown result into an
121
+ # automatic second attempt of a potentially completed call.
122
+ update.update(mcp_stop=True, mcp_tunnel_unknown=True)
123
+ return update
84
124
  if self.oauth.owns(call, state):
85
125
  return {**update, **await self.oauth.execute(state, config)}
86
126
  update["messages"] = [_reply(call, {"error": "MCP_TOOL_UNAVAILABLE"}, error=True)]
@@ -98,9 +138,13 @@ class _Agent:
98
138
  @staticmethod
99
139
  def finish(state):
100
140
  message = (
101
- "已按你的决定停止本次操作。"
102
- if state.get("mcp_stop")
103
- else "已达到本次工具调用上限,请缩小任务范围后重试。"
141
+ "工具调用结果未知,已停止本次操作。请先查询业务状态,再决定是否重新执行。"
142
+ if state.get("mcp_tunnel_unknown")
143
+ else (
144
+ "已按你的决定停止本次操作。"
145
+ if state.get("mcp_stop")
146
+ else "已达到本次工具调用上限,请缩小任务范围后重试。"
147
+ )
104
148
  )
105
149
  messages, working = [], dict(state)
106
150
  while call := _pending(working):
@@ -130,6 +174,11 @@ def build_agent(
130
174
  max_tool_calls,
131
175
  execution_policies,
132
176
  )
177
+ return _compile_agent(agent, checkpointer=checkpointer)
178
+
179
+
180
+ def _compile_agent(agent, *, checkpointer, template=None):
181
+ """Rebuild SDK nodes around an isolated agent; preserve graph-owned storage."""
133
182
  graph = StateGraph(_State)
134
183
  graph.add_node("begin", agent.begin)
135
184
  graph.add_node("chat", agent.chat)
@@ -140,8 +189,27 @@ def build_agent(
140
189
  graph.add_conditional_edges("chat", agent.after_chat)
141
190
  graph.add_conditional_edges("tools", agent.after_tool)
142
191
  graph.add_edge("finish", END)
143
- compiled = graph.compile(checkpointer=checkpointer).with_config(
144
- {"recursion_limit": 2 * max_tool_calls + 8}
192
+ compile_options = {}
193
+ if template is not None:
194
+ compile_options = {
195
+ "store": template.store,
196
+ "cache": template.cache,
197
+ "interrupt_before": template.interrupt_before_nodes,
198
+ "interrupt_after": template.interrupt_after_nodes,
199
+ "debug": template.debug,
200
+ "name": template.name,
201
+ }
202
+ compiled = graph.compile(checkpointer=checkpointer, **compile_options).with_config(
203
+ {"recursion_limit": 2 * agent.limit + 8, **dict(getattr(template, "config", None) or {})}
145
204
  )
146
205
  graph._ksadk_mcp_agent = agent
147
206
  return compiled
207
+
208
+
209
+ def bind_tunnel_graph(graph, tunnel_tools, *, checkpointer):
210
+ """Copy SDK graph behavior, never mutate the imported graph's closures."""
211
+ from copy import copy
212
+
213
+ agent = copy(graph.builder._ksadk_mcp_agent)
214
+ agent.tunnel_tools = tunnel_tools
215
+ return _compile_agent(agent, checkpointer=checkpointer, template=graph)
@@ -8,6 +8,8 @@ from .client import BrokerError, MCPToolOutcomeUnknown
8
8
 
9
9
  SCHEMA = "mcp.authorization/v1"
10
10
  MARKER = "x-ksadk-mcp-authorization"
11
+
12
+ from ksadk._mcp_compat import tool_input_schema # noqa: E402
11
13
  _declaration = ContextVar("mcp_oauth_declaration", default=None)
12
14
  _extension = ContextVar("mcp_oauth_extension", default=None)
13
15
 
@@ -92,13 +94,14 @@ def classify_mcp_error(error):
92
94
  if isinstance(error, BrokerError):
93
95
  return error.code
94
96
  import httpx
97
+ from ksadk._mcp_compat import httpx_module
95
98
 
96
99
  children = getattr(error, "exceptions", ())
97
100
  for child in children:
98
101
  code = classify_mcp_error(child)
99
102
  if code != "CONNECTION_FAILED":
100
103
  return code
101
- if isinstance(error, httpx.HTTPStatusError):
104
+ if isinstance(error, (httpx.HTTPStatusError, httpx_module().HTTPStatusError)):
102
105
  challenge = error.response.headers.get("WWW-Authenticate", "")
103
106
  if error.response.status_code == 403:
104
107
  return (
@@ -114,18 +117,43 @@ def classify_mcp_error(error):
114
117
  @asynccontextmanager
115
118
  async def connect(credential):
116
119
  from mcp import ClientSession
117
- from mcp.client.streamable_http import streamablehttp_client
118
120
 
121
+ from ksadk._mcp_compat import streamable_http
119
122
  from .transport import http_client_factory
120
123
 
121
- async with streamablehttp_client(
122
- credential["resource"],
123
- headers={"Authorization": "Bearer " + credential["access_token"]},
124
- httpx_client_factory=http_client_factory(credential),
125
- ) as (read, write, _):
126
- async with ClientSession(read, write) as session:
127
- await session.initialize()
128
- yield session
124
+ authorization_error = None
125
+
126
+ async def remember_authorization_error(response):
127
+ nonlocal authorization_error
128
+ # MCP 2 replaces non-JSON-RPC HTTP errors with a generic MCPError.
129
+ # Retain only the safe authorization category, never the token/body/URL.
130
+ # A background GET/DELETE denial is not proof a business POST declined.
131
+ if response.request.method != "POST":
132
+ return
133
+ if response.status_code == 401:
134
+ authorization_error = "REAUTHORIZATION_REQUIRED"
135
+ elif response.status_code == 403:
136
+ authorization_error = (
137
+ "INSUFFICIENT_SCOPE"
138
+ if "insufficient_scope" in response.headers.get("WWW-Authenticate", "")
139
+ else "BUSINESS_PERMISSION_DENIED"
140
+ )
141
+
142
+ async with http_client_factory(credential)(
143
+ headers={"Authorization": "Bearer " + credential["access_token"]}, timeout=30,
144
+ ) as http_client:
145
+ http_client.event_hooks["response"].append(remember_authorization_error)
146
+ try:
147
+ async with streamable_http(
148
+ credential["resource"], http_client=http_client,
149
+ ) as (read, write):
150
+ async with ClientSession(read, write) as session:
151
+ await session.initialize()
152
+ yield session
153
+ except Exception:
154
+ if authorization_error is not None:
155
+ raise BrokerError(authorization_error) from None
156
+ raise
129
157
 
130
158
 
131
159
  async def prepare_connection(client, wait_id):
@@ -202,17 +230,21 @@ async def _authorized_credential(
202
230
 
203
231
  async def _catalog(session, credential):
204
232
  """Read all catalog pages and apply the immutable connection filter."""
233
+ from ksadk._mcp_compat import list_tools_page
234
+
205
235
  allowed = credential.get("allowed_tools", [])
206
236
  tools, cursors = {}, set()
207
237
  cursor = None
208
238
  while True:
209
- page = await session.list_tools(cursor=cursor) if cursor else await session.list_tools()
239
+ # mcp 2.x 的 `list_tools` 不接受 `cursor` 关键字(改成
240
+ # `params=PaginatedRequestParams(cursor=...)`),用兼容层统一。
241
+ page = await list_tools_page(session, cursor)
210
242
  for tool in page.tools:
211
243
  if not allowed or tool.name in allowed:
212
244
  if tool.name in tools:
213
245
  raise BrokerError("MCP_TOOL_CATALOG_INVALID")
214
246
  tools[tool.name] = tool
215
- cursor = page.nextCursor
247
+ cursor = getattr(page, 'next_cursor', None) or getattr(page, 'nextCursor', None)
216
248
  if not cursor:
217
249
  return tools
218
250
  if cursor in cursors or len(cursors) >= 100:
@@ -275,7 +307,7 @@ async def list_mcp_tools(config_id: str, *, request_key: str):
275
307
  {
276
308
  "name": tool.name,
277
309
  "description": tool.description or "",
278
- "inputSchema": tool.inputSchema,
310
+ "inputSchema": tool_input_schema(tool),
279
311
  }
280
312
  for tool in tools.values()
281
313
  ]
@@ -318,12 +350,12 @@ async def call_mcp_tool(
318
350
  ):
319
351
  if tool not in catalog:
320
352
  raise BrokerError("MCP_TOOL_UNAVAILABLE")
321
- validate_input_schema(catalog[tool].inputSchema, arguments)
353
+ validate_input_schema(tool_input_schema(catalog[tool]), arguments)
322
354
  call_digest = digest([credential["config_ref"], tool, arguments])
323
355
  result = await extension.claim_dispatch(run_id, request_key, call_digest)
324
356
  if result is None:
325
357
  dispatched = True
326
- result = (await session.call_tool(tool, arguments)).model_dump(mode="json")
358
+ result = (await session.call_tool(tool, arguments)).model_dump(mode="json", by_alias=True)
327
359
  await extension.finish_dispatch(run_id, request_key, call_digest, result)
328
360
  except BrokerError as exc:
329
361
  if not dispatched:
@@ -131,7 +131,29 @@ class LocalBroker:
131
131
  if wait_id in self.data["waits"]:
132
132
  wait = self.wait(wait_id)
133
133
  self.vault.save()
134
- return {"status": "resume_wait"} if lookup else self.view(wait)
134
+ if not lookup:
135
+ return self.view(wait)
136
+ # ## `lookup=True` 不能无条件返回 `resume_wait`
137
+ #
138
+ # `_authorized_credential()` 只在 `status == "authorized"` 时
139
+ # 才跳过 `interrupt()`。若这里无条件返回 `resume_wait`,
140
+ # **每次都 interrupt**——consent 完成后 run 永远停在
141
+ # `RunState.WAITING`(实测 6 个用例卡死,`legacy_key_read`
142
+ # 被重复执行 3 次)。
143
+ #
144
+ # 正确语义:wait 已存在 ≠ 未授权。要按 grant 的实际状态判断,
145
+ # 已授权就直接返回 credential,让调用方走直连路径。
146
+ wait_config = self.config(wait)
147
+ wait_grant = self.data["grants"].get(wait["config_id"], {})
148
+ wait_ready = wait_grant.get("status") == "active" and not refresh_due(
149
+ wait_grant["expires"], wait_grant["tokens"], self.clock()
150
+ )
151
+ if wait_ready:
152
+ return {
153
+ "status": "authorized",
154
+ "credential": self._credential(wait_grant, wait_config),
155
+ }
156
+ return {"status": "resume_wait"}
135
157
  declaration = self.declarations.get(name) or declaration
136
158
  if declaration is None:
137
159
  raise BrokerError("MCP_CONFIGURATION_NOT_FOUND")
@@ -2,6 +2,8 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ from ksadk._mcp_compat import tool_input_schema
6
+
5
7
  import hashlib
6
8
  import json
7
9
  import re
@@ -200,10 +202,27 @@ class McpOAuthTools:
200
202
  return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
201
203
 
202
204
  def _tool_state(self, state):
205
+ """把 `ToolMessage.artifact` 里的 catalog 回填成 state 字段。
206
+
207
+ ## 为什么不能"显式 state 就早退"
208
+
209
+ `reset()` 会写入 `mcp_catalogs={}`(`begin` 节点每轮都跑),
210
+ 所以 `"mcp_catalogs" in state` **恒为真**。早退会让 artifact 里的
211
+ catalog **永远读不回来**,导致:
212
+
213
+ - `bindings()` 空 → `owns()` False → 已发现的 MCP 工具被错误路由到
214
+ 开发者的 legacy 分支
215
+ - 表现为**执行错工具** + **重复执行**(实测 `legacy_key_read`
216
+ 被调 3 次,应为 2 次)
217
+
218
+ ## 修法:合并而非早退
219
+
220
+ 显式 state 的 catalog **优先**(保持原 API 语义),artifact 作为补充。
221
+ """
203
222
  state = state if state is not None else {}
204
- if "mcp_catalogs" in state:
205
- return state # Preserve the original explicit-state API.
206
- catalogs, stopped = {}, False
223
+ catalogs = dict(state.get("mcp_catalogs") or {})
224
+ stopped_override = state.get("mcp_stop")
225
+ stopped = False if stopped_override is None else bool(stopped_override)
207
226
  turn = []
208
227
  for message in reversed(state.get("messages", [])):
209
228
  if isinstance(message, HumanMessage):
@@ -216,7 +235,9 @@ class McpOAuthTools:
216
235
  data = message.artifact.get(_CATALOG_ARTIFACT)
217
236
  if not isinstance(data, dict) or data.get("version") != 1 or data.get("scope") != scope:
218
237
  continue
219
- catalogs.update(data.get("catalogs", {}))
238
+ # 显式 state 优先;artifact 只补空缺的 connection。
239
+ for connection, catalog in data.get("catalogs", {}).items():
240
+ catalogs.setdefault(connection, catalog)
220
241
  stopped = stopped or data.get("stopped", False)
221
242
  return {**state, "mcp_catalogs": catalogs, "mcp_stop": stopped}
222
243
 
@@ -275,15 +296,32 @@ class McpOAuthTools:
275
296
  _function(
276
297
  alias,
277
298
  f"[{connection}] {tool['name']}: {tool['description']}",
278
- tool["inputSchema"],
299
+ tool_input_schema(tool),
279
300
  )
280
301
  )
281
302
  return definitions
282
303
 
283
304
  def owns(self, call, state):
284
- """Route only these OAuth calls to execute; leave all other tools alone."""
305
+ """Route only these OAuth calls to execute; leave all other tools alone.
306
+
307
+ ## 为什么必须先 `_tool_state`
308
+
309
+ 已发现的 catalog 存在 `ToolMessage.artifact` 里(不是 state 字段),
310
+ 只有 `_tool_state()` 会把它回填成 `state["mcp_catalogs"]`。
311
+
312
+ `route()` 传进来的是**原始 graph state**——`begin` 节点刚跑过
313
+ `reset()`,`mcp_catalogs` 是空的。若直接 `self.bindings(state)`,
314
+ 已发现的 MCP 工具(如 `research__read_snapshot`)会**不被认领**,
315
+ 被错误路由到开发者的 legacy 分支,导致**执行错工具**且
316
+ **重复执行**(checkpoint 里已有结果,却仍重跑一次)。
317
+
318
+ 实测(2026-11-19):`legacy_key_read` 被调用 3 次(应为 2 次)。
319
+ """
320
+ if not call:
321
+ return False
322
+ normalized = self._tool_state(state)
285
323
  return bool(
286
- call and (call["name"] in self.connectors or call["name"] in self.bindings(state))
324
+ call["name"] in self.connectors or call["name"] in self.bindings(normalized)
287
325
  )
288
326
 
289
327
  async def execute(self, state, config: RunnableConfig):
@@ -351,7 +389,7 @@ class McpOAuthTools:
351
389
  schema = (
352
390
  {"type": "object", "properties": {}}
353
391
  if connection is not None
354
- else binding[1]["inputSchema"]
392
+ else tool_input_schema(binding[1])
355
393
  )
356
394
  runnable = StructuredTool.from_function(
357
395
  coroutine=invoke,
@@ -5,8 +5,25 @@ import ipaddress
5
5
  import socket
6
6
  import ssl
7
7
 
8
- import httpcore
9
- import httpx
8
+ # ## 为什么是双库导入
9
+ #
10
+ # `mcp` **2.3.0** 换了 HTTP 底座:`httpx` → **`httpx2`**,
11
+ # `httpcore` → **`httpcore2`**(两个都是独立包,不是子类关系)。
12
+ #
13
+ # 本模块的安全保证(DNS pinning / origin 不可变 / 禁重定向)依赖
14
+ # `AsyncNetworkBackend` + `AsyncConnectionPool` 这两个**内部 API**——
15
+ # 必须和 `mcp` 用的是**同一套**,否则 `transport=` 传进
16
+ # `httpx2.AsyncClient` 会直接类型不匹配。
17
+ #
18
+ # `httpx2` / `httpcore2` 与旧版签名逐字兼容(`connect_tcp`、
19
+ # `AsyncConnectionPool.__init__` 实测一致),所以只需换导入。
20
+ from ksadk._mcp_compat import httpx_module
21
+
22
+ httpx = httpx_module()
23
+ if httpx.__name__ == "httpx2":
24
+ import httpcore2 as httpcore
25
+ else:
26
+ import httpcore # type: ignore[no-redef]
10
27
 
11
28
 
12
29
  class MCPNetworkBackend(httpcore.AsyncNetworkBackend):