solari-sdk 0.1.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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brandazine
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.4
2
+ Name: solari-sdk
3
+ Version: 0.1.0
4
+ Summary: Python client for the SOLARI API — creator and brand intelligence across Instagram and TikTok.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://solari.sh
7
+ Project-URL: Documentation, https://solari.sh/api
8
+ Keywords: solari,brandazine,instagram,tiktok,creator,influencer,brand,sdk,api-client
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # solari-sdk
21
+
22
+ Python client for the [SOLARI API](https://solari.sh/api) — creator and brand intelligence across Instagram and TikTok. Standard library only; Python 3.9+.
23
+
24
+ ```
25
+ pip install solari-sdk
26
+ ```
27
+
28
+ ## Quickstart
29
+
30
+ ```python
31
+ from solari_sdk import Solari
32
+
33
+ solari = Solari() # reads SOLARI_TOKEN; or Solari(token="...")
34
+
35
+ hits = solari.tools.catalog.instagram.account.search(query="nike", limit=3)
36
+ brand = solari.call("solari_insight_instagram_brand_overview", username="nike")
37
+ tools = solari.list_tools()
38
+ ```
39
+
40
+ Get a token with `solari auth token` on a machine that is signed in to the [solari CLI](https://solari.sh/docs), or use a token you already hold from an MCP connector.
41
+
42
+ ## API
43
+
44
+ - `Solari(token=None, base_url="https://solari.sh", timeout=150, user_agent=None, transport=None)`
45
+ - `list_tools()` — every tool the signed-in account can call, with its JSON input schema.
46
+ - `get_tool(name)` — one tool.
47
+ - `call(name, arguments=None, **kwargs)` — run a tool and get its JSON payload back.
48
+ - `tools.<family>.<platform>.<group>.<name>(**kwargs)` — the same call spelled as a path; segments join with `_` under the `solari_` prefix.
49
+ - `me()` — the identity behind the token.
50
+
51
+ Errors raise `SolariError` with `status`, `code`, `message`, `tool`, `retry_after_seconds`, and a `retryable` property (429, 502, 503, 504).
52
+
53
+ ## Development
54
+
55
+ ```
56
+ python3 -m unittest discover -s tests -v
57
+ ```
@@ -0,0 +1,38 @@
1
+ # solari-sdk
2
+
3
+ Python client for the [SOLARI API](https://solari.sh/api) — creator and brand intelligence across Instagram and TikTok. Standard library only; Python 3.9+.
4
+
5
+ ```
6
+ pip install solari-sdk
7
+ ```
8
+
9
+ ## Quickstart
10
+
11
+ ```python
12
+ from solari_sdk import Solari
13
+
14
+ solari = Solari() # reads SOLARI_TOKEN; or Solari(token="...")
15
+
16
+ hits = solari.tools.catalog.instagram.account.search(query="nike", limit=3)
17
+ brand = solari.call("solari_insight_instagram_brand_overview", username="nike")
18
+ tools = solari.list_tools()
19
+ ```
20
+
21
+ Get a token with `solari auth token` on a machine that is signed in to the [solari CLI](https://solari.sh/docs), or use a token you already hold from an MCP connector.
22
+
23
+ ## API
24
+
25
+ - `Solari(token=None, base_url="https://solari.sh", timeout=150, user_agent=None, transport=None)`
26
+ - `list_tools()` — every tool the signed-in account can call, with its JSON input schema.
27
+ - `get_tool(name)` — one tool.
28
+ - `call(name, arguments=None, **kwargs)` — run a tool and get its JSON payload back.
29
+ - `tools.<family>.<platform>.<group>.<name>(**kwargs)` — the same call spelled as a path; segments join with `_` under the `solari_` prefix.
30
+ - `me()` — the identity behind the token.
31
+
32
+ Errors raise `SolariError` with `status`, `code`, `message`, `tool`, `retry_after_seconds`, and a `retryable` property (429, 502, 503, 504).
33
+
34
+ ## Development
35
+
36
+ ```
37
+ python3 -m unittest discover -s tests -v
38
+ ```
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "solari-sdk"
7
+ version = "0.1.0"
8
+ description = "Python client for the SOLARI API — creator and brand intelligence across Instagram and TikTok."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.9"
13
+ dependencies = []
14
+ keywords = ["solari", "brandazine", "instagram", "tiktok", "creator", "influencer", "brand", "sdk", "api-client"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ "Typing :: Typed",
22
+ ]
23
+
24
+ [project.urls]
25
+ Homepage = "https://solari.sh"
26
+ Documentation = "https://solari.sh/api"
27
+
28
+ [tool.setuptools.packages.find]
29
+ include = ["solari_sdk*"]
30
+
31
+ [tool.setuptools.package-data]
32
+ solari_sdk = ["py.typed"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,211 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ import os
6
+ import socket
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from typing import Any, Callable, Mapping, Optional
11
+
12
+ __all__ = ["Solari", "SolariError", "ToolPath", "DEFAULT_BASE_URL", "API_PREFIX", "SDK_VERSION", "TOKEN_ENV"]
13
+
14
+ DEFAULT_BASE_URL = "https://solari.sh"
15
+ API_PREFIX = "/mcp/api/v1"
16
+ SDK_VERSION = "0.1.0"
17
+ TOKEN_ENV = "SOLARI_TOKEN"
18
+ DEFAULT_TIMEOUT_SECONDS = 150.0
19
+
20
+ Transport = Callable[[str, str, Mapping[str, str], Optional[bytes], float], "TransportResponse"]
21
+
22
+ logger = logging.getLogger("solari_sdk")
23
+
24
+
25
+ class TransportResponse:
26
+ __slots__ = ("status", "headers", "body")
27
+
28
+ def __init__(self, status: int, headers: Mapping[str, str], body: bytes) -> None:
29
+ self.status = status
30
+ self.headers = {key.lower(): value for key, value in headers.items()}
31
+ self.body = body
32
+
33
+
34
+ class SolariError(Exception):
35
+ def __init__(
36
+ self,
37
+ status: int,
38
+ code: str,
39
+ message: str,
40
+ tool: Optional[str] = None,
41
+ retry_after_seconds: Optional[int] = None,
42
+ ) -> None:
43
+ super().__init__(message)
44
+ self.status = status
45
+ self.code = code
46
+ self.message = message
47
+ self.tool = tool
48
+ self.retry_after_seconds = retry_after_seconds
49
+
50
+ @property
51
+ def retryable(self) -> bool:
52
+ return self.status in (429, 502, 503, 504)
53
+
54
+ def __repr__(self) -> str:
55
+ return f"SolariError(status={self.status}, code={self.code!r}, message={self.message!r}, tool={self.tool!r})"
56
+
57
+
58
+ def normalize_base_url(raw: str) -> str:
59
+ trimmed = raw.strip().rstrip("/")
60
+ if not trimmed.lower().startswith(("http://", "https://")):
61
+ trimmed = f"https://{trimmed}"
62
+ parsed = urllib.parse.urlsplit(trimmed)
63
+ path = parsed.path.rstrip("/")
64
+ if path.endswith(API_PREFIX):
65
+ path = path[: -len(API_PREFIX)]
66
+ return f"{parsed.scheme}://{parsed.netloc}{path}"
67
+
68
+
69
+ def tool_name(segments: list[str]) -> str:
70
+ parts = [segment.strip() for segment in segments if segment.strip()]
71
+ if not parts:
72
+ raise SolariError(0, "invalid_tool_path", "a tool path needs at least one segment")
73
+ joined = "_".join(parts)
74
+ if joined == "solari" or joined.startswith("solari_"):
75
+ return joined
76
+ return "solari_" + joined
77
+
78
+
79
+ def _urllib_transport(method: str, url: str, headers: Mapping[str, str], body: Optional[bytes], timeout: float) -> TransportResponse:
80
+ request = urllib.request.Request(url, data=body, method=method, headers=dict(headers))
81
+ try:
82
+ with urllib.request.urlopen(request, timeout=timeout) as response:
83
+ return TransportResponse(response.status, dict(response.headers.items()), response.read())
84
+ except urllib.error.HTTPError as error:
85
+ return TransportResponse(error.code, dict(error.headers.items()), error.read())
86
+
87
+
88
+ def _parse_error(response: TransportResponse) -> tuple[str, str, Optional[str]]:
89
+ fallback = (f"http_{response.status}", f"SOLARI API returned HTTP {response.status}", None)
90
+ text = response.body.decode("utf-8", errors="replace") if response.body else ""
91
+ if not text:
92
+ return fallback
93
+ try:
94
+ parsed = json.loads(text)
95
+ except ValueError:
96
+ return (fallback[0], text[:300], None)
97
+ if isinstance(parsed, dict):
98
+ error = parsed.get("error")
99
+ if isinstance(error, dict):
100
+ code = error.get("code") if isinstance(error.get("code"), str) else fallback[0]
101
+ message = error.get("message") if isinstance(error.get("message"), str) else fallback[1]
102
+ tool = error.get("tool") if isinstance(error.get("tool"), str) else None
103
+ return (code, message, tool)
104
+ description = parsed.get("error_description")
105
+ if isinstance(description, str):
106
+ code = error if isinstance(error, str) else fallback[0]
107
+ return (code, description, None)
108
+ return fallback
109
+
110
+
111
+ class ToolPath:
112
+ __slots__ = ("_client", "_segments")
113
+
114
+ def __init__(self, client: "Solari", segments: list[str]) -> None:
115
+ self._client = client
116
+ self._segments = segments
117
+
118
+ def __getattr__(self, segment: str) -> "ToolPath":
119
+ if segment.startswith("_"):
120
+ raise AttributeError(segment)
121
+ return ToolPath(self._client, [*self._segments, segment])
122
+
123
+ def __call__(self, arguments: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> Any:
124
+ merged: dict[str, Any] = dict(arguments or {})
125
+ merged.update(kwargs)
126
+ return self._client.call(tool_name(self._segments), merged)
127
+
128
+ @property
129
+ def tool_name(self) -> str:
130
+ return tool_name(self._segments)
131
+
132
+
133
+ class Solari:
134
+ def __init__(
135
+ self,
136
+ token: Optional[str] = None,
137
+ base_url: str = DEFAULT_BASE_URL,
138
+ timeout: float = DEFAULT_TIMEOUT_SECONDS,
139
+ user_agent: Optional[str] = None,
140
+ transport: Optional[Transport] = None,
141
+ ) -> None:
142
+ resolved = (token or os.environ.get(TOKEN_ENV, "")).strip()
143
+ if not resolved:
144
+ raise SolariError(
145
+ 0,
146
+ "missing_token",
147
+ f'no access token: pass token= or set {TOKEN_ENV} (mint one with "solari auth token")',
148
+ )
149
+ self._token = resolved
150
+ self.base_url = normalize_base_url(base_url)
151
+ self.timeout = timeout
152
+ self.user_agent = user_agent or f"solari-sdk-python/{SDK_VERSION}"
153
+ self._transport = transport or _urllib_transport
154
+ self.tools = ToolPath(self, [])
155
+
156
+ def list_tools(self) -> list[dict[str, Any]]:
157
+ body = self._request("GET", f"{API_PREFIX}/tools")
158
+ tools = body.get("tools") if isinstance(body, dict) else None
159
+ return list(tools) if isinstance(tools, list) else []
160
+
161
+ def get_tool(self, name: str) -> dict[str, Any]:
162
+ body = self._request("GET", f"{API_PREFIX}/tools/{urllib.parse.quote(name, safe='')}")
163
+ return body if isinstance(body, dict) else {}
164
+
165
+ def call(self, name: str, arguments: Optional[Mapping[str, Any]] = None, **kwargs: Any) -> Any:
166
+ merged: dict[str, Any] = dict(arguments or {})
167
+ merged.update(kwargs)
168
+ return self._request("POST", f"{API_PREFIX}/tools/{urllib.parse.quote(name, safe='')}", merged)
169
+
170
+ def me(self) -> dict[str, Any]:
171
+ body = self._request("GET", f"{API_PREFIX}/me")
172
+ return body if isinstance(body, dict) else {}
173
+
174
+ def _request(self, method: str, path: str, body: Optional[Mapping[str, Any]] = None) -> Any:
175
+ headers = {
176
+ "Authorization": f"Bearer {self._token}",
177
+ "Accept": "application/json",
178
+ "User-Agent": self.user_agent,
179
+ }
180
+ payload: Optional[bytes] = None
181
+ if body is not None:
182
+ headers["Content-Type"] = "application/json"
183
+ payload = json.dumps(dict(body)).encode("utf-8")
184
+ url = f"{self.base_url}{path}"
185
+ logger.debug("event=solari_request method=%s path=%s", method, path)
186
+ try:
187
+ response = self._transport(method, url, headers, payload, self.timeout)
188
+ except urllib.error.URLError as error:
189
+ reason = getattr(error, "reason", error)
190
+ timed_out = isinstance(reason, TimeoutError) or "timed out" in str(reason).lower()
191
+ raise SolariError(
192
+ 0,
193
+ "timeout" if timed_out else "network_error",
194
+ f"SOLARI API did not answer within {int(self.timeout)}s" if timed_out else f"could not reach SOLARI API: {reason}",
195
+ ) from error
196
+ except (TimeoutError, socket.timeout) as error:
197
+ raise SolariError(0, "timeout", f"SOLARI API did not answer within {int(self.timeout)}s") from error
198
+ logger.debug("event=solari_response method=%s path=%s status=%s", method, path, response.status)
199
+ if response.status < 200 or response.status >= 300:
200
+ code, message, tool = _parse_error(response)
201
+ retry_after: Optional[int] = None
202
+ raw_retry = response.headers.get("retry-after")
203
+ if raw_retry and raw_retry.isdigit():
204
+ retry_after = int(raw_retry)
205
+ raise SolariError(response.status, code, message, tool, retry_after)
206
+ if not response.body:
207
+ return None
208
+ try:
209
+ return json.loads(response.body.decode("utf-8"))
210
+ except ValueError as error:
211
+ raise SolariError(response.status, "invalid_response", "SOLARI API returned non-JSON") from error
File without changes
@@ -0,0 +1,57 @@
1
+ Metadata-Version: 2.4
2
+ Name: solari-sdk
3
+ Version: 0.1.0
4
+ Summary: Python client for the SOLARI API — creator and brand intelligence across Instagram and TikTok.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://solari.sh
7
+ Project-URL: Documentation, https://solari.sh/api
8
+ Keywords: solari,brandazine,instagram,tiktok,creator,influencer,brand,sdk,api-client
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # solari-sdk
21
+
22
+ Python client for the [SOLARI API](https://solari.sh/api) — creator and brand intelligence across Instagram and TikTok. Standard library only; Python 3.9+.
23
+
24
+ ```
25
+ pip install solari-sdk
26
+ ```
27
+
28
+ ## Quickstart
29
+
30
+ ```python
31
+ from solari_sdk import Solari
32
+
33
+ solari = Solari() # reads SOLARI_TOKEN; or Solari(token="...")
34
+
35
+ hits = solari.tools.catalog.instagram.account.search(query="nike", limit=3)
36
+ brand = solari.call("solari_insight_instagram_brand_overview", username="nike")
37
+ tools = solari.list_tools()
38
+ ```
39
+
40
+ Get a token with `solari auth token` on a machine that is signed in to the [solari CLI](https://solari.sh/docs), or use a token you already hold from an MCP connector.
41
+
42
+ ## API
43
+
44
+ - `Solari(token=None, base_url="https://solari.sh", timeout=150, user_agent=None, transport=None)`
45
+ - `list_tools()` — every tool the signed-in account can call, with its JSON input schema.
46
+ - `get_tool(name)` — one tool.
47
+ - `call(name, arguments=None, **kwargs)` — run a tool and get its JSON payload back.
48
+ - `tools.<family>.<platform>.<group>.<name>(**kwargs)` — the same call spelled as a path; segments join with `_` under the `solari_` prefix.
49
+ - `me()` — the identity behind the token.
50
+
51
+ Errors raise `SolariError` with `status`, `code`, `message`, `tool`, `retry_after_seconds`, and a `retryable` property (429, 502, 503, 504).
52
+
53
+ ## Development
54
+
55
+ ```
56
+ python3 -m unittest discover -s tests -v
57
+ ```
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ solari_sdk/__init__.py
5
+ solari_sdk/py.typed
6
+ solari_sdk.egg-info/PKG-INFO
7
+ solari_sdk.egg-info/SOURCES.txt
8
+ solari_sdk.egg-info/dependency_links.txt
9
+ solari_sdk.egg-info/top_level.txt
10
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ solari_sdk
@@ -0,0 +1,152 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import os
5
+ import unittest
6
+ import urllib.error
7
+ from typing import Any, Mapping, Optional
8
+
9
+ from solari_sdk import TOKEN_ENV, Solari, SolariError, TransportResponse, normalize_base_url, tool_name
10
+
11
+
12
+ class Recorder:
13
+ def __init__(self, responder):
14
+ self.calls: list[dict[str, Any]] = []
15
+ self._responder = responder
16
+
17
+ def __call__(self, method: str, url: str, headers: Mapping[str, str], body: Optional[bytes], timeout: float) -> TransportResponse:
18
+ call = {"method": method, "url": url, "headers": dict(headers), "body": body, "timeout": timeout}
19
+ self.calls.append(call)
20
+ return self._responder(call)
21
+
22
+
23
+ def json_response(payload: Any, status: int = 200, headers: Optional[dict[str, str]] = None) -> TransportResponse:
24
+ return TransportResponse(status, {"content-type": "application/json", **(headers or {})}, json.dumps(payload).encode("utf-8"))
25
+
26
+
27
+ class ConstructionTests(unittest.TestCase):
28
+ def setUp(self) -> None:
29
+ self._saved = os.environ.pop(TOKEN_ENV, None)
30
+
31
+ def tearDown(self) -> None:
32
+ if self._saved is None:
33
+ os.environ.pop(TOKEN_ENV, None)
34
+ else:
35
+ os.environ[TOKEN_ENV] = self._saved
36
+
37
+ def test_requires_a_token_from_argument_or_environment(self) -> None:
38
+ with self.assertRaises(SolariError) as raised:
39
+ Solari()
40
+ self.assertEqual(raised.exception.code, "missing_token")
41
+ os.environ[TOKEN_ENV] = "env-token"
42
+ self.assertEqual(Solari().base_url, "https://solari.sh")
43
+
44
+ def test_normalizes_the_base_url(self) -> None:
45
+ self.assertEqual(normalize_base_url("https://solari.sh/"), "https://solari.sh")
46
+ self.assertEqual(normalize_base_url("solari.sh"), "https://solari.sh")
47
+ self.assertEqual(normalize_base_url("https://solari.sh/mcp/api/v1"), "https://solari.sh")
48
+ self.assertEqual(normalize_base_url("http://localhost:8787/"), "http://localhost:8787")
49
+
50
+ def test_builds_tool_names_from_segments(self) -> None:
51
+ self.assertEqual(tool_name(["catalog", "instagram", "account", "search"]), "solari_catalog_instagram_account_search")
52
+ self.assertEqual(tool_name(["solari_insight_instagram_brand_overview"]), "solari_insight_instagram_brand_overview")
53
+ with self.assertRaises(SolariError):
54
+ tool_name([])
55
+
56
+
57
+ class RequestTests(unittest.TestCase):
58
+ def test_lists_tools_with_bearer_and_user_agent(self) -> None:
59
+ transport = Recorder(lambda call: json_response({"tools": [{"name": "solari_catalog_instagram_account_search"}]}))
60
+ client = Solari(token="tok", transport=transport)
61
+
62
+ tools = client.list_tools()
63
+
64
+ self.assertEqual([tool["name"] for tool in tools], ["solari_catalog_instagram_account_search"])
65
+ call = transport.calls[0]
66
+ self.assertEqual(call["url"], "https://solari.sh/mcp/api/v1/tools")
67
+ self.assertEqual(call["headers"]["Authorization"], "Bearer tok")
68
+ self.assertIn("solari-sdk-python/", call["headers"]["User-Agent"])
69
+ self.assertIsNone(call["body"])
70
+
71
+ def test_calls_a_tool_with_a_json_body(self) -> None:
72
+ transport = Recorder(lambda call: json_response({"found": True, "items": [{"username": "nike"}]}))
73
+ client = Solari(token="tok", base_url="https://example.test/", transport=transport)
74
+
75
+ result = client.call("solari_catalog_instagram_account_search", {"query": "nike"}, limit=3)
76
+
77
+ self.assertTrue(result["found"])
78
+ call = transport.calls[0]
79
+ self.assertEqual(call["method"], "POST")
80
+ self.assertEqual(call["url"], "https://example.test/mcp/api/v1/tools/solari_catalog_instagram_account_search")
81
+ self.assertEqual(call["headers"]["Content-Type"], "application/json")
82
+ self.assertEqual(json.loads(call["body"]), {"query": "nike", "limit": 3})
83
+
84
+ def test_tools_proxy_turns_attribute_path_into_a_call(self) -> None:
85
+ transport = Recorder(lambda call: json_response({"items": []}))
86
+ client = Solari(token="tok", transport=transport)
87
+
88
+ client.tools.catalog.instagram.account.search(query="nike", limit=3)
89
+ client.tools.insight.instagram.brand.overview()
90
+
91
+ names = [call["url"].split("/tools/")[1] for call in transport.calls]
92
+ self.assertEqual(names, ["solari_catalog_instagram_account_search", "solari_insight_instagram_brand_overview"])
93
+ self.assertEqual(json.loads(transport.calls[1]["body"]), {})
94
+ self.assertEqual(client.tools.fetch.tiktok.account.tool_name, "solari_fetch_tiktok_account")
95
+
96
+ def test_get_tool_and_me(self) -> None:
97
+ def responder(call: dict[str, Any]) -> TransportResponse:
98
+ if call["url"].endswith("/me"):
99
+ return json_response({"sub": "abc", "email": "a@b.c"})
100
+ return json_response({"name": "solari_fetch_instagram_account"})
101
+
102
+ transport = Recorder(responder)
103
+ client = Solari(token="tok", transport=transport)
104
+
105
+ self.assertEqual(client.get_tool("solari_fetch_instagram_account")["name"], "solari_fetch_instagram_account")
106
+ self.assertEqual(client.me()["sub"], "abc")
107
+ self.assertEqual(transport.calls[0]["url"], "https://solari.sh/mcp/api/v1/tools/solari_fetch_instagram_account")
108
+
109
+
110
+ class ErrorTests(unittest.TestCase):
111
+ def test_surfaces_the_api_error_envelope(self) -> None:
112
+ transport = Recorder(
113
+ lambda call: json_response(
114
+ {"error": {"code": "rate_limited", "message": "rate limited, retry shortly", "tool": "solari_x"}},
115
+ status=429,
116
+ headers={"retry-after": "7"},
117
+ )
118
+ )
119
+ client = Solari(token="tok", transport=transport)
120
+
121
+ with self.assertRaises(SolariError) as raised:
122
+ client.call("solari_x")
123
+
124
+ error = raised.exception
125
+ self.assertEqual(error.status, 429)
126
+ self.assertEqual(error.code, "rate_limited")
127
+ self.assertEqual(error.tool, "solari_x")
128
+ self.assertEqual(error.retry_after_seconds, 7)
129
+ self.assertTrue(error.retryable)
130
+
131
+ def test_maps_oauth_layer_and_plain_failures(self) -> None:
132
+ oauth = Recorder(lambda call: json_response({"error": "invalid_token", "error_description": "Invalid access token"}, status=401))
133
+ with self.assertRaises(SolariError) as raised:
134
+ Solari(token="tok", transport=oauth).list_tools()
135
+ self.assertEqual((raised.exception.status, raised.exception.code), (401, "invalid_token"))
136
+
137
+ plain = Recorder(lambda call: TransportResponse(500, {}, b"boom"))
138
+ with self.assertRaises(SolariError) as raised_plain:
139
+ Solari(token="tok", transport=plain).list_tools()
140
+ self.assertEqual((raised_plain.exception.status, raised_plain.exception.code, raised_plain.exception.message), (500, "http_500", "boom"))
141
+
142
+ def test_wraps_network_failures(self) -> None:
143
+ def failing(method, url, headers, body, timeout):
144
+ raise urllib.error.URLError("connection refused")
145
+
146
+ with self.assertRaises(SolariError) as raised:
147
+ Solari(token="tok", transport=failing).list_tools()
148
+ self.assertEqual(raised.exception.code, "network_error")
149
+
150
+
151
+ if __name__ == "__main__":
152
+ unittest.main()