langchain-crossly 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,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .env
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-30)
4
+
5
+ First release.
6
+
7
+ - `CrosslyToolkit` with 15 tools: search, list and get listings, create a draft, update a price, crosspost,
8
+ delist, list inventory, adjust quantity, list and get orders, mark shipped, list and answer offers, and the
9
+ sales summary.
10
+ - `read_only`, `include_destructive` and `selected_tools` toolkit options.
11
+ - Sync and async tools over the Crossly REST API with retries, `Retry-After` and idempotency keys on writes.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Crossly
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,182 @@
1
+ Metadata-Version: 2.5
2
+ Name: langchain-crossly
3
+ Version: 0.1.0
4
+ Summary: LangChain tools for Crossly: search, crosspost and delist listings, manage inventory, ship orders, answer offers and read sales across eBay, Poshmark, Mercari, Depop and more.
5
+ Project-URL: Homepage, https://crossly.net
6
+ Project-URL: Documentation, https://github.com/crossly-dev/langchain-crossly#readme
7
+ Project-URL: Source, https://github.com/crossly-dev/langchain-crossly
8
+ Project-URL: Issues, https://github.com/crossly-dev/langchain-crossly/issues
9
+ Project-URL: Changelog, https://github.com/crossly-dev/langchain-crossly/blob/main/CHANGELOG.md
10
+ Project-URL: API docs, https://crossly.net/docs/api-quickstart
11
+ Author-email: Crossly <support@crossly.net>
12
+ License-Expression: MIT
13
+ License-File: LICENSE
14
+ Keywords: agents,crosslisting,crossly,depop,ebay,langchain,mercari,poshmark,reselling,tools
15
+ Classifier: Development Status :: 4 - Beta
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3 :: Only
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Classifier: Topic :: Office/Business
25
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Classifier: Typing :: Typed
28
+ Requires-Python: >=3.10
29
+ Requires-Dist: httpx<1.0.0,>=0.25.0
30
+ Requires-Dist: langchain-core<2.0.0,>=1.0.0
31
+ Requires-Dist: pydantic<3.0.0,>=2.7.4
32
+ Description-Content-Type: text/markdown
33
+
34
+ # langchain-crossly
35
+
36
+ [![PyPI](https://img.shields.io/pypi/v/langchain-crossly)](https://pypi.org/project/langchain-crossly/)
37
+ [![ci](https://github.com/crossly-dev/langchain-crossly/actions/workflows/ci.yml/badge.svg)](https://github.com/crossly-dev/langchain-crossly/actions/workflows/ci.yml)
38
+
39
+ LangChain tools for [Crossly](https://crossly.net), the crosslisting platform for resellers. With them an agent
40
+ can work a seller's Crossly account: find and price listings, crosspost them to eBay, Poshmark, Mercari, Depop,
41
+ Etsy and other marketplaces, delist, keep stock counts right, ship orders, answer offers and read the sales
42
+ numbers.
43
+
44
+ ## Installation
45
+
46
+ ```bash
47
+ pip install -U langchain-crossly
48
+ ```
49
+
50
+ Python 3.10 or newer, `langchain-core` 1.x.
51
+
52
+ ## Credentials
53
+
54
+ The tools authenticate with a Crossly **Personal Access Token** (it starts with `crossly_pat_`). Create one in
55
+ Crossly under **Settings → Developer** ([create a free account](https://crossly.net/register)), then set it as
56
+ `CROSSLY_API_KEY`:
57
+
58
+ ```bash
59
+ export CROSSLY_API_KEY="crossly_pat_..."
60
+ ```
61
+
62
+ or pass it in code: `CrosslyToolkit(api_key="crossly_pat_...")`. The token's scopes limit what the tools can do;
63
+ a read-only token is enough for the read-only toolkit below.
64
+
65
+ `CROSSLY_BASE_URL` (default `https://crossly.net/api`) points the tools at another server, for example the
66
+ [Crossly mock API](https://github.com/crossly-dev/crossly-mock) in tests.
67
+
68
+ ## Toolkit
69
+
70
+ ```python
71
+ from langchain_crossly import CrosslyToolkit
72
+
73
+ toolkit = CrosslyToolkit()
74
+ tools = toolkit.get_tools()
75
+
76
+ for tool in tools:
77
+ print(tool.name)
78
+ ```
79
+
80
+ | Tool | What it does |
81
+ | --- | --- |
82
+ | `crossly_search` | Search inventory, listings, orders, sales, customers and offers at once (SKU, order number, URL, title…) |
83
+ | `crossly_list_listings` | List listings across marketplaces, filtered by status, marketplace or SKU |
84
+ | `crossly_get_listing` | One listing with every marketplace copy, its status, URL and any publish error |
85
+ | `crossly_create_draft_listing` | Save an item to inventory as an unlisted draft |
86
+ | `crossly_update_listing_price` | Change a price on every marketplace, or only the ones named |
87
+ | `crossly_crosspost_listing` | Publish a listing or a draft item to one or more marketplaces |
88
+ | `crossly_delist_listing` | **Destructive.** End a listing everywhere, or on the marketplaces named |
89
+ | `crossly_list_inventory` | List inventory items with quantities and where each is listed |
90
+ | `crossly_adjust_inventory_quantity` | Change available stock by a delta or to a count, with a reason |
91
+ | `crossly_list_orders` | List orders with prices, fees, buyer and shipping status |
92
+ | `crossly_get_order` | One order with line items, address and tracking |
93
+ | `crossly_mark_order_shipped` | Mark an order shipped and upload tracking to the marketplace |
94
+ | `crossly_list_offers` | Offers on Crossly Shop listings, or marketplace conversations waiting on a reply |
95
+ | `crossly_respond_to_offer` | **Destructive.** Accept, decline or counter an offer |
96
+ | `crossly_get_sales_summary` | Sales, units, revenue, fees, net sales and net profit for the last N days |
97
+
98
+ Every tool returns the API's JSON response as a string. Errors (a missing token, an unknown id, a marketplace
99
+ that isn't connected) come back as the tool's output, so the agent can fix its arguments or tell the user.
100
+
101
+ ### Choosing tools
102
+
103
+ ```python
104
+ # Only tools that read data: nothing is listed, repriced, shipped or answered.
105
+ CrosslyToolkit(read_only=True).get_tools()
106
+
107
+ # Everything except the destructive tools (delist, respond to offer).
108
+ CrosslyToolkit(include_destructive=False).get_tools()
109
+
110
+ # A hand-picked set.
111
+ CrosslyToolkit(selected_tools=["crossly_list_orders", "crossly_mark_order_shipped"]).get_tools()
112
+ ```
113
+
114
+ Each tool also has a `destructive` attribute, so you can put the destructive ones behind a human approval step
115
+ (for example LangChain's human-in-the-loop middleware).
116
+
117
+ ### Using one tool
118
+
119
+ ```python
120
+ from langchain_crossly import CrosslyListListingsTool
121
+
122
+ tool = CrosslyListListingsTool()
123
+ print(tool.invoke({"status": "active", "platform": "ebay", "sort_by": "days_listed", "sort_order": "desc", "limit": 5}))
124
+ ```
125
+
126
+ Tools are also async: `await tool.ainvoke({...})`.
127
+
128
+ ## Use within an agent
129
+
130
+ ```python
131
+ from langchain.agents import create_agent
132
+ from langchain_crossly import CrosslyToolkit
133
+
134
+ tools = CrosslyToolkit(include_destructive=False).get_tools()
135
+
136
+ agent = create_agent(
137
+ "anthropic:claude-sonnet-4-5",
138
+ tools,
139
+ system_prompt="You help a reseller run their Crossly store. Prices are in dollars.",
140
+ )
141
+
142
+ result = agent.invoke(
143
+ {"messages": [("user", "Which of my eBay listings have been up longest? Drop the oldest one by 10%.")]}
144
+ )
145
+ print(result["messages"][-1].content)
146
+ ```
147
+
148
+ Any chat model with tool calling works; install its LangChain package (here `langchain-anthropic`) and `langchain`.
149
+
150
+ ### Prefer MCP?
151
+
152
+ Crossly also runs a hosted MCP server with the full API at `https://crossly.net/mcp`
153
+ ([crossly-mcp](https://github.com/crossly-dev/crossly-mcp)). Use it with `langchain-mcp-adapters` when you want
154
+ every endpoint rather than this focused tool set.
155
+
156
+ ## Development
157
+
158
+ ```bash
159
+ uv sync --group test
160
+ uv run pytest tests/unit_tests # mocked HTTP + langchain-tests standard unit tests
161
+ CROSSLY_API_KEY=crossly_pat_... uv run pytest tests/integration_tests # read-only tools against the live API
162
+ ```
163
+
164
+ The integration tests only call read-only tools and are skipped when `CROSSLY_API_KEY` is not set.
165
+
166
+ ## Releases
167
+
168
+ Pushing a `v*` tag builds, tests and publishes to PyPI with signed build provenance. Check a downloaded file
169
+ with:
170
+
171
+ ```bash
172
+ gh attestation verify langchain_crossly-0.1.0-py3-none-any.whl --repo crossly-dev/langchain-crossly
173
+ ```
174
+
175
+ ## Links
176
+
177
+ - Crossly API quickstart: https://crossly.net/docs/api-quickstart
178
+ - Python SDK: https://github.com/crossly-dev/crossly-python
179
+ - CrewAI tools: https://github.com/crossly-dev/crewai-crossly
180
+ - Issues: https://github.com/crossly-dev/langchain-crossly/issues
181
+
182
+ MIT licensed.
@@ -0,0 +1,149 @@
1
+ # langchain-crossly
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/langchain-crossly)](https://pypi.org/project/langchain-crossly/)
4
+ [![ci](https://github.com/crossly-dev/langchain-crossly/actions/workflows/ci.yml/badge.svg)](https://github.com/crossly-dev/langchain-crossly/actions/workflows/ci.yml)
5
+
6
+ LangChain tools for [Crossly](https://crossly.net), the crosslisting platform for resellers. With them an agent
7
+ can work a seller's Crossly account: find and price listings, crosspost them to eBay, Poshmark, Mercari, Depop,
8
+ Etsy and other marketplaces, delist, keep stock counts right, ship orders, answer offers and read the sales
9
+ numbers.
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ pip install -U langchain-crossly
15
+ ```
16
+
17
+ Python 3.10 or newer, `langchain-core` 1.x.
18
+
19
+ ## Credentials
20
+
21
+ The tools authenticate with a Crossly **Personal Access Token** (it starts with `crossly_pat_`). Create one in
22
+ Crossly under **Settings → Developer** ([create a free account](https://crossly.net/register)), then set it as
23
+ `CROSSLY_API_KEY`:
24
+
25
+ ```bash
26
+ export CROSSLY_API_KEY="crossly_pat_..."
27
+ ```
28
+
29
+ or pass it in code: `CrosslyToolkit(api_key="crossly_pat_...")`. The token's scopes limit what the tools can do;
30
+ a read-only token is enough for the read-only toolkit below.
31
+
32
+ `CROSSLY_BASE_URL` (default `https://crossly.net/api`) points the tools at another server, for example the
33
+ [Crossly mock API](https://github.com/crossly-dev/crossly-mock) in tests.
34
+
35
+ ## Toolkit
36
+
37
+ ```python
38
+ from langchain_crossly import CrosslyToolkit
39
+
40
+ toolkit = CrosslyToolkit()
41
+ tools = toolkit.get_tools()
42
+
43
+ for tool in tools:
44
+ print(tool.name)
45
+ ```
46
+
47
+ | Tool | What it does |
48
+ | --- | --- |
49
+ | `crossly_search` | Search inventory, listings, orders, sales, customers and offers at once (SKU, order number, URL, title…) |
50
+ | `crossly_list_listings` | List listings across marketplaces, filtered by status, marketplace or SKU |
51
+ | `crossly_get_listing` | One listing with every marketplace copy, its status, URL and any publish error |
52
+ | `crossly_create_draft_listing` | Save an item to inventory as an unlisted draft |
53
+ | `crossly_update_listing_price` | Change a price on every marketplace, or only the ones named |
54
+ | `crossly_crosspost_listing` | Publish a listing or a draft item to one or more marketplaces |
55
+ | `crossly_delist_listing` | **Destructive.** End a listing everywhere, or on the marketplaces named |
56
+ | `crossly_list_inventory` | List inventory items with quantities and where each is listed |
57
+ | `crossly_adjust_inventory_quantity` | Change available stock by a delta or to a count, with a reason |
58
+ | `crossly_list_orders` | List orders with prices, fees, buyer and shipping status |
59
+ | `crossly_get_order` | One order with line items, address and tracking |
60
+ | `crossly_mark_order_shipped` | Mark an order shipped and upload tracking to the marketplace |
61
+ | `crossly_list_offers` | Offers on Crossly Shop listings, or marketplace conversations waiting on a reply |
62
+ | `crossly_respond_to_offer` | **Destructive.** Accept, decline or counter an offer |
63
+ | `crossly_get_sales_summary` | Sales, units, revenue, fees, net sales and net profit for the last N days |
64
+
65
+ Every tool returns the API's JSON response as a string. Errors (a missing token, an unknown id, a marketplace
66
+ that isn't connected) come back as the tool's output, so the agent can fix its arguments or tell the user.
67
+
68
+ ### Choosing tools
69
+
70
+ ```python
71
+ # Only tools that read data: nothing is listed, repriced, shipped or answered.
72
+ CrosslyToolkit(read_only=True).get_tools()
73
+
74
+ # Everything except the destructive tools (delist, respond to offer).
75
+ CrosslyToolkit(include_destructive=False).get_tools()
76
+
77
+ # A hand-picked set.
78
+ CrosslyToolkit(selected_tools=["crossly_list_orders", "crossly_mark_order_shipped"]).get_tools()
79
+ ```
80
+
81
+ Each tool also has a `destructive` attribute, so you can put the destructive ones behind a human approval step
82
+ (for example LangChain's human-in-the-loop middleware).
83
+
84
+ ### Using one tool
85
+
86
+ ```python
87
+ from langchain_crossly import CrosslyListListingsTool
88
+
89
+ tool = CrosslyListListingsTool()
90
+ print(tool.invoke({"status": "active", "platform": "ebay", "sort_by": "days_listed", "sort_order": "desc", "limit": 5}))
91
+ ```
92
+
93
+ Tools are also async: `await tool.ainvoke({...})`.
94
+
95
+ ## Use within an agent
96
+
97
+ ```python
98
+ from langchain.agents import create_agent
99
+ from langchain_crossly import CrosslyToolkit
100
+
101
+ tools = CrosslyToolkit(include_destructive=False).get_tools()
102
+
103
+ agent = create_agent(
104
+ "anthropic:claude-sonnet-4-5",
105
+ tools,
106
+ system_prompt="You help a reseller run their Crossly store. Prices are in dollars.",
107
+ )
108
+
109
+ result = agent.invoke(
110
+ {"messages": [("user", "Which of my eBay listings have been up longest? Drop the oldest one by 10%.")]}
111
+ )
112
+ print(result["messages"][-1].content)
113
+ ```
114
+
115
+ Any chat model with tool calling works; install its LangChain package (here `langchain-anthropic`) and `langchain`.
116
+
117
+ ### Prefer MCP?
118
+
119
+ Crossly also runs a hosted MCP server with the full API at `https://crossly.net/mcp`
120
+ ([crossly-mcp](https://github.com/crossly-dev/crossly-mcp)). Use it with `langchain-mcp-adapters` when you want
121
+ every endpoint rather than this focused tool set.
122
+
123
+ ## Development
124
+
125
+ ```bash
126
+ uv sync --group test
127
+ uv run pytest tests/unit_tests # mocked HTTP + langchain-tests standard unit tests
128
+ CROSSLY_API_KEY=crossly_pat_... uv run pytest tests/integration_tests # read-only tools against the live API
129
+ ```
130
+
131
+ The integration tests only call read-only tools and are skipped when `CROSSLY_API_KEY` is not set.
132
+
133
+ ## Releases
134
+
135
+ Pushing a `v*` tag builds, tests and publishes to PyPI with signed build provenance. Check a downloaded file
136
+ with:
137
+
138
+ ```bash
139
+ gh attestation verify langchain_crossly-0.1.0-py3-none-any.whl --repo crossly-dev/langchain-crossly
140
+ ```
141
+
142
+ ## Links
143
+
144
+ - Crossly API quickstart: https://crossly.net/docs/api-quickstart
145
+ - Python SDK: https://github.com/crossly-dev/crossly-python
146
+ - CrewAI tools: https://github.com/crossly-dev/crewai-crossly
147
+ - Issues: https://github.com/crossly-dev/langchain-crossly/issues
148
+
149
+ MIT licensed.
@@ -0,0 +1,48 @@
1
+ """LangChain integration for Crossly, the crosslisting platform for resellers."""
2
+
3
+ from langchain_crossly._client import CrosslyAPIWrapper, CrosslyError
4
+ from langchain_crossly._version import __version__
5
+ from langchain_crossly.toolkits import CrosslyToolkit
6
+ from langchain_crossly.tools import (
7
+ ALL_TOOLS,
8
+ CrosslyBaseTool,
9
+ CrosslySearchTool,
10
+ CrosslyListListingsTool,
11
+ CrosslyGetListingTool,
12
+ CrosslyCreateDraftListingTool,
13
+ CrosslyUpdateListingPriceTool,
14
+ CrosslyCrosspostListingTool,
15
+ CrosslyDelistListingTool,
16
+ CrosslyListInventoryTool,
17
+ CrosslyAdjustInventoryQuantityTool,
18
+ CrosslyListOrdersTool,
19
+ CrosslyGetOrderTool,
20
+ CrosslyMarkOrderShippedTool,
21
+ CrosslyListOffersTool,
22
+ CrosslyRespondToOfferTool,
23
+ CrosslyGetSalesSummaryTool,
24
+ )
25
+
26
+ __all__ = [
27
+ "ALL_TOOLS",
28
+ "CrosslyAPIWrapper",
29
+ "CrosslyBaseTool",
30
+ "CrosslyError",
31
+ "CrosslyToolkit",
32
+ "CrosslySearchTool",
33
+ "CrosslyListListingsTool",
34
+ "CrosslyGetListingTool",
35
+ "CrosslyCreateDraftListingTool",
36
+ "CrosslyUpdateListingPriceTool",
37
+ "CrosslyCrosspostListingTool",
38
+ "CrosslyDelistListingTool",
39
+ "CrosslyListInventoryTool",
40
+ "CrosslyAdjustInventoryQuantityTool",
41
+ "CrosslyListOrdersTool",
42
+ "CrosslyGetOrderTool",
43
+ "CrosslyMarkOrderShippedTool",
44
+ "CrosslyListOffersTool",
45
+ "CrosslyRespondToOfferTool",
46
+ "CrosslyGetSalesSummaryTool",
47
+ "__version__",
48
+ ]
@@ -0,0 +1,225 @@
1
+ """A small HTTP client for the Crossly seller REST API (https://crossly.net/api/v1).
2
+
3
+ Every call sends the Personal Access Token as a bearer token, a ``langchain-crossly/<version>`` User-Agent and,
4
+ for writes, an ``Idempotency-Key`` that stays the same across retries of that call. 429 responses are retried for
5
+ every method (honouring ``Retry-After``); 5xx and network errors only for reads.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import asyncio
11
+ import email.utils
12
+ import json
13
+ import os
14
+ import time
15
+ import uuid
16
+ from typing import Any, Dict, Mapping, Optional
17
+
18
+ import httpx
19
+ from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator
20
+
21
+ from ._version import PACKAGE, __version__
22
+
23
+ DEFAULT_BASE_URL = "https://crossly.net/api"
24
+ API_KEY_ENV = "CROSSLY_API_KEY"
25
+ BASE_URL_ENV = "CROSSLY_BASE_URL"
26
+
27
+ _READS = frozenset(("GET", "HEAD"))
28
+ _TRANSIENT = frozenset((500, 502, 503, 504))
29
+ _MAX_RETRY_WAIT = 10.0
30
+
31
+
32
+ class CrosslyError(Exception):
33
+ """A failed Crossly API call (or missing configuration), with a message an agent can act on."""
34
+
35
+ def __init__(self, message: str, status: Optional[int] = None, code: Optional[str] = None) -> None:
36
+ super().__init__(message)
37
+ self.status = status
38
+ self.code = code
39
+
40
+
41
+ def _retry_after(value: Optional[str]) -> Optional[float]:
42
+ if not value:
43
+ return None
44
+ try:
45
+ return max(0.0, float(value))
46
+ except ValueError:
47
+ pass
48
+ try:
49
+ when = email.utils.parsedate_to_datetime(value)
50
+ except (TypeError, ValueError):
51
+ return None
52
+ return max(0.0, when.timestamp() - time.time())
53
+
54
+
55
+ def _clean(params: Optional[Mapping[str, Any]]) -> Optional[Dict[str, Any]]:
56
+ """Drop unset values and render booleans the way the API's query parser reads them."""
57
+ if not params:
58
+ return None
59
+ out: Dict[str, Any] = {}
60
+ for key, value in params.items():
61
+ if value is None:
62
+ continue
63
+ out[key] = ("true" if value else "false") if isinstance(value, bool) else value
64
+ return out or None
65
+
66
+
67
+ def _error(response: httpx.Response) -> CrosslyError:
68
+ try:
69
+ payload = response.json()
70
+ except ValueError:
71
+ payload = None
72
+ code = message = correlation = None
73
+ if isinstance(payload, dict):
74
+ err = payload.get("error")
75
+ if isinstance(err, dict):
76
+ code, message = err.get("code"), err.get("message")
77
+ elif isinstance(err, str):
78
+ message = err
79
+ message = message or payload.get("message")
80
+ correlation = payload.get("correlationId")
81
+ text = f"Crossly API error {response.status_code}"
82
+ if code:
83
+ text += f" {code}"
84
+ text += f": {message or response.reason_phrase or 'request failed'}"
85
+ if response.status_code == 401:
86
+ text += " (check that CROSSLY_API_KEY is a valid crossly_pat_ token)"
87
+ if correlation:
88
+ text += f" [correlationId {correlation}]"
89
+ return CrosslyError(text, status=response.status_code, code=code)
90
+
91
+
92
+ def _result(response: httpx.Response) -> Any:
93
+ if response.status_code >= 400:
94
+ raise _error(response)
95
+ if not response.content:
96
+ return {"ok": True, "status": response.status_code}
97
+ try:
98
+ return response.json()
99
+ except ValueError:
100
+ return {"ok": True, "status": response.status_code, "body": response.text}
101
+
102
+
103
+ class CrosslyAPIWrapper(BaseModel):
104
+ """Configuration and transport for the Crossly seller API.
105
+
106
+ ``api_key`` defaults to the ``CROSSLY_API_KEY`` environment variable (a Personal Access Token,
107
+ ``crossly_pat_…``, from Crossly → Settings → Developer). It is read when the wrapper is built and checked
108
+ when a tool runs, so a toolkit can be constructed before the key is configured.
109
+ """
110
+
111
+ model_config = ConfigDict(arbitrary_types_allowed=True)
112
+
113
+ api_key: Optional[SecretStr] = Field(default=None)
114
+ base_url: str = Field(default=DEFAULT_BASE_URL)
115
+ timeout: float = Field(default=30.0)
116
+ max_retries: int = Field(default=2)
117
+ user_agent: str = Field(default=f"{PACKAGE}/{__version__}")
118
+
119
+ @model_validator(mode="before")
120
+ @classmethod
121
+ def _from_env(cls, values: Any) -> Any:
122
+ if not isinstance(values, dict):
123
+ return values
124
+ values = dict(values)
125
+ if not values.get("api_key") and os.environ.get(API_KEY_ENV):
126
+ values["api_key"] = os.environ[API_KEY_ENV]
127
+ if not values.get("base_url") and os.environ.get(BASE_URL_ENV):
128
+ values["base_url"] = os.environ[BASE_URL_ENV]
129
+ return values
130
+
131
+ def _headers(self, method: str, idempotency_key: Optional[str]) -> Dict[str, str]:
132
+ if self.api_key is None or not self.api_key.get_secret_value():
133
+ raise CrosslyError(
134
+ f"No Crossly API key. Set the {API_KEY_ENV} environment variable to a Personal Access Token "
135
+ "(crossly_pat_…, from Crossly → Settings → Developer) or pass api_key."
136
+ )
137
+ headers = {
138
+ "Authorization": f"Bearer {self.api_key.get_secret_value()}",
139
+ "Accept": "application/json",
140
+ "User-Agent": self.user_agent,
141
+ }
142
+ if method not in _READS:
143
+ headers["Idempotency-Key"] = idempotency_key or str(uuid.uuid4())
144
+ return headers
145
+
146
+ def _url(self, path: str) -> str:
147
+ return self.base_url.rstrip("/") + path
148
+
149
+ def _wait(self, method: str, attempt: int, response: Optional[httpx.Response]) -> Optional[float]:
150
+ """Seconds to wait before retrying, or None when the call must not be retried."""
151
+ if attempt >= self.max_retries:
152
+ return None
153
+ if response is None:
154
+ retryable = method in _READS
155
+ elif response.status_code == 429:
156
+ retryable = True
157
+ else:
158
+ retryable = method in _READS and response.status_code in _TRANSIENT
159
+ if not retryable:
160
+ return None
161
+ hinted = _retry_after(response.headers.get("Retry-After")) if response is not None else None
162
+ return min(_MAX_RETRY_WAIT, hinted if hinted is not None else 0.5 * (2**attempt))
163
+
164
+ def request(
165
+ self,
166
+ method: str,
167
+ path: str,
168
+ *,
169
+ params: Optional[Mapping[str, Any]] = None,
170
+ body: Any = None,
171
+ ) -> Any:
172
+ """Call the API and return the decoded JSON. Raises CrosslyError on an error response."""
173
+ headers = self._headers(method, None)
174
+ attempt = 0
175
+ with httpx.Client(timeout=self.timeout) as client:
176
+ while True:
177
+ response: Optional[httpx.Response] = None
178
+ try:
179
+ response = client.request(
180
+ method, self._url(path), params=_clean(params), json=body, headers=headers
181
+ )
182
+ except httpx.HTTPError as exc:
183
+ wait = self._wait(method, attempt, None)
184
+ if wait is None:
185
+ raise CrosslyError(f"Could not reach the Crossly API: {exc}") from exc
186
+ else:
187
+ wait = self._wait(method, attempt, response) if response.status_code >= 429 else None
188
+ if wait is None:
189
+ return _result(response)
190
+ time.sleep(wait)
191
+ attempt += 1
192
+
193
+ async def arequest(
194
+ self,
195
+ method: str,
196
+ path: str,
197
+ *,
198
+ params: Optional[Mapping[str, Any]] = None,
199
+ body: Any = None,
200
+ ) -> Any:
201
+ """Async :meth:`request`."""
202
+ headers = self._headers(method, None)
203
+ attempt = 0
204
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
205
+ while True:
206
+ response: Optional[httpx.Response] = None
207
+ try:
208
+ response = await client.request(
209
+ method, self._url(path), params=_clean(params), json=body, headers=headers
210
+ )
211
+ except httpx.HTTPError as exc:
212
+ wait = self._wait(method, attempt, None)
213
+ if wait is None:
214
+ raise CrosslyError(f"Could not reach the Crossly API: {exc}") from exc
215
+ else:
216
+ wait = self._wait(method, attempt, response) if response.status_code >= 429 else None
217
+ if wait is None:
218
+ return _result(response)
219
+ await asyncio.sleep(wait)
220
+ attempt += 1
221
+
222
+
223
+ def to_json(value: Any) -> str:
224
+ """Compact JSON for a tool's string output."""
225
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"), default=str)