agentenv-framework-protocol 0.1.330__py3-none-any.whl → 0.1.332__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentenv-framework-protocol
3
- Version: 0.1.330
3
+ Version: 0.1.332
4
4
  Summary: Open data-plane protocol and server SDK for agent environments.
5
5
  Project-URL: Homepage, https://www.agentenvframework.com
6
6
  Project-URL: Documentation, https://www.agentenvframework.com/docs
@@ -245,7 +245,48 @@ class SlackEnv(AgentEnvEnvironment):
245
245
  return [DataPart(data=self.state())]
246
246
  ```
247
247
 
248
- Dependencies are intentionally light (`pydantic`, `starlette`) so the package can be added to environment server images without pulling a heavier framework — `mcp` is imported lazily inside `create_fastmcp_app()` and is deliberately not a dependency.
248
+ Dependencies are intentionally light (`pydantic`, `starlette`, `httpx`) so the package can be added to environment server images without pulling a heavier framework — `mcp` is imported lazily inside `create_fastmcp_app()` and is deliberately not a dependency.
249
+
250
+ ## Calling an env's tools
251
+
252
+ A loop of your own, such as a trainer's rollout or an eval harness, reaches an env's tools through `ToolSession`. It
253
+ is an MCP client for the env's streamable-HTTP endpoint, written on `httpx`, so it works wherever this package
254
+ installs, whichever `mcp` version the loop's own environment pins.
255
+
256
+ ```python
257
+ from agentenv_protocol import ToolSession
258
+
259
+ async with ToolSession(mcp_url=mcp_url, role="alice@example.com") as session:
260
+ tools = await session.list_tools() # EnvironmentTool: name, description, inputSchema
261
+ result = await session.call_tool("slack_send_message", {"channel": "general", "text": "hi"})
262
+ print(result.text, result.isError)
263
+ ```
264
+
265
+ - **The URL:** `mcp_url` is `DeployedEnv.mcp_url` in agent-env, or the address a card was fetched from joined with
266
+ `client.mcp_path(card)`.
267
+ - **Sessions:** a `ToolSession` is one MCP session, and calls on it may run concurrently. `async with` opens and ends
268
+ it; `open()` and `close()` do the same for a session held across calls. A tool tells sessions apart by
269
+ `ctx.caller.session`: the session's id when the server is reached directly, or, behind a gateway, a key the gateway
270
+ gives each session. A session belongs to the event loop that opened it, and using or closing it on another raises
271
+ `RuntimeError`, so a caller with a synchronous API runs all of a session's calls on one loop of its own.
272
+ - **Roles:** `role` is sent as `AgentEnv-Role` (`ROLE_HEADER`) and says who the caller is. A gateway lists only the
273
+ tools that role may use, answers a call to a hidden one with an error result, and forwards the role to the servers
274
+ behind it; a server reached directly reads the header itself. Either way a tool reads it as `ctx.caller.role`
275
+ ([Who is calling](#who-is-calling)), where `default`, like no role, is `None`. `headers` adds any others.
276
+ - **Errors:**
277
+ - A tool that fails, or a call the server refuses (a tool hidden from the role, or an `on_tool_call` refusal),
278
+ returns a result with `isError` set and the server's text.
279
+ - `ToolSessionError` means the request failed at the MCP level: a JSON-RPC error, an HTTP error status, a reply
280
+ that can't be read, or a session the server no longer knows. After a restart, the env's state is usually gone too.
281
+ Only the server the session talks to reports this: a gateway reconnects to a child that restarted and retries the
282
+ call, and a stateless server has no session to lose, so neither restart raises anything.
283
+ - `httpx.TransportError` means the connection failed, and `TimeoutError` that a request outlived `timeout`
284
+ (600 s by default, the gateway's own limit on a tool call).
285
+ - `ToolSession` retries nothing. A call that raised may still have run on the server, or may yet run: a request
286
+ stalled on a bad link can arrive after the client has given up. So after any failed call the env's state is
287
+ unknown; read it back (`data/get`) or end the episode.
288
+ - **Tools:** `list_tools()` returns the tools the role may use as `EnvironmentTool`, the type a card's
289
+ `capabilities.tools` holds. Each `inputSchema` is the JSON Schema a model API takes as the tool's parameters.
249
290
 
250
291
  ## A2A agent framework
251
292
 
@@ -1,8 +1,9 @@
1
- agentenv_protocol/__init__.py,sha256=v7VGvA6dW3p6VCY82RZVrufMLrj_P9TUKhTP-8GlzmE,2973
1
+ agentenv_protocol/__init__.py,sha256=M61f1W9sb8etEnJhS1CpxtuWnjTHwRQ4LxFyQrQr8Yc,3101
2
2
  agentenv_protocol/agent_env_environment.py,sha256=7W7mufr7J_xf56QD5eAY2tZDZW6JJTLI-GWiNVgmrUE,49277
3
3
  agentenv_protocol/client.py,sha256=OweWzQslkAEdwwxhjkTVOCFwfVvsrNzbg7URJi-05BQ,8937
4
4
  agentenv_protocol/manifest.py,sha256=T-bOI6LKpFvR4iFZ0rg3iYPDz2NpOIaJWofygDiJusc,7049
5
5
  agentenv_protocol/preflight.py,sha256=DEtN-js2cHn850QYLIC1gfuhKPsHVW0WF6oW5BzhkpI,3159
6
+ agentenv_protocol/tool_client.py,sha256=OR-UNYTeZ3NHirL1ig0HSkNj-2kspV1MrSrcP046JOw,9837
6
7
  agentenv_protocol/tool_context.py,sha256=u5QdlBWONa5O4YAZDivuRyNu5K84sagAkH9PD_sR95g,8827
7
8
  agentenv_protocol/transfers.py,sha256=Blda7dueQrCMPvFjR4FHOuLXnGX6sSGKNLd6vEMg7gU,22541
8
9
  agentenv_protocol/types.py,sha256=iXOcfEDSyH6hBIRTVXKkax4wpq7bUNEj4cRmlbinCkQ,6696
@@ -15,9 +16,9 @@ agentenv_protocol/a2a_agent/registry.py,sha256=TCfmvLfYthVSyH2xPLJXiG545mo7_ITiU
15
16
  agentenv_protocol/a2a_agent/staging.py,sha256=fdDdO0cQ5O-fYcPTpGKVK3intECufI4rcxmNrVBeFRI,21082
16
17
  agentenv_protocol/a2a_agent/tasks/__init__.py,sha256=r_PEL7-Uwxdi4miWKig9QMKg5bjhWdR89ch21vdzoMw,707
17
18
  agentenv_protocol/a2a_agent/tasks/v1.py,sha256=ukWq0ynimv7OjDnO7c6QyLBHl9OxxtzS4AOdCmfSgrw,16585
18
- agentenv_framework_protocol-0.1.330.dist-info/METADATA,sha256=F3VUnz5_OAbU_cXaQIhvYdKkFvDDv1aQLGlKa6Y6IP0,42806
19
- agentenv_framework_protocol-0.1.330.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
20
- agentenv_framework_protocol-0.1.330.dist-info/licenses/LICENSE,sha256=tDzJZMZjW-flCBnzsHtIbtYZ6O0TrZxH7lQFPCzdWNo,11339
21
- agentenv_framework_protocol-0.1.330.dist-info/licenses/NOTICE,sha256=VpxCebMPcCz2R4HL8BD4M2hHjKWnUPmKSrng8h33ykc,127
22
- agentenv_framework_protocol-0.1.330.dist-info/licenses/THIRD_PARTY_NOTICES.md,sha256=F3M7Q9QQRwyBR7FAPfOn-vchpLTOWtgwCdMx1WTj5IM,82022
23
- agentenv_framework_protocol-0.1.330.dist-info/RECORD,,
19
+ agentenv_framework_protocol-0.1.332.dist-info/METADATA,sha256=fbI_0_5jJYaIHdvWwYoelvMNNpyLThneHiNqbJCr4nk,45982
20
+ agentenv_framework_protocol-0.1.332.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
21
+ agentenv_framework_protocol-0.1.332.dist-info/licenses/LICENSE,sha256=tDzJZMZjW-flCBnzsHtIbtYZ6O0TrZxH7lQFPCzdWNo,11339
22
+ agentenv_framework_protocol-0.1.332.dist-info/licenses/NOTICE,sha256=VpxCebMPcCz2R4HL8BD4M2hHjKWnUPmKSrng8h33ykc,127
23
+ agentenv_framework_protocol-0.1.332.dist-info/licenses/THIRD_PARTY_NOTICES.md,sha256=F3M7Q9QQRwyBR7FAPfOn-vchpLTOWtgwCdMx1WTj5IM,82022
24
+ agentenv_framework_protocol-0.1.332.dist-info/RECORD,,
@@ -2,6 +2,7 @@
2
2
 
3
3
  from . import client
4
4
  from .preflight import intake_fit_check
5
+ from .tool_client import ToolResult, ToolSession, ToolSessionError
5
6
  from .agent_env_environment import (
6
7
  AgentEnvApplication,
7
8
  AgentEnvEnvironment,
@@ -116,6 +117,9 @@ __all__ = [
116
117
  "uploaded_object_path",
117
118
  "MCP_PATH",
118
119
  "MCP_TRANSPORT",
120
+ "ToolSession",
121
+ "ToolResult",
122
+ "ToolSessionError",
119
123
  "MANIFEST_VERSION",
120
124
  "INTERFACE_MANIFEST_PATH",
121
125
  "GET_INTERFACES_EXTENSION_URI",
@@ -0,0 +1,205 @@
1
+ """MCP client for an environment's tools, over the streamable-HTTP transport on httpx alone: a trainer's or eval
2
+ harness's own loop lists and calls an env's tools with it, whatever `mcp` version that loop's environment pins."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import asyncio
7
+ import contextlib
8
+ import itertools
9
+ import json
10
+ from collections.abc import AsyncIterator
11
+ from typing import Any
12
+
13
+ import httpx
14
+ from pydantic import BaseModel, Field, field_validator
15
+
16
+ from .tool_context import ROLE_HEADER
17
+ from .types import PROTOCOL_VERSION, EnvironmentTool
18
+
19
+ _MCP_PROTOCOL_VERSION = "2025-11-25"
20
+ _SESSION_HEADER = "Mcp-Session-Id"
21
+ _VERSION_HEADER = "MCP-Protocol-Version"
22
+ _ACCEPT = "application/json, text/event-stream"
23
+ _CLOSE_TIMEOUT_S = 5.0
24
+
25
+
26
+ class ToolSessionError(RuntimeError):
27
+ """An MCP-level failure: a JSON-RPC error, an HTTP error status, a reply that can't be read, or a session the server
28
+ no longer knows. A tool that fails is not one; its result carries ``isError``."""
29
+
30
+
31
+ class ToolResult(BaseModel):
32
+ content: list[dict] = Field(default_factory=list)
33
+ isError: bool = False
34
+
35
+ @field_validator("content")
36
+ @classmethod
37
+ def _text_blocks_carry_text(cls, content: list[dict]) -> list[dict]:
38
+ if any(block.get("type") == "text" and not isinstance(block.get("text"), str) for block in content):
39
+ raise ValueError("a text block has no string text")
40
+ return content
41
+
42
+ @property
43
+ def text(self) -> str:
44
+ return "\n".join(block["text"] for block in self.content if block.get("type") == "text")
45
+
46
+
47
+ class ToolSession:
48
+ """One MCP session on an env's ``mcp_url``. Use it on the event loop that opened it, and after any failed call treat
49
+ the env's state as unknown: nothing is retried, and a call that raised may still run on the server."""
50
+
51
+ def __init__(self, *, mcp_url: str, role: str | None = None, headers: dict[str, str] | None = None,
52
+ timeout: float = 600.0) -> None:
53
+ self.mcp_url = mcp_url
54
+ self.timeout = timeout
55
+ self.session_id: str | None = None
56
+ self.protocol_version: str | None = None
57
+ self._headers = {**(headers or {}), **({ROLE_HEADER: role} if role else {}), "Accept": _ACCEPT}
58
+ self._client: httpx.AsyncClient | None = None
59
+ self._loop: asyncio.AbstractEventLoop | None = None
60
+ self._ids = itertools.count(1)
61
+
62
+ async def __aenter__(self) -> ToolSession:
63
+ return await self.open()
64
+
65
+ async def __aexit__(self, *exc_info: object) -> None:
66
+ await self.close()
67
+
68
+ async def open(self) -> ToolSession:
69
+ """Start a new MCP session, ending the one this object holds, if any."""
70
+ await self.close()
71
+ self.session_id = self.protocol_version = None
72
+ self._loop = asyncio.get_running_loop()
73
+ self._client = httpx.AsyncClient(headers=self._headers, timeout=None, follow_redirects=True)
74
+ try:
75
+ result = await self._request("initialize", {
76
+ "protocolVersion": _MCP_PROTOCOL_VERSION,
77
+ "capabilities": {},
78
+ "clientInfo": {"name": "agentenv-protocol", "version": PROTOCOL_VERSION},
79
+ })
80
+ self.protocol_version = result.get("protocolVersion") or _MCP_PROTOCOL_VERSION
81
+ await self._deadline("notifications/initialized",
82
+ self._exchange({"jsonrpc": "2.0", "method": "notifications/initialized"}))
83
+ except BaseException:
84
+ await self.close()
85
+ raise
86
+ return self
87
+
88
+ async def close(self) -> None:
89
+ """End the session on the server, waiting at most 5 s (or ``timeout``, if shorter), then close the connection; a
90
+ server that is already gone is not an error."""
91
+ if self._client is None:
92
+ return
93
+ client, self._client = self._open_client(), None
94
+ try:
95
+ if self.session_id:
96
+ with contextlib.suppress(httpx.HTTPError, asyncio.TimeoutError):
97
+ await asyncio.wait_for(client.delete(self.mcp_url, headers=self._session_headers()),
98
+ min(self.timeout, _CLOSE_TIMEOUT_S))
99
+ finally:
100
+ await client.aclose()
101
+
102
+ async def list_tools(self) -> list[EnvironmentTool]:
103
+ tools: list[EnvironmentTool] = []
104
+ params: dict[str, Any] = {}
105
+ while True:
106
+ result = await self._request("tools/list", params)
107
+ if not isinstance(result.get("tools"), list):
108
+ raise ToolSessionError("tools/list: unreadable result: tools is not a list")
109
+ tools += [_validated(EnvironmentTool, tool, "tools/list") for tool in result["tools"]]
110
+ if not result.get("nextCursor"):
111
+ return tools
112
+ params = {"cursor": result["nextCursor"]}
113
+
114
+ async def call_tool(self, name: str, arguments: dict[str, Any] | None = None) -> ToolResult:
115
+ result = await self._request("tools/call", {"name": name, "arguments": arguments or {}})
116
+ return _validated(ToolResult, result, "tools/call")
117
+
118
+ async def _request(self, method: str, params: dict[str, Any]) -> dict:
119
+ message = {"jsonrpc": "2.0", "id": next(self._ids), "method": method, "params": params}
120
+ reply = await self._deadline(method, self._exchange(message))
121
+ if "error" in reply:
122
+ error = reply["error"] if isinstance(reply["error"], dict) else {"message": reply["error"]}
123
+ raise ToolSessionError(f"{method} failed: {error.get('message')} (code {error.get('code')})")
124
+ if not isinstance(reply.get("result"), dict):
125
+ raise ToolSessionError(f"{method}: the reply has no result object")
126
+ return reply["result"]
127
+
128
+ async def _deadline(self, method: str, exchange: Any) -> Any:
129
+ try:
130
+ return await asyncio.wait_for(exchange, self.timeout)
131
+ except asyncio.TimeoutError as e:
132
+ raise TimeoutError(f"{method} did not finish within {self.timeout}s") from e
133
+
134
+ async def _exchange(self, message: dict) -> dict:
135
+ async with self._open_client().stream("POST", self.mcp_url, json=message,
136
+ headers=self._session_headers()) as response:
137
+ await self._raise_for_status(response, message["method"])
138
+ if "id" not in message:
139
+ return {}
140
+ if message["method"] == "initialize":
141
+ self.session_id = response.headers.get(_SESSION_HEADER)
142
+ content_type = response.headers.get("content-type", "")
143
+ try:
144
+ if content_type.startswith("text/event-stream"):
145
+ async for data in _sse_data(response):
146
+ reply = json.loads(data)
147
+ if isinstance(reply, dict) and reply.get("id") == message["id"] and (
148
+ "result" in reply or "error" in reply):
149
+ return reply
150
+ raise ToolSessionError(f"{message['method']}: the event stream ended before the reply")
151
+ if content_type.startswith("application/json"):
152
+ reply = json.loads(await response.aread())
153
+ if isinstance(reply, dict):
154
+ return reply
155
+ raise ToolSessionError(f"{message['method']}: the reply is not a JSON-RPC object")
156
+ except ValueError as e:
157
+ raise ToolSessionError(f"{message['method']}: unreadable reply: {e}") from e
158
+ raise ToolSessionError(f"{message['method']}: unexpected content type {content_type!r}")
159
+
160
+ async def _raise_for_status(self, response: httpx.Response, method: str) -> None:
161
+ if response.status_code == 404 and self.session_id:
162
+ raise ToolSessionError(f"{method}: the server no longer knows session {self.session_id}; it restarted "
163
+ "or ended the session, and the env's state may be gone with it")
164
+ if response.status_code >= 400:
165
+ body = (await response.aread()).decode(errors="replace")[:1000]
166
+ raise ToolSessionError(f"{method}: HTTP {response.status_code} from {self.mcp_url}: {body}")
167
+
168
+ def _session_headers(self) -> dict[str, str]:
169
+ headers = {_SESSION_HEADER: self.session_id} if self.session_id else {}
170
+ if self.protocol_version:
171
+ headers[_VERSION_HEADER] = self.protocol_version
172
+ return headers
173
+
174
+ def _open_client(self) -> httpx.AsyncClient:
175
+ if self._client is None:
176
+ raise RuntimeError("the ToolSession is not open: use `async with ToolSession(...)` or `await open()`")
177
+ if asyncio.get_running_loop() is not self._loop:
178
+ raise RuntimeError("the ToolSession was opened on another event loop; use and close it on that one")
179
+ return self._client
180
+
181
+
182
+ def _validated(model: type[BaseModel], data: Any, method: str) -> Any:
183
+ try:
184
+ return model.model_validate(data)
185
+ except ValueError as e:
186
+ raise ToolSessionError(f"{method}: unreadable result: {e}") from e
187
+
188
+
189
+ async def _sse_data(response: httpx.Response) -> AsyncIterator[str]:
190
+ """The data of each ``message`` event in a server-sent event stream; an event the stream ends inside is dropped,
191
+ as the SSE spec has it, and so are events with no data, such as a resumable server's priming event."""
192
+ event, data = "message", []
193
+ async for line in response.aiter_lines():
194
+ if not line:
195
+ payload = "\n".join(data)
196
+ if payload.strip() and event == "message":
197
+ yield payload
198
+ event, data = "message", []
199
+ continue
200
+ field, _, value = line.partition(":")
201
+ value = value[1:] if value.startswith(" ") else value
202
+ if field == "data":
203
+ data.append(value)
204
+ elif field == "event":
205
+ event = value