google-agents-cli-extensions 1.14.2__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.
- core/claude/README.md +35 -0
- core/claude/template/.agents/skills/agents-cli-claude/SKILL.md +106 -0
- core/claude/template/.agents/skills/agents-cli-claude/references/claude.md +386 -0
- core/claude/template/.agents/skills/agents-cli-claude/references/migrate-claude-agent.md +318 -0
- core/claude/template/.agents/skills/agents-cli-claude/references/migrate-from-aws.md +132 -0
- core/claude/template/.dockerignore +28 -0
- core/claude/template/.env +18 -0
- core/claude/template/.env.example +17 -0
- core/claude/template/.template/templateconfig.yaml +31 -0
- core/claude/template/AGENTS.md +33 -0
- core/claude/template/Dockerfile +55 -0
- core/claude/template/agent_config/README.md +9 -0
- core/claude/template/agents-cli-extension.yaml +49 -0
- core/claude/template/app/__init__.py +15 -0
- core/claude/template/app/agent.py +49 -0
- core/claude/template/app/app_utils/a2a.py +245 -0
- core/claude/template/app/app_utils/bq_analytics/__init__.py +124 -0
- core/claude/template/app/app_utils/bq_analytics/recorder.py +593 -0
- core/claude/template/app/app_utils/bq_analytics/redaction.py +209 -0
- core/claude/template/app/app_utils/bq_analytics/schema.py +394 -0
- core/claude/template/app/app_utils/bq_analytics/tables.py +104 -0
- core/claude/template/app/app_utils/bq_analytics/uploader.py +188 -0
- core/claude/template/app/app_utils/claude.py +297 -0
- core/claude/template/app/app_utils/completions.py +225 -0
- core/claude/template/app/app_utils/conversation.py +29 -0
- core/claude/template/app/app_utils/memory_bank.py +308 -0
- core/claude/template/app/app_utils/project_settings.py +91 -0
- core/claude/template/app/app_utils/reasoning_engine.py +237 -0
- core/claude/template/app/app_utils/remote_agents.py +349 -0
- core/claude/template/app/app_utils/remote_auth.py +159 -0
- core/claude/template/app/app_utils/replies.py +143 -0
- core/claude/template/app/app_utils/session_store.py +174 -0
- core/claude/template/app/app_utils/settings.py +24 -0
- core/claude/template/app/app_utils/telemetry/__init__.py +114 -0
- core/claude/template/app/app_utils/telemetry/call_counts.py +44 -0
- core/claude/template/app/app_utils/telemetry/cli_relay.py +266 -0
- core/claude/template/app/app_utils/telemetry/config.py +133 -0
- core/claude/template/app/app_utils/telemetry/logs.py +175 -0
- core/claude/template/app/app_utils/telemetry/metrics.py +270 -0
- core/claude/template/app/app_utils/telemetry/request_flush.py +104 -0
- core/claude/template/app/app_utils/telemetry/subagent_spans.py +80 -0
- core/claude/template/app/app_utils/telemetry/traces.py +166 -0
- core/claude/template/app/app_utils/turn_events.py +463 -0
- core/claude/template/app/app_utils/turn_options.py +219 -0
- core/claude/template/app/app_utils/workspaces.py +65 -0
- core/claude/template/app/fast_api_app.py +71 -0
- core/claude/template/app/feature_tools.py +27 -0
- core/claude/template/pyproject.toml +100 -0
- core/claude/template/scripts/eval_generate.py +340 -0
- core/claude/template/scripts/publish.py +66 -0
- core/claude/template/scripts/run.py +85 -0
- core/claude/template/scripts/unsupported.py +48 -0
- core/claude/template/tests/eval/datasets/basic-dataset.json +31 -0
- core/claude/template/tests/eval/eval_config.yaml +17 -0
- core/claude/template/tests/eval/response_quality.py +60 -0
- core/claude/template/tests/integration/test_server_e2e.py +168 -0
- core/claude/template/tests/load_test/.results/.placeholder +0 -0
- core/claude/template/tests/load_test/README.md +24 -0
- core/claude/template/tests/load_test/load_test.py +118 -0
- core/claude/template/tests/unit/conftest.py +63 -0
- core/claude/template/tests/unit/helpers.py +32 -0
- core/claude/template/tests/unit/test_a2a.py +432 -0
- core/claude/template/tests/unit/test_bq_analytics.py +928 -0
- core/claude/template/tests/unit/test_bq_redaction.py +89 -0
- core/claude/template/tests/unit/test_claude.py +825 -0
- core/claude/template/tests/unit/test_completions.py +369 -0
- core/claude/template/tests/unit/test_fast_api_app.py +59 -0
- core/claude/template/tests/unit/test_feature_tools.py +55 -0
- core/claude/template/tests/unit/test_memory_bank.py +625 -0
- core/claude/template/tests/unit/test_reasoning_engine.py +295 -0
- core/claude/template/tests/unit/test_remote_agents.py +517 -0
- core/claude/template/tests/unit/test_telemetry.py +991 -0
- core/claude/template/tests/unit/test_turn_events.py +309 -0
- core/claude/template/tests/unit/test_turn_options.py +394 -0
- core/claude/template/uv.lock +3029 -0
- core/langchain/README.md +54 -0
- core/langchain/template/.agents/skills/agents-cli-langchain/SKILL.md +84 -0
- core/langchain/template/.agents/skills/agents-cli-langchain/references/langchain.md +120 -0
- core/langchain/template/.agents/skills/agents-cli-langchain/references/samples.md +42 -0
- core/langchain/template/.template/templateconfig.yaml +32 -0
- core/langchain/template/AGENTS.md +35 -0
- core/langchain/template/agents-cli-extension.yaml +54 -0
- core/langchain/template/app/__init__.py +19 -0
- core/langchain/template/app/agent.py +61 -0
- core/langchain/template/app/app_utils/a2a.py +176 -0
- core/langchain/template/app/app_utils/content.py +37 -0
- core/langchain/template/app/app_utils/telemetry.py +154 -0
- core/langchain/template/app/fast_api_app.py +68 -0
- core/langchain/template/langgraph.json +7 -0
- core/langchain/template/pyproject.toml +102 -0
- core/langchain/template/scripts/_content.py +40 -0
- core/langchain/template/scripts/eval_generate.py +202 -0
- core/langchain/template/scripts/publish.py +59 -0
- core/langchain/template/scripts/run.py +59 -0
- core/langchain/template/scripts/unsupported.py +48 -0
- core/langchain/template/tests/eval/datasets/basic-dataset.json +16 -0
- core/langchain/template/tests/eval/eval_config.yaml +32 -0
- core/langchain/template/tests/eval/response_quality.py +60 -0
- core/langchain/template/tests/integration/test_server_e2e.py +173 -0
- core/langchain/template/tests/load_test/.results/.placeholder +0 -0
- core/langchain/template/tests/load_test/README.md +20 -0
- core/langchain/template/tests/load_test/load_test.py +82 -0
- core/langchain/template/uv.lock +3820 -0
- google_agents_cli_extensions-1.14.2.dist-info/METADATA +133 -0
- google_agents_cli_extensions-1.14.2.dist-info/RECORD +107 -0
- google_agents_cli_extensions-1.14.2.dist-info/WHEEL +4 -0
- google_agents_cli_extensions-1.14.2.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Agent Runtime's `:query` and `:streamQuery` methods.
|
|
16
|
+
|
|
17
|
+
Agent Runtime forwards them to `/api/reasoning_engine` and
|
|
18
|
+
`/api/stream_reasoning_engine` with a `{"class_method": ..., "input": {...}}` body.
|
|
19
|
+
An ingress Agent Gateway governs only these two methods. They serve ADK's
|
|
20
|
+
`async_create_session` and `async_stream_query`, with ADK's inputs and events, so
|
|
21
|
+
ADK clients such as `agents-cli run --mode adk` work. A session id is a
|
|
22
|
+
conversation id.
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import json
|
|
28
|
+
import logging
|
|
29
|
+
import time
|
|
30
|
+
import uuid
|
|
31
|
+
from collections.abc import AsyncGenerator, AsyncIterator
|
|
32
|
+
from contextlib import aclosing
|
|
33
|
+
from typing import Any
|
|
34
|
+
|
|
35
|
+
from claude_agent_sdk import (
|
|
36
|
+
AssistantMessage,
|
|
37
|
+
Message,
|
|
38
|
+
ResultMessage,
|
|
39
|
+
TextBlock,
|
|
40
|
+
ToolResultBlock,
|
|
41
|
+
ToolUseBlock,
|
|
42
|
+
UserMessage,
|
|
43
|
+
)
|
|
44
|
+
from fastapi import FastAPI, HTTPException, Request, responses
|
|
45
|
+
from opentelemetry import trace
|
|
46
|
+
|
|
47
|
+
from app.agent import root_agent
|
|
48
|
+
from app.app_utils import memory_bank
|
|
49
|
+
from app.app_utils.claude import stream_turn
|
|
50
|
+
from app.app_utils.replies import result_error, tool_result_text
|
|
51
|
+
from app.app_utils.telemetry.config import agent_name, on_agent_runtime
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def add_reasoning_engine_routes(app: FastAPI) -> None:
|
|
55
|
+
"""Mount the routes Agent Runtime forwards `:query` and `:streamQuery` to."""
|
|
56
|
+
|
|
57
|
+
@app.post("/api/reasoning_engine")
|
|
58
|
+
async def query(request: Request) -> dict[str, Any]:
|
|
59
|
+
args = await _input(request, "async_create_session")
|
|
60
|
+
user_id = _string(args, "user_id")
|
|
61
|
+
session_id = _session_id(args)
|
|
62
|
+
session = {
|
|
63
|
+
"id": session_id,
|
|
64
|
+
"app_name": agent_name(),
|
|
65
|
+
"user_id": user_id,
|
|
66
|
+
"state": {},
|
|
67
|
+
"events": [],
|
|
68
|
+
"last_update_time": time.time(),
|
|
69
|
+
}
|
|
70
|
+
return {"output": session}
|
|
71
|
+
|
|
72
|
+
@app.post("/api/stream_reasoning_engine")
|
|
73
|
+
async def stream_query(request: Request) -> responses.StreamingResponse:
|
|
74
|
+
args = await _input(request, "async_stream_query")
|
|
75
|
+
prompt = _prompt(args.get("message"))
|
|
76
|
+
events = _turn(prompt, _string(args, "user_id"), _session_id(args))
|
|
77
|
+
|
|
78
|
+
async def lines() -> AsyncIterator[str]:
|
|
79
|
+
async with aclosing(events):
|
|
80
|
+
async for event in events:
|
|
81
|
+
yield json.dumps(event) + "\n"
|
|
82
|
+
|
|
83
|
+
return responses.StreamingResponse(lines(), media_type="application/json")
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
async def _input(request: Request, class_method: str) -> dict[str, Any]:
|
|
87
|
+
"""The `input` of a call to `class_method`, the one method the route serves."""
|
|
88
|
+
try:
|
|
89
|
+
body = await request.json()
|
|
90
|
+
except ValueError as err:
|
|
91
|
+
raise HTTPException(400, "The request body is not JSON.") from err
|
|
92
|
+
if not isinstance(body, dict):
|
|
93
|
+
raise HTTPException(400, 'Send {"class_method": ..., "input": {...}}.')
|
|
94
|
+
if body.get("class_method") != class_method:
|
|
95
|
+
raise HTTPException(
|
|
96
|
+
404,
|
|
97
|
+
f"Unsupported reasoning_engine method: {body.get('class_method')!r}. "
|
|
98
|
+
f"Supported: {class_method}.",
|
|
99
|
+
)
|
|
100
|
+
args = body.get("input")
|
|
101
|
+
if args is None:
|
|
102
|
+
return {}
|
|
103
|
+
if not isinstance(args, dict):
|
|
104
|
+
raise HTTPException(400, '"input" must be an object.')
|
|
105
|
+
return args
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _string(args: dict[str, Any], key: str) -> str:
|
|
109
|
+
value = args.get(key)
|
|
110
|
+
if not isinstance(value, str) or not value:
|
|
111
|
+
raise HTTPException(400, f"{key} must be a non-empty string.")
|
|
112
|
+
return value
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _session_id(args: dict[str, Any]) -> str:
|
|
116
|
+
"""The session to continue, or a new one."""
|
|
117
|
+
if args.get("session_id") is None:
|
|
118
|
+
return str(uuid.uuid4())
|
|
119
|
+
return _string(args, "session_id")
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _prompt(message: Any) -> str:
|
|
123
|
+
"""The text of a message: a string, or a Content object's text parts."""
|
|
124
|
+
if isinstance(message, str):
|
|
125
|
+
text = message
|
|
126
|
+
elif isinstance(message, dict) and isinstance(message.get("parts"), list):
|
|
127
|
+
text = "".join(
|
|
128
|
+
part["text"]
|
|
129
|
+
for part in message["parts"]
|
|
130
|
+
if isinstance(part, dict) and isinstance(part.get("text"), str)
|
|
131
|
+
)
|
|
132
|
+
else:
|
|
133
|
+
raise HTTPException(
|
|
134
|
+
400,
|
|
135
|
+
'message must be a string or {"role": "user", "parts": [{"text": ...}]}.',
|
|
136
|
+
)
|
|
137
|
+
if not text.strip():
|
|
138
|
+
raise HTTPException(400, "message has no text.")
|
|
139
|
+
return text
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
async def _turn(
|
|
143
|
+
prompt: str, user_id: str, session_id: str
|
|
144
|
+
) -> AsyncGenerator[dict[str, Any], None]:
|
|
145
|
+
"""Run one turn and yield its events; a failed turn ends with an error event."""
|
|
146
|
+
invocation_id = f"e-{uuid.uuid4()}"
|
|
147
|
+
tool_names: dict[str, str] = {}
|
|
148
|
+
failed = False
|
|
149
|
+
turn_span = trace.INVALID_SPAN
|
|
150
|
+
try:
|
|
151
|
+
async with aclosing(
|
|
152
|
+
stream_turn(prompt, root_agent, session_id, user_id)
|
|
153
|
+
) as stream:
|
|
154
|
+
async for message in stream:
|
|
155
|
+
turn_span = trace.get_current_span()
|
|
156
|
+
if isinstance(message, ResultMessage) and message.is_error:
|
|
157
|
+
failed = True
|
|
158
|
+
yield _error(invocation_id, result_error(message))
|
|
159
|
+
elif event := _event(invocation_id, message, tool_names):
|
|
160
|
+
yield event
|
|
161
|
+
if on_agent_runtime():
|
|
162
|
+
# Agent Runtime throttles the CPU once the response ends.
|
|
163
|
+
await memory_bank.flush()
|
|
164
|
+
except Exception as e:
|
|
165
|
+
# Log under the ended turn span so the record links to its trace.
|
|
166
|
+
with trace.use_span(turn_span):
|
|
167
|
+
logging.exception("Claude agent turn failed")
|
|
168
|
+
# The SDK raises after an error result too, which already ended the turn.
|
|
169
|
+
if not failed:
|
|
170
|
+
yield _error(invocation_id, str(e))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _event(
|
|
174
|
+
invocation_id: str, message: Message, tool_names: dict[str, str]
|
|
175
|
+
) -> dict[str, Any] | None:
|
|
176
|
+
"""The event for a message: the agent's text and tool calls, or tool results.
|
|
177
|
+
|
|
178
|
+
A subagent's messages are left out; its work shows as the tool call that ran it.
|
|
179
|
+
"""
|
|
180
|
+
if isinstance(message, ResultMessage):
|
|
181
|
+
# With output_format set, the reply is the structured output.
|
|
182
|
+
if root_agent.output_format is None or message.structured_output is None:
|
|
183
|
+
return None
|
|
184
|
+
parts = [{"text": json.dumps(message.structured_output)}]
|
|
185
|
+
return _adk_event(invocation_id, "model", parts)
|
|
186
|
+
if not isinstance(message, AssistantMessage | UserMessage):
|
|
187
|
+
return None
|
|
188
|
+
if message.parent_tool_use_id or isinstance(message.content, str):
|
|
189
|
+
return None
|
|
190
|
+
parts: list[dict[str, Any]] = []
|
|
191
|
+
for block in message.content:
|
|
192
|
+
if isinstance(block, TextBlock) and block.text:
|
|
193
|
+
parts.append({"text": block.text})
|
|
194
|
+
elif isinstance(block, ToolUseBlock):
|
|
195
|
+
tool_names[block.id] = block.name
|
|
196
|
+
call = {"id": block.id, "name": block.name, "args": block.input}
|
|
197
|
+
parts.append({"function_call": call})
|
|
198
|
+
elif isinstance(block, ToolResultBlock):
|
|
199
|
+
key = "error" if block.is_error else "result"
|
|
200
|
+
response = {
|
|
201
|
+
"id": block.tool_use_id,
|
|
202
|
+
"name": tool_names.get(block.tool_use_id, ""),
|
|
203
|
+
"response": {key: tool_result_text(block)},
|
|
204
|
+
}
|
|
205
|
+
parts.append({"function_response": response})
|
|
206
|
+
if not parts:
|
|
207
|
+
return None
|
|
208
|
+
role = "user" if isinstance(message, UserMessage) else "model"
|
|
209
|
+
return _adk_event(invocation_id, role, parts)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _error(invocation_id: str, message: str) -> dict[str, Any]:
|
|
213
|
+
return {
|
|
214
|
+
**_adk_event(invocation_id, "model", []),
|
|
215
|
+
"error_code": "AGENT_ERROR",
|
|
216
|
+
"error_message": message,
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _adk_event(
|
|
221
|
+
invocation_id: str, role: str, parts: list[dict[str, Any]]
|
|
222
|
+
) -> dict[str, Any]:
|
|
223
|
+
event: dict[str, Any] = {
|
|
224
|
+
"invocation_id": invocation_id,
|
|
225
|
+
"author": agent_name(),
|
|
226
|
+
"actions": {
|
|
227
|
+
"state_delta": {},
|
|
228
|
+
"artifact_delta": {},
|
|
229
|
+
"requested_auth_configs": {},
|
|
230
|
+
"requested_tool_confirmations": {},
|
|
231
|
+
},
|
|
232
|
+
"id": str(uuid.uuid4()),
|
|
233
|
+
"timestamp": time.time(),
|
|
234
|
+
}
|
|
235
|
+
if parts:
|
|
236
|
+
event["content"] = {"parts": parts, "role": role}
|
|
237
|
+
return event
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
# Copyright 2026 Google LLC
|
|
2
|
+
#
|
|
3
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
# you may not use this file except in compliance with the License.
|
|
5
|
+
# You may obtain a copy of the License at
|
|
6
|
+
#
|
|
7
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
#
|
|
9
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
# See the License for the specific language governing permissions and
|
|
13
|
+
# limitations under the License.
|
|
14
|
+
|
|
15
|
+
"""Call other agents over A2A, as a tool the Claude agent can use."""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import logging
|
|
20
|
+
import os
|
|
21
|
+
import ssl
|
|
22
|
+
import uuid
|
|
23
|
+
import weakref
|
|
24
|
+
from collections import OrderedDict
|
|
25
|
+
from collections.abc import AsyncIterator, Mapping
|
|
26
|
+
from typing import Any
|
|
27
|
+
|
|
28
|
+
import anyio
|
|
29
|
+
import httpx
|
|
30
|
+
from a2a.client import A2ACardResolver, Client, ClientConfig, ClientFactory
|
|
31
|
+
from a2a.types import (
|
|
32
|
+
AgentCard,
|
|
33
|
+
Message,
|
|
34
|
+
Part,
|
|
35
|
+
Role,
|
|
36
|
+
SendMessageRequest,
|
|
37
|
+
StreamResponse,
|
|
38
|
+
TaskState,
|
|
39
|
+
)
|
|
40
|
+
from a2a.utils.constants import TransportProtocol
|
|
41
|
+
from claude_agent_sdk import McpSdkServerConfig, create_sdk_mcp_server, tool
|
|
42
|
+
|
|
43
|
+
from app.app_utils.conversation import current_conversation
|
|
44
|
+
from app.app_utils.remote_auth import (
|
|
45
|
+
PinnedHeaders,
|
|
46
|
+
access_token,
|
|
47
|
+
cloud_credentials,
|
|
48
|
+
id_token,
|
|
49
|
+
is_agent_runtime,
|
|
50
|
+
is_cloud_run,
|
|
51
|
+
mtls_target,
|
|
52
|
+
origin,
|
|
53
|
+
pin_to_origin,
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
# Remote conversations kept per remote agent; least recently used are dropped.
|
|
57
|
+
MAX_CONVERSATIONS = 1000
|
|
58
|
+
|
|
59
|
+
# Each remote_agent server's URL, keyed by its MCP server instance.
|
|
60
|
+
_urls: weakref.WeakKeyDictionary[Any, str] = weakref.WeakKeyDictionary()
|
|
61
|
+
|
|
62
|
+
_FAILED_STATES = {
|
|
63
|
+
TaskState.TASK_STATE_FAILED: "failed",
|
|
64
|
+
TaskState.TASK_STATE_REJECTED: "rejected",
|
|
65
|
+
TaskState.TASK_STATE_CANCELED: "was canceled",
|
|
66
|
+
TaskState.TASK_STATE_AUTH_REQUIRED: "requires authentication",
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def remote_agent(
|
|
71
|
+
name: str,
|
|
72
|
+
url: str,
|
|
73
|
+
*,
|
|
74
|
+
description: str | None = None,
|
|
75
|
+
auth: bool | None = None,
|
|
76
|
+
bind_id_token: bool = True,
|
|
77
|
+
headers: Mapping[str, str] | None = None,
|
|
78
|
+
timeout: float = 300.0,
|
|
79
|
+
) -> McpSdkServerConfig:
|
|
80
|
+
"""An MCP server whose `ask` tool sends a message to the A2A agent at `url`.
|
|
81
|
+
|
|
82
|
+
Follow-up calls in a conversation continue the remote agent's conversation.
|
|
83
|
+
|
|
84
|
+
billing = remote_agent("billing", "https://billing-xyz.a.run.app/a2a/app")
|
|
85
|
+
root_agent = ClaudeAgentOptions(
|
|
86
|
+
mcp_servers={"billing": billing},
|
|
87
|
+
allowed_tools=["mcp__billing__ask"],
|
|
88
|
+
...
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
Args:
|
|
92
|
+
name: The server name; the tool is `mcp__<name>__ask`.
|
|
93
|
+
url: Where the agent card is served, e.g. `https://<service>/a2a/app`.
|
|
94
|
+
For an Agent Runtime agent, its `/api` passthrough URL plus that
|
|
95
|
+
path: `https://<location>-aiplatform.googleapis.com/reasoningEngines/
|
|
96
|
+
v1/projects/<project>/locations/<location>/reasoningEngines/<id>/api/
|
|
97
|
+
a2a/app`.
|
|
98
|
+
description: Tells the model when to call the remote agent.
|
|
99
|
+
auth: None (default) sends a token only to Google-hosted agents: a
|
|
100
|
+
Google ID token to Cloud Run (`*.run.app`; the caller needs
|
|
101
|
+
roles/run.invoker) or an OAuth access token to Agent Runtime (the
|
|
102
|
+
caller needs roles/aiplatform.user). True sends an ID token to any
|
|
103
|
+
host; with gcloud user credentials that token can call any Cloud Run
|
|
104
|
+
service you can, so use a service account for untrusted hosts.
|
|
105
|
+
False sends no token.
|
|
106
|
+
bind_id_token: Set False when an Agent Runtime agent calls a Cloud Run
|
|
107
|
+
agent: Cloud Run rejects ID tokens bound to Agent Identity (401).
|
|
108
|
+
headers: Extra headers for every request; `Authorization` replaces the
|
|
109
|
+
token.
|
|
110
|
+
timeout: Seconds to wait for the remote agent's reply.
|
|
111
|
+
"""
|
|
112
|
+
if is_agent_runtime(url) and "/api" not in httpx.URL(url).path:
|
|
113
|
+
raise ValueError(
|
|
114
|
+
f"{url} is an Agent Runtime resource URL, which serves no A2A. Use "
|
|
115
|
+
"the agent's passthrough URL: https://<location>-aiplatform."
|
|
116
|
+
"googleapis.com/reasoningEngines/v1/projects/<project>/locations/"
|
|
117
|
+
"<location>/reasoningEngines/<id>/api, plus the agent's A2A path "
|
|
118
|
+
"(/a2a/app for an agent from this template)."
|
|
119
|
+
)
|
|
120
|
+
remote = _RemoteAgent(
|
|
121
|
+
name,
|
|
122
|
+
url,
|
|
123
|
+
auth=auth,
|
|
124
|
+
bind_id_token=bind_id_token,
|
|
125
|
+
headers=headers or {},
|
|
126
|
+
timeout=timeout,
|
|
127
|
+
)
|
|
128
|
+
|
|
129
|
+
@tool(
|
|
130
|
+
"ask",
|
|
131
|
+
description
|
|
132
|
+
or f"Send a message to the {name} agent and return its reply. "
|
|
133
|
+
"Follow-up messages continue the same conversation with it.",
|
|
134
|
+
{"message": str},
|
|
135
|
+
)
|
|
136
|
+
async def ask(args: dict[str, Any]) -> dict[str, Any]:
|
|
137
|
+
# Failures go back to the model as the tool result instead of ending
|
|
138
|
+
# the turn.
|
|
139
|
+
try:
|
|
140
|
+
with anyio.fail_after(timeout):
|
|
141
|
+
reply = await remote.send(args["message"])
|
|
142
|
+
except TimeoutError:
|
|
143
|
+
return _error(f"The {name} agent did not reply within {timeout:g}s.")
|
|
144
|
+
except Exception as e:
|
|
145
|
+
message = f"Calling the {name} agent failed: {e}"
|
|
146
|
+
if (
|
|
147
|
+
bind_id_token
|
|
148
|
+
and not remote.agent_runtime
|
|
149
|
+
and os.environ.get("GOOGLE_CLOUD_AGENT_ENGINE_ID")
|
|
150
|
+
and "401" in str(e)
|
|
151
|
+
):
|
|
152
|
+
# Likely Cloud Run rejecting a certificate-bound ID token.
|
|
153
|
+
message += (
|
|
154
|
+
" From Agent Runtime, a Cloud Run agent needs "
|
|
155
|
+
f'remote_agent("{name}", ..., bind_id_token=False).'
|
|
156
|
+
)
|
|
157
|
+
logging.warning("%s", message)
|
|
158
|
+
return _error(message)
|
|
159
|
+
return {"content": [{"type": "text", "text": reply or "(empty reply)"}]}
|
|
160
|
+
|
|
161
|
+
server = create_sdk_mcp_server(name=name, tools=[ask])
|
|
162
|
+
_urls[server["instance"]] = url
|
|
163
|
+
return server
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def remote_agent_url(config: Mapping[str, Any]) -> str | None:
|
|
167
|
+
"""The remote agent's URL if `config` is a remote_agent server, else None.
|
|
168
|
+
|
|
169
|
+
Lets BigQuery Agent Analytics record its tool as an A2A call.
|
|
170
|
+
"""
|
|
171
|
+
instance = config.get("instance")
|
|
172
|
+
try:
|
|
173
|
+
return _urls.get(instance)
|
|
174
|
+
except TypeError: # not weak-referenceable, so not one of ours
|
|
175
|
+
return None
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
class RemoteAgentError(RuntimeError):
|
|
179
|
+
"""The remote agent ended its task without a reply."""
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
class _RemoteAgent:
|
|
183
|
+
"""One remote agent's settings, and what it keeps between calls.
|
|
184
|
+
|
|
185
|
+
Keeps the resolved agent card, Google credentials, and the remote context id
|
|
186
|
+
of each local conversation.
|
|
187
|
+
"""
|
|
188
|
+
|
|
189
|
+
def __init__(
|
|
190
|
+
self,
|
|
191
|
+
name: str,
|
|
192
|
+
url: str,
|
|
193
|
+
*,
|
|
194
|
+
auth: bool | None,
|
|
195
|
+
bind_id_token: bool,
|
|
196
|
+
headers: Mapping[str, str],
|
|
197
|
+
timeout: float,
|
|
198
|
+
) -> None:
|
|
199
|
+
self.name = name
|
|
200
|
+
self.url = url
|
|
201
|
+
self.agent_runtime = is_agent_runtime(url)
|
|
202
|
+
self._google_hosted = self.agent_runtime or is_cloud_run(url)
|
|
203
|
+
self._send_token = self._google_hosted if auth is None else auth
|
|
204
|
+
self._audience = str(origin(url)).rstrip("/")
|
|
205
|
+
self._bind_id_token = bind_id_token
|
|
206
|
+
self._headers = headers
|
|
207
|
+
self._timeout = timeout
|
|
208
|
+
self._card: AgentCard | None = None
|
|
209
|
+
self._credentials: Any = None
|
|
210
|
+
self._warned = False
|
|
211
|
+
self._contexts: OrderedDict[str, str] = OrderedDict()
|
|
212
|
+
|
|
213
|
+
async def send(self, message: str) -> str:
|
|
214
|
+
"""Send `message` to the remote agent and return its reply."""
|
|
215
|
+
target, verify = await self._target()
|
|
216
|
+
headers = await self._request_headers()
|
|
217
|
+
conversation = current_conversation.get()
|
|
218
|
+
async with httpx.AsyncClient(
|
|
219
|
+
auth=PinnedHeaders(headers, origin(target)),
|
|
220
|
+
timeout=self._timeout,
|
|
221
|
+
verify=verify,
|
|
222
|
+
) as http_client:
|
|
223
|
+
client = await self._client(http_client, target)
|
|
224
|
+
request = self._request(message, conversation)
|
|
225
|
+
reply, context_id = await _read_reply(
|
|
226
|
+
client.send_message(request), self.name
|
|
227
|
+
)
|
|
228
|
+
if conversation and context_id:
|
|
229
|
+
self._remember(conversation, context_id)
|
|
230
|
+
return reply
|
|
231
|
+
|
|
232
|
+
async def _target(self) -> tuple[str, ssl.SSLContext | bool]:
|
|
233
|
+
"""The URL to call and how to verify its TLS certificate."""
|
|
234
|
+
if self.agent_runtime:
|
|
235
|
+
return await anyio.to_thread.run_sync(mtls_target, self.url)
|
|
236
|
+
return self.url, True
|
|
237
|
+
|
|
238
|
+
async def _request_headers(self) -> dict[str, str]:
|
|
239
|
+
headers = dict(self._headers)
|
|
240
|
+
if self._send_token and "authorization" not in {k.lower() for k in headers}:
|
|
241
|
+
headers["Authorization"] = f"Bearer {await self._token()}"
|
|
242
|
+
return headers
|
|
243
|
+
|
|
244
|
+
async def _token(self) -> str:
|
|
245
|
+
"""An access token for Agent Runtime, else an ID token for the host."""
|
|
246
|
+
if self.agent_runtime:
|
|
247
|
+
self._credentials = self._credentials or await anyio.to_thread.run_sync(
|
|
248
|
+
cloud_credentials
|
|
249
|
+
)
|
|
250
|
+
return await anyio.to_thread.run_sync(access_token, self._credentials)
|
|
251
|
+
token, unbound = await anyio.to_thread.run_sync(
|
|
252
|
+
id_token, self._audience, self._bind_id_token
|
|
253
|
+
)
|
|
254
|
+
if unbound and not self._google_hosted and not self._warned:
|
|
255
|
+
logging.warning(
|
|
256
|
+
"remote_agent %r sends your gcloud user ID token to %s, "
|
|
257
|
+
"which isn't bound to that host: it can call any Cloud "
|
|
258
|
+
"Run service you can. Use a service account or "
|
|
259
|
+
"impersonation for a host you don't trust.",
|
|
260
|
+
self.name,
|
|
261
|
+
httpx.URL(self.url).host,
|
|
262
|
+
)
|
|
263
|
+
self._warned = True
|
|
264
|
+
return token
|
|
265
|
+
|
|
266
|
+
async def _client(self, http_client: httpx.AsyncClient, target: str) -> Client:
|
|
267
|
+
"""An A2A client for the agent card, resolved on the first call."""
|
|
268
|
+
if self._card is None:
|
|
269
|
+
card = await A2ACardResolver(http_client, target).get_agent_card()
|
|
270
|
+
pin_to_origin(card, target)
|
|
271
|
+
self._card = card
|
|
272
|
+
return ClientFactory(
|
|
273
|
+
ClientConfig(
|
|
274
|
+
httpx_client=http_client,
|
|
275
|
+
supported_protocol_bindings=[
|
|
276
|
+
TransportProtocol.JSONRPC,
|
|
277
|
+
TransportProtocol.HTTP_JSON,
|
|
278
|
+
],
|
|
279
|
+
)
|
|
280
|
+
).create(self._card)
|
|
281
|
+
|
|
282
|
+
def _request(self, message: str, conversation: str | None) -> SendMessageRequest:
|
|
283
|
+
"""`message` in the remote conversation that continues `conversation`."""
|
|
284
|
+
return SendMessageRequest(
|
|
285
|
+
message=Message(
|
|
286
|
+
message_id=uuid.uuid4().hex,
|
|
287
|
+
role=Role.ROLE_USER,
|
|
288
|
+
parts=[Part(text=message)],
|
|
289
|
+
context_id=self._contexts.get(conversation, "") if conversation else "",
|
|
290
|
+
)
|
|
291
|
+
)
|
|
292
|
+
|
|
293
|
+
def _remember(self, conversation: str, context_id: str) -> None:
|
|
294
|
+
self._contexts[conversation] = context_id
|
|
295
|
+
self._contexts.move_to_end(conversation)
|
|
296
|
+
while len(self._contexts) > MAX_CONVERSATIONS:
|
|
297
|
+
self._contexts.popitem(last=False)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
async def _read_reply(
|
|
301
|
+
chunks: AsyncIterator[StreamResponse], name: str
|
|
302
|
+
) -> tuple[str, str]:
|
|
303
|
+
"""The reply and remote context id from the streamed response.
|
|
304
|
+
|
|
305
|
+
The reply is the task's text artifacts, else the last message.
|
|
306
|
+
|
|
307
|
+
Raises:
|
|
308
|
+
RemoteAgentError: The task ended in one of `_FAILED_STATES`.
|
|
309
|
+
"""
|
|
310
|
+
artifacts: dict[str, str] = {}
|
|
311
|
+
reply = ""
|
|
312
|
+
context_id = ""
|
|
313
|
+
async for chunk in chunks:
|
|
314
|
+
status = None
|
|
315
|
+
if chunk.HasField("task"):
|
|
316
|
+
task = chunk.task
|
|
317
|
+
context_id = task.context_id or context_id
|
|
318
|
+
status = task.status
|
|
319
|
+
if task.artifacts:
|
|
320
|
+
artifacts = {a.artifact_id: _text(a.parts) for a in task.artifacts}
|
|
321
|
+
elif chunk.HasField("artifact_update"):
|
|
322
|
+
update = chunk.artifact_update
|
|
323
|
+
context_id = update.context_id or context_id
|
|
324
|
+
previous = artifacts.get(update.artifact.artifact_id, "")
|
|
325
|
+
artifacts[update.artifact.artifact_id] = (
|
|
326
|
+
previous if update.append else ""
|
|
327
|
+
) + _text(update.artifact.parts)
|
|
328
|
+
elif chunk.HasField("status_update"):
|
|
329
|
+
context_id = chunk.status_update.context_id or context_id
|
|
330
|
+
status = chunk.status_update.status
|
|
331
|
+
elif chunk.HasField("message"):
|
|
332
|
+
context_id = chunk.message.context_id or context_id
|
|
333
|
+
reply = _text(chunk.message.parts) or reply
|
|
334
|
+
if status is not None and status.HasField("message"):
|
|
335
|
+
reply = _text(status.message.parts) or reply
|
|
336
|
+
if status is not None and status.state in _FAILED_STATES:
|
|
337
|
+
raise RemoteAgentError(
|
|
338
|
+
f"The {name} agent's task {_FAILED_STATES[status.state]}: "
|
|
339
|
+
f"{_text(status.message.parts) or 'no reason given'}"
|
|
340
|
+
)
|
|
341
|
+
return "".join(artifacts.values()) or reply, context_id
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _text(parts: Any) -> str:
|
|
345
|
+
return "".join(part.text for part in parts if part.text)
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
def _error(text: str) -> dict[str, Any]:
|
|
349
|
+
return {"content": [{"type": "text", "text": text}], "is_error": True}
|