sofias-sdk-lite 0.2.1__tar.gz → 0.3.0__tar.gz

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 (82) hide show
  1. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/PKG-INFO +11 -6
  2. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/README.md +10 -5
  3. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/pyproject.toml +1 -1
  4. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/pyproject.toml.orig +1 -1
  5. sofias_sdk_lite-0.3.0/src/sofias_sdk_lite/mcp.py +240 -0
  6. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/LICENSE +0 -0
  7. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/__init__.py +0 -0
  8. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/agent/__init__.py +0 -0
  9. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/agent/agent.py +0 -0
  10. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/agent/agent_builder.py +0 -0
  11. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/agent/agent_config.py +0 -0
  12. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/agent/execution_context.py +0 -0
  13. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/agent/middleware.py +0 -0
  14. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/agent/response_workflow.py +0 -0
  15. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/agent/streaming.py +0 -0
  16. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/config/__init__.py +0 -0
  17. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/config/agent_settings.py +0 -0
  18. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/config/defaults.py +0 -0
  19. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/config/runtime_config.py +0 -0
  20. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/config/sdk_config.py +0 -0
  21. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/config/source.py +0 -0
  22. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/contracts/__init__.py +0 -0
  23. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/contracts/agent_contracts.py +0 -0
  24. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/contracts/base_contracts.py +0 -0
  25. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/contracts/node_contracts.py +0 -0
  26. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/contracts/strict_contract.py +0 -0
  27. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/errors/__init__.py +0 -0
  28. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/errors/circuit_breaker.py +0 -0
  29. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/errors/error_handler.py +0 -0
  30. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/errors/exceptions.py +0 -0
  31. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/llm/__init__.py +0 -0
  32. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/llm/factory.py +0 -0
  33. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/llm/gateway.py +0 -0
  34. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/llm/openai_compatible.py +0 -0
  35. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/llm/protocol.py +0 -0
  36. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/llm/tokens.py +0 -0
  37. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/llm/tools.py +0 -0
  38. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/messaging/__init__.py +0 -0
  39. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/messaging/models.py +0 -0
  40. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/__init__.py +0 -0
  41. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/aggregator_config.py +0 -0
  42. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/aggregator_node.py +0 -0
  43. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/base_node.py +0 -0
  44. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/delegation_config.py +0 -0
  45. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/delegation_node.py +0 -0
  46. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/delegation_transport.py +0 -0
  47. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/function_node.py +0 -0
  48. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/llm_node.py +0 -0
  49. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/llm_node_config.py +0 -0
  50. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/plan_executor.py +0 -0
  51. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/planner_node.py +0 -0
  52. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/planning_models.py +0 -0
  53. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/nodes/prompt_assembler.py +0 -0
  54. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/observability/__init__.py +0 -0
  55. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/observability/_log.py +0 -0
  56. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/observability/events.py +0 -0
  57. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/observability/trace_context.py +0 -0
  58. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/observability/tracing.py +0 -0
  59. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/py.typed +0 -0
  60. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/rabbitmq/__init__.py +0 -0
  61. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/rabbitmq/client.py +0 -0
  62. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/rabbitmq/config.py +0 -0
  63. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/rabbitmq/consumer.py +0 -0
  64. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/rabbitmq/delegation_transport.py +0 -0
  65. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/rabbitmq/publisher.py +0 -0
  66. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/rabbitmq/rpc_client.py +0 -0
  67. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/rabbitmq/types.py +0 -0
  68. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/routing/__init__.py +0 -0
  69. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/routing/router.py +0 -0
  70. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/routing/strategies.py +0 -0
  71. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/runner/__init__.py +0 -0
  72. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/runner/config.py +0 -0
  73. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/runner/runner.py +0 -0
  74. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/state/__init__.py +0 -0
  75. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/state/conversation_state.py +0 -0
  76. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/state/history.py +0 -0
  77. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/state/memory.py +0 -0
  78. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/tools.py +0 -0
  79. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/workflows/__init__.py +0 -0
  80. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/workflows/chat.py +0 -0
  81. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/workflows/null.py +0 -0
  82. {sofias_sdk_lite-0.2.1 → sofias_sdk_lite-0.3.0}/src/sofias_sdk_lite/workflows/streaming_chat.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: sofias-sdk-lite
3
- Version: 0.2.1
3
+ Version: 0.3.0
4
4
  Summary: Build agents on the Sofias agent graph and run them over RabbitMQ.
5
5
  Keywords: agents,ai,llm,rabbitmq,sofias
6
6
  Author: Sofias Tech, S.L.
@@ -56,6 +56,11 @@ Build multi-node agents on a declarative graph and run them against RabbitMQ.
56
56
  from the agent's settings or the `SOFIAS_LLM_*` environment. `create_llm()`
57
57
  builds the client when you need it explicitly; `LLMCallable` stays a protocol
58
58
  for anything the bundled clients do not cover.
59
+ - **The user's connectors** — `McpToolProvider` turns the connectors the platform
60
+ sends with each turn (mail, documents, CRM, the company's own MCP servers…)
61
+ into tools for your LLM nodes. They go through the platform's intermediary:
62
+ your agent never sees a credential. See
63
+ [Using the user's connectors](https://docs.sofias.ai/guides/connectors/).
59
64
 
60
65
  Nothing here depends on a private backend or an internal config service.
61
66
  Where the model lives is deployment configuration, not agent code.
@@ -209,11 +214,11 @@ if __name__ == "__main__":
209
214
 
210
215
  ## Scope (v1)
211
216
 
212
- Core agent graph, RabbitMQ messaging, the runner, and LLM clients for the
213
- Sofias gateway / any OpenAI-compatible endpoint ship today. Memory and MCP
214
- tool discovery are intentionally out of scope for v1 — the SDK ships the
215
- relevant protocols (`MemoryProvider`, `ToolProvider`) so you can plug in
216
- your own, and these become optional extras in a later release.
217
+ Core agent graph, RabbitMQ messaging, the runner, LLM clients for the Sofias
218
+ gateway / any OpenAI-compatible endpoint and, since 0.3.0, the user's
219
+ connectors (MCP) ship today. Memory is intentionally out of scope for v1 — the
220
+ SDK ships the `MemoryProvider` protocol so you can plug in your own, and it
221
+ becomes an optional extra in a later release.
217
222
 
218
223
  ## Source and contributions
219
224
 
@@ -20,6 +20,11 @@ Build multi-node agents on a declarative graph and run them against RabbitMQ.
20
20
  from the agent's settings or the `SOFIAS_LLM_*` environment. `create_llm()`
21
21
  builds the client when you need it explicitly; `LLMCallable` stays a protocol
22
22
  for anything the bundled clients do not cover.
23
+ - **The user's connectors** — `McpToolProvider` turns the connectors the platform
24
+ sends with each turn (mail, documents, CRM, the company's own MCP servers…)
25
+ into tools for your LLM nodes. They go through the platform's intermediary:
26
+ your agent never sees a credential. See
27
+ [Using the user's connectors](https://docs.sofias.ai/guides/connectors/).
23
28
 
24
29
  Nothing here depends on a private backend or an internal config service.
25
30
  Where the model lives is deployment configuration, not agent code.
@@ -173,11 +178,11 @@ if __name__ == "__main__":
173
178
 
174
179
  ## Scope (v1)
175
180
 
176
- Core agent graph, RabbitMQ messaging, the runner, and LLM clients for the
177
- Sofias gateway / any OpenAI-compatible endpoint ship today. Memory and MCP
178
- tool discovery are intentionally out of scope for v1 — the SDK ships the
179
- relevant protocols (`MemoryProvider`, `ToolProvider`) so you can plug in
180
- your own, and these become optional extras in a later release.
181
+ Core agent graph, RabbitMQ messaging, the runner, LLM clients for the Sofias
182
+ gateway / any OpenAI-compatible endpoint and, since 0.3.0, the user's
183
+ connectors (MCP) ship today. Memory is intentionally out of scope for v1 — the
184
+ SDK ships the `MemoryProvider` protocol so you can plug in your own, and it
185
+ becomes an optional extra in a later release.
181
186
 
182
187
  ## Source and contributions
183
188
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sofias-sdk-lite"
3
- version = "0.2.1"
3
+ version = "0.3.0"
4
4
  description = "Build agents on the Sofias agent graph and run them over RabbitMQ."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "sofias-sdk-lite"
3
- version = "0.2.1"
3
+ version = "0.3.0"
4
4
  description = "Build agents on the Sofias agent graph and run them over RabbitMQ."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.11"
@@ -0,0 +1,240 @@
1
+ """MCP connectors delivered by the Sofias platform.
2
+
3
+ The platform sends each turn's connectors in ``AgentTaskMessage.mcp_servers``.
4
+ Inside ``configuration`` it puts the transport details under ``__mcp_*`` keys:
5
+
6
+ - ``__mcp_url``: the endpoint to call. For marketplace agents it is always the
7
+ platform's MCP intermediary, which adds the user's real credentials itself.
8
+ - ``__mcp_headers``: headers for every request (a short-lived grant). Never put
9
+ them in a prompt or a log.
10
+ - ``__mcp_tools``: the allow list approved for that connector.
11
+ - ``__mcp_namespace``: offer the tools as ``connector__tool`` so two connectors
12
+ with a tool of the same name do not clash.
13
+
14
+ ``McpToolProvider`` implements the ``ToolProvider`` protocol on top of those
15
+ entries with a minimal Streamable HTTP client (JSON-RPC over ``httpx``, JSON or
16
+ event-stream answers, ``Mcp-Session-Id``), so it needs no extra dependency::
17
+
18
+ from sofias_sdk_lite.mcp import McpToolProvider
19
+ from sofias_sdk_lite.tools import ToolRegistry
20
+
21
+ provider = McpToolProvider(task.mcp_servers)
22
+ builder.with_tool_registry(ToolRegistry(provider))
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import json
28
+ import re
29
+ from dataclasses import dataclass, field
30
+ from typing import Any
31
+
32
+ import httpx
33
+
34
+ from sofias_sdk_lite.llm.tools import ToolSpec
35
+ from sofias_sdk_lite.observability._log import get_logger
36
+
37
+ logger = get_logger("mcp")
38
+
39
+ __all__ = ["McpError", "McpServer", "McpToolProvider", "mcp_servers_from_message"]
40
+
41
+ PROTOCOL_VERSION = "2025-06-18"
42
+ _UNSUPPORTED = re.compile(r"[^A-Za-z0-9_-]")
43
+
44
+
45
+ class McpError(Exception):
46
+ """An MCP server answered with an error or could not be reached."""
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class McpServer:
51
+ """One connector of the turn, ready to call."""
52
+
53
+ name: str
54
+ url: str
55
+ headers: dict[str, str] = field(default_factory=dict)
56
+ tools: tuple[str, ...] | None = None
57
+ namespace: bool = False
58
+
59
+
60
+ def _field(raw: Any, name: str) -> Any:
61
+ return raw.get(name) if isinstance(raw, dict) else getattr(raw, name, None)
62
+
63
+
64
+ def mcp_servers_from_message(raw_servers: list[Any]) -> list[McpServer]:
65
+ """Read the ``mcp_servers`` of a task message (models or plain dicts)."""
66
+ servers: list[McpServer] = []
67
+ for raw in raw_servers:
68
+ conf = dict(_field(raw, "conf") or _field(raw, "configuration") or {})
69
+ tools = conf.get("__mcp_tools")
70
+ servers.append(
71
+ McpServer(
72
+ name=str(_field(raw, "name")),
73
+ url=conf.get("__mcp_url") or f"http://{_field(raw, 'address')}:{_field(raw, 'port')}/mcp",
74
+ headers=dict(conf.get("__mcp_headers") or {}),
75
+ tools=tuple(tools) if tools else None,
76
+ namespace=bool(conf.get("__mcp_namespace") or conf.get("__mcp_headers")),
77
+ )
78
+ )
79
+ return servers
80
+
81
+
82
+ def _offered_name(server: McpServer, tool: str) -> str:
83
+ if not server.namespace:
84
+ return tool
85
+ return _UNSUPPORTED.sub("_", f"{server.name}__{tool}")[:64]
86
+
87
+
88
+ class _Session:
89
+ """A minimal Streamable HTTP MCP session against one server."""
90
+
91
+ def __init__(self, server: McpServer, client: httpx.AsyncClient) -> None:
92
+ self._server = server
93
+ self._client = client
94
+ self._session_id: str | None = None
95
+ self._next_id = 0
96
+ self._initialized = False
97
+
98
+ async def _post(self, payload: dict[str, Any]) -> dict[str, Any] | None:
99
+ headers = {
100
+ **self._server.headers,
101
+ "Content-Type": "application/json",
102
+ "Accept": "application/json, text/event-stream",
103
+ "MCP-Protocol-Version": PROTOCOL_VERSION,
104
+ }
105
+ if self._session_id:
106
+ headers["Mcp-Session-Id"] = self._session_id
107
+ try:
108
+ response = await self._client.post(self._server.url, json=payload, headers=headers)
109
+ except httpx.HTTPError as exc:
110
+ raise McpError(f"{self._server.name}: unreachable ({type(exc).__name__})") from exc
111
+ self._session_id = response.headers.get("Mcp-Session-Id") or self._session_id
112
+ if response.status_code == 202 or "id" not in payload:
113
+ return None
114
+ if response.status_code >= 400:
115
+ raise McpError(f"{self._server.name}: HTTP {response.status_code}")
116
+ message = self._message(response, payload["id"])
117
+ if message.get("error"):
118
+ raise McpError(f"{self._server.name}: {message['error'].get('message', message['error'])}")
119
+ return message.get("result") or {}
120
+
121
+ @staticmethod
122
+ def _message(response: httpx.Response, id_: int) -> dict[str, Any]:
123
+ if "text/event-stream" not in response.headers.get("Content-Type", ""):
124
+ return response.json()
125
+ messages = []
126
+ for event in re.split(r"\r?\n\r?\n", response.text):
127
+ data = "\n".join(line[5:].strip() for line in event.splitlines() if line.startswith("data:"))
128
+ if data:
129
+ try:
130
+ messages.append(json.loads(data))
131
+ except json.JSONDecodeError:
132
+ continue
133
+ for message in messages:
134
+ if message.get("id") == id_:
135
+ return message
136
+ raise McpError("event stream without an answer")
137
+
138
+ async def request(self, method: str, params: dict[str, Any] | None = None) -> dict[str, Any]:
139
+ if not self._initialized:
140
+ await self._initialize()
141
+ return await self._call(method, params) or {}
142
+
143
+ async def _call(self, method: str, params: dict[str, Any] | None) -> dict[str, Any] | None:
144
+ self._next_id += 1
145
+ payload: dict[str, Any] = {"jsonrpc": "2.0", "id": self._next_id, "method": method}
146
+ if params is not None:
147
+ payload["params"] = params
148
+ return await self._post(payload)
149
+
150
+ async def _initialize(self) -> None:
151
+ await self._call(
152
+ "initialize",
153
+ {"protocolVersion": PROTOCOL_VERSION, "capabilities": {},
154
+ "clientInfo": {"name": "sofias-sdk-lite", "version": "1"}},
155
+ )
156
+ await self._post({"jsonrpc": "2.0", "method": "notifications/initialized"})
157
+ self._initialized = True
158
+
159
+
160
+ class McpToolProvider:
161
+ """``ToolProvider`` over the connectors the platform sent for this turn.
162
+
163
+ Connects lazily on the first ``get_tools``. A connector that cannot be
164
+ reached is skipped (and logged) so the others keep working.
165
+ """
166
+
167
+ def __init__(self, raw_servers: list[Any], *, transport: httpx.AsyncBaseTransport | None = None,
168
+ timeout: float = 60.0) -> None:
169
+ self._servers = mcp_servers_from_message(raw_servers)
170
+ self._client = httpx.AsyncClient(transport=transport, timeout=timeout)
171
+ self._sessions = {server.name: _Session(server, self._client) for server in self._servers}
172
+ self._routes: dict[str, tuple[str, str]] = {}
173
+ self._specs: list[ToolSpec] | None = None
174
+
175
+ async def get_tools(self, node_name: str) -> list[ToolSpec]:
176
+ if self._specs is None:
177
+ self._specs = []
178
+ for server in self._servers:
179
+ try:
180
+ listed = await self._list(server)
181
+ except McpError as exc:
182
+ logger.warning("mcp_server_unavailable", server=server.name, error=str(exc))
183
+ continue
184
+ self._specs.extend(listed)
185
+ return list(self._specs)
186
+
187
+ async def _list(self, server: McpServer) -> list[ToolSpec]:
188
+ specs: list[ToolSpec] = []
189
+ cursor: str | None = None
190
+ while True:
191
+ result = await self._sessions[server.name].request("tools/list", {"cursor": cursor} if cursor else None)
192
+ for tool in result.get("tools", []):
193
+ name = tool.get("name")
194
+ if not name or (server.tools is not None and name not in server.tools):
195
+ continue
196
+ offered = _offered_name(server, name)
197
+ self._routes[offered] = (server.name, name)
198
+ specs.append(ToolSpec(name=offered, description=tool.get("description") or name,
199
+ parameters_schema=tool.get("inputSchema") or {"type": "object"}))
200
+ cursor = result.get("nextCursor")
201
+ if not cursor:
202
+ return specs
203
+
204
+ async def execute_tool(self, tool_name: str, tool_input: dict[str, Any]) -> Any:
205
+ if self._specs is None:
206
+ await self.get_tools("")
207
+ route = self._routes.get(tool_name)
208
+ if route is None:
209
+ raise McpError(f"unknown MCP tool '{tool_name}'")
210
+ server_name, real_name = route
211
+ result = await self._sessions[server_name].request(
212
+ "tools/call", {"name": real_name, "arguments": tool_input or {}}
213
+ )
214
+ if result.get("isError"):
215
+ raise McpError(_text(result) or f"{tool_name} failed")
216
+ return _with_structured(result)
217
+
218
+ async def aclose(self) -> None:
219
+ await self._client.aclose()
220
+
221
+
222
+ def _text(result: dict[str, Any]) -> str:
223
+ return "\n".join(block.get("text", "") for block in result.get("content", []) if block.get("type") == "text")
224
+
225
+
226
+ def _with_structured(result: dict[str, Any]) -> str:
227
+ """The text of a tool result plus its ``structuredContent``, unless the text
228
+ already is that same JSON. Some servers only put a summary in the text."""
229
+ text = _text(result)
230
+ structured = result.get("structuredContent")
231
+ if not structured:
232
+ return text if result.get("content") else json.dumps(result)
233
+ for block in result.get("content", []):
234
+ try:
235
+ if json.loads(block.get("text", "")) == structured:
236
+ return text
237
+ except (TypeError, ValueError):
238
+ continue
239
+ serialized = json.dumps(structured)
240
+ return f"{text}\n{serialized}" if text else serialized
File without changes