silpo-agent-cli 0.2.0__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.
File without changes
@@ -0,0 +1,141 @@
1
+ """Address Resolver: resolves which delivery address/branch context product
2
+ search runs against, before any product search happens (see
3
+ prd_reorder_optimizer.md's Address Resolver section and CONTEXT.md's
4
+ "Delivery address resolution" entry).
5
+
6
+ Source is `silpo_get_my_delivery_addresses` (never order data). The first
7
+ address in the API's return order is always proposed for confirmation first,
8
+ every run, regardless of what a prior run's Reorder Log recorded -- MCP does
9
+ not mark any address as a server-side default (live-verified, see
10
+ ../../docs/mcp_schema.md's "Live-verified: address tools" section), so
11
+ "propose first" just means "first as the API returns them," documented here
12
+ as an assumption rather than a real default. On decline: pick from the
13
+ remaining saved addresses, or type a brand-new address (geocoded via
14
+ `silpo_find_address` -> `silpo_get_available_delivery_types`, looked up by
15
+ lat/lon). The confirmed choice is written to the Reorder Log for audit only
16
+ -- it never feeds back into what's proposed next run.
17
+
18
+ Real schemas (live-verified, see ../../docs/mcp_schema.md):
19
+ - `silpo_get_my_delivery_addresses` takes no args and returns
20
+ `{"success", "summary", "addresses": [...]}`; each entry has
21
+ `id`/`tag`/`city`/`street`/`building`/`apartment`/`floor`/`entrance`/
22
+ `latitude`/`longitude`/`comment`, no `"address"`/`"label"`/`"is_default"`.
23
+ - `silpo_find_address` takes `{"address": "<free text>"}` and returns
24
+ `{"success", "summary", "addresses": [...]}`; each entry has
25
+ `address`/`city`/`street`/`houseNumber`/`district`/`latitude`/`longitude`,
26
+ no `"id"` (it's a geocode result, not a saved-address record).
27
+ - `silpo_get_available_delivery_types` takes `{"latitude": ..., "longitude": ...}`,
28
+ sourced from whichever resolved address's coordinates (saved or geocoded).
29
+ """
30
+
31
+ from dataclasses import dataclass, replace
32
+ from datetime import datetime
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ResolvedAddress:
37
+ id: str | None
38
+ label: str
39
+ latitude: float | None
40
+ longitude: float | None
41
+ # Raw `silpo_get_available_delivery_types` response for this address's
42
+ # coordinates, if looked up below -- `None` when coordinates were missing
43
+ # so the lookup was skipped. Exposed so the Cart Context Resolver's
44
+ # no-shipments fallback (issue #29) can reuse this call's result instead
45
+ # of duplicating it.
46
+ delivery_types: dict | None = None
47
+
48
+
49
+ def _build_label(address: dict) -> str:
50
+ """Human-readable label from an address's city/street/building/apartment,
51
+ e.g. "Вінниця, Варшавська вулиця, 27, кв. 25". Saved addresses (from
52
+ address_resolver/silpo_find_address) key the building/apartment as
53
+ "building"/"apartment"; a cart's own address (silpo_get_shopping_cart_by_id,
54
+ docs/mcp_schema.md) keys the same info as "house"/"flat" instead -- both
55
+ are checked so neither source silently drops the house/apartment number."""
56
+ building = address.get("building") or address.get("house")
57
+ apartment = address.get("apartment") or address.get("flat")
58
+ parts = [address.get("city"), address.get("street"), building]
59
+ if apartment:
60
+ parts.append(f"кв. {apartment}")
61
+ return ", ".join(str(p) for p in parts if p)
62
+
63
+
64
+ def _to_resolved(address: dict) -> ResolvedAddress:
65
+ # silpo_find_address results already carry a pre-formatted "address" string;
66
+ # saved addresses don't, so build one from city/street/building/apartment.
67
+ label = address.get("address") or _build_label(address)
68
+ return ResolvedAddress(
69
+ id=address.get("id"),
70
+ label=label,
71
+ latitude=address.get("latitude"),
72
+ longitude=address.get("longitude"),
73
+ )
74
+
75
+
76
+ def _unwrap_addresses(response) -> list[dict]:
77
+ if isinstance(response, dict):
78
+ return response.get("addresses") or []
79
+ return response or []
80
+
81
+
82
+ def _pick_from_list_or_new(remaining: list[dict], client, input_fn, print_fn) -> ResolvedAddress | None:
83
+ for i, address in enumerate(remaining, start=1):
84
+ print_fn(f"{i}. {_to_resolved(address).label}")
85
+ choice = input_fn("Pick a number, or type a new address: ").strip()
86
+ if choice.isdigit():
87
+ idx = int(choice)
88
+ if 1 <= idx <= len(remaining):
89
+ return _to_resolved(remaining[idx - 1])
90
+ print_fn(f"No address numbered {idx}.")
91
+ return None
92
+ return _enter_new_address(client, choice, print_fn)
93
+
94
+
95
+ def _enter_new_address(client, query: str, print_fn) -> ResolvedAddress | None:
96
+ query = query.strip()
97
+ if not query:
98
+ print_fn("No address entered.")
99
+ return None
100
+ found = _unwrap_addresses(client.call("silpo_find_address", {"address": query}))
101
+ if not found:
102
+ print_fn(f"No address found for '{query}'.")
103
+ return None
104
+ return _to_resolved(found[0])
105
+
106
+
107
+ def resolve_address(client, log_store, *, input_fn=None, print_fn=None) -> ResolvedAddress | None:
108
+ input_fn = input_fn or input
109
+ print_fn = print_fn or print
110
+
111
+ addresses = _unwrap_addresses(client.call("silpo_get_my_delivery_addresses"))
112
+ if addresses:
113
+ first_resolved = _to_resolved(addresses[0])
114
+ answer = input_fn(f"Deliver to {first_resolved.label}? [Y/n] ").strip().lower()
115
+ if answer in ("", "y", "yes"):
116
+ resolved = first_resolved
117
+ else:
118
+ resolved = _pick_from_list_or_new(addresses[1:], client, input_fn, print_fn)
119
+ else:
120
+ print_fn("No saved delivery addresses found.")
121
+ query = input_fn("Enter a delivery address: ")
122
+ resolved = _enter_new_address(client, query, print_fn)
123
+
124
+ if resolved is not None:
125
+ # A resolved address without coordinates can't establish delivery-type
126
+ # context (a malformed saved-address entry, e.g.) -- skip rather than
127
+ # send nulls to the real API.
128
+ if resolved.latitude is not None and resolved.longitude is not None:
129
+ delivery_types = client.call(
130
+ "silpo_get_available_delivery_types",
131
+ {"latitude": resolved.latitude, "longitude": resolved.longitude},
132
+ )
133
+ resolved = replace(resolved, delivery_types=delivery_types)
134
+ log_store.append_run(
135
+ {
136
+ "timestamp": datetime.now().isoformat(timespec="seconds"),
137
+ "address": resolved.label,
138
+ "address_id": resolved.id,
139
+ }
140
+ )
141
+ return resolved
silpo_agent/auth.py ADDED
@@ -0,0 +1,266 @@
1
+ """MCP Client / Auth: OAuth2.1+PKCE browser login against the Silpo MCP
2
+ server, OS keyring token storage, refresh-on-expiry, and a single
3
+ `call(tool, args)` wrapper used by every other module for all silpo_* tool
4
+ calls.
5
+
6
+ Live schema note: the MCP server's tools/list response (order objects,
7
+ delivery-address objects) is not publicly documented and requires an
8
+ authenticated call. See ../../docs/mcp_schema.md for what has and hasn't
9
+ been verified against the live server.
10
+ """
11
+
12
+ import base64
13
+ import hashlib
14
+ import json
15
+ import secrets
16
+ import time
17
+ import urllib.error
18
+ import urllib.parse
19
+ import urllib.request
20
+ import webbrowser
21
+ from http.server import BaseHTTPRequestHandler, HTTPServer
22
+
23
+ import keyring
24
+
25
+ SERVER_URL = "https://mcp.silpo.ua/mcp"
26
+ AUTHORIZE_URL = "https://mcp.silpo.ua/authorize"
27
+ TOKEN_URL = "https://mcp.silpo.ua/token"
28
+ REGISTER_URL = "https://mcp.silpo.ua/register"
29
+ REDIRECT_PORT = 8765
30
+ # "localhost", not the 127.0.0.1 literal -- a real working Claude Code ->
31
+ # mcp.silpo.ua authorize request (HAR-captured 2026-08-04) used
32
+ # "localhost", ours used the raw IP; that request never hit the Cloudflare
33
+ # block this one did, so this may be a distinguishing factor worth testing.
34
+ REDIRECT_URI = f"http://localhost:{REDIRECT_PORT}/callback"
35
+
36
+ KEYRING_SERVICE = "silpo-agent"
37
+ KEYRING_USERNAME = "mcp-token"
38
+
39
+
40
+ class MCPError(Exception):
41
+ pass
42
+
43
+
44
+ class AuthError(Exception):
45
+ pass
46
+
47
+
48
+ class TokenStore:
49
+ """Wraps the OS keyring (via the `keyring` package) as JSON-serialized
50
+ token storage. This is the mockable system boundary for auth persistence.
51
+ """
52
+
53
+ def __init__(self, service: str = KEYRING_SERVICE, username: str = KEYRING_USERNAME):
54
+ self.service = service
55
+ self.username = username
56
+
57
+ def load(self) -> dict | None:
58
+ raw = keyring.get_password(self.service, self.username)
59
+ if not raw:
60
+ return None
61
+ try:
62
+ return json.loads(raw)
63
+ except json.JSONDecodeError:
64
+ return None
65
+
66
+ def save(self, token: dict) -> None:
67
+ keyring.set_password(self.service, self.username, json.dumps(token))
68
+
69
+ def clear(self) -> None:
70
+ try:
71
+ keyring.delete_password(self.service, self.username)
72
+ except keyring.errors.PasswordDeleteError:
73
+ pass
74
+
75
+
76
+ def _post_json(url: str, payload: dict, headers: dict | None = None) -> dict:
77
+ body = json.dumps(payload).encode()
78
+ req = urllib.request.Request(
79
+ url,
80
+ data=body,
81
+ method="POST",
82
+ headers={"Content-Type": "application/json", **(headers or {})},
83
+ )
84
+ try:
85
+ with urllib.request.urlopen(req, timeout=15) as resp:
86
+ return json.loads(resp.read())
87
+ except urllib.error.HTTPError as exc:
88
+ raise AuthError(f"{url} returned {exc.code}: {exc.read().decode(errors='replace')}") from exc
89
+
90
+
91
+ def _post_form(url: str, fields: dict) -> dict:
92
+ body = urllib.parse.urlencode(fields).encode()
93
+ req = urllib.request.Request(
94
+ url, data=body, method="POST", headers={"Content-Type": "application/x-www-form-urlencoded"}
95
+ )
96
+ try:
97
+ with urllib.request.urlopen(req, timeout=15) as resp:
98
+ return json.loads(resp.read())
99
+ except urllib.error.HTTPError as exc:
100
+ raise AuthError(f"{url} returned {exc.code}: {exc.read().decode(errors='replace')}") from exc
101
+
102
+
103
+ def _token_from_response(resp: dict) -> dict:
104
+ if "access_token" not in resp:
105
+ raise AuthError(f"token endpoint response missing access_token: {resp}")
106
+ return {
107
+ "access_token": resp["access_token"],
108
+ "refresh_token": resp.get("refresh_token"),
109
+ "expires_at": time.time() + float(resp.get("expires_in", 3600)),
110
+ }
111
+
112
+
113
+ def _register_client() -> str:
114
+ resp = _post_json(
115
+ REGISTER_URL,
116
+ {
117
+ "redirect_uris": [REDIRECT_URI],
118
+ "token_endpoint_auth_method": "none",
119
+ "grant_types": ["authorization_code", "refresh_token"],
120
+ "response_types": ["code"],
121
+ "client_name": "silpo-agent-cli",
122
+ },
123
+ )
124
+ if "client_id" not in resp:
125
+ raise AuthError(f"dynamic client registration response missing client_id: {resp}")
126
+ return resp["client_id"]
127
+
128
+
129
+ class _CallbackHandler(BaseHTTPRequestHandler):
130
+ def do_GET(self):
131
+ params = urllib.parse.parse_qs(urllib.parse.urlparse(self.path).query)
132
+ self.server.auth_code = params.get("code", [None])[0]
133
+ self.server.auth_error = params.get("error", [None])[0]
134
+ self.server.auth_state = params.get("state", [None])[0]
135
+ self.send_response(200)
136
+ self.send_header("Content-Type", "text/plain")
137
+ self.end_headers()
138
+ self.wfile.write(b"Login complete, you can close this tab.")
139
+
140
+ def log_message(self, *args):
141
+ pass
142
+
143
+
144
+ def _wait_for_redirect(expected_state: str) -> str:
145
+ httpd = HTTPServer(("127.0.0.1", REDIRECT_PORT), _CallbackHandler)
146
+ httpd.auth_code = None
147
+ httpd.auth_error = None
148
+ httpd.auth_state = None
149
+ httpd.handle_request()
150
+ if httpd.auth_error or not httpd.auth_code:
151
+ raise AuthError(f"OAuth authorize redirect returned an error: {httpd.auth_error}")
152
+ if httpd.auth_state != expected_state:
153
+ raise AuthError("OAuth authorize redirect returned a mismatched state (possible CSRF)")
154
+ return httpd.auth_code
155
+
156
+
157
+ def pkce_browser_login() -> dict:
158
+ """Full OAuth2.1+PKCE flow: dynamic client registration, browser
159
+ authorize, local redirect capture, code-for-token exchange.
160
+
161
+ Includes `resource` (RFC 8707) and `state` on the authorize request --
162
+ a live comparison against a real, working Claude Code -> mcp.silpo.ua
163
+ OAuth request (2026-08-04) showed both present; this implementation was
164
+ missing them, which may be why mcp.silpo.ua/authorize hard-blocked this
165
+ flow with a Cloudflare 403 (see mcp_auth_cloudflare_block memory note).
166
+ """
167
+ client_id = _register_client()
168
+ verifier = secrets.token_urlsafe(64)
169
+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).rstrip(b"=").decode()
170
+ state = secrets.token_urlsafe(32)
171
+
172
+ authorize_url = AUTHORIZE_URL + "?" + urllib.parse.urlencode(
173
+ {
174
+ "response_type": "code",
175
+ "client_id": client_id,
176
+ "redirect_uri": REDIRECT_URI,
177
+ "code_challenge": challenge,
178
+ "code_challenge_method": "S256",
179
+ "state": state,
180
+ "resource": SERVER_URL,
181
+ }
182
+ )
183
+ webbrowser.open(authorize_url)
184
+ code = _wait_for_redirect(state)
185
+
186
+ resp = _post_form(
187
+ TOKEN_URL,
188
+ {
189
+ "grant_type": "authorization_code",
190
+ "code": code,
191
+ "redirect_uri": REDIRECT_URI,
192
+ "client_id": client_id,
193
+ "code_verifier": verifier,
194
+ },
195
+ )
196
+ return _token_from_response(resp)
197
+
198
+
199
+ def refresh_token_http(refresh_token: str) -> dict:
200
+ resp = _post_form(TOKEN_URL, {"grant_type": "refresh_token", "refresh_token": refresh_token})
201
+ return _token_from_response(resp)
202
+
203
+
204
+ def call_tool_http(server_url: str, tool: str, args: dict, access_token: str) -> dict:
205
+ payload = {"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": tool, "arguments": args}}
206
+ resp = _post_json(server_url, payload, headers={"Authorization": f"Bearer {access_token}"})
207
+ if "error" in resp:
208
+ raise MCPError(resp["error"])
209
+ result = resp.get("result", resp)
210
+ return _unwrap_tool_result(tool, result)
211
+
212
+
213
+ def _unwrap_tool_result(tool: str, result: dict) -> dict:
214
+ """MCP tools/call responses wrap a tool's actual JSON output as a string
215
+ inside result["content"][0]["text"] -- this parses that envelope so
216
+ every other module can keep working with plain dicts. Non-tool-call
217
+ results (e.g. tools/list) have no "content" list and pass through as-is.
218
+ """
219
+ content = result.get("content") if isinstance(result, dict) else None
220
+ if not content:
221
+ return result
222
+ if result.get("isError"):
223
+ raise MCPError(f"{tool} returned an error: {content}")
224
+ text = content[0].get("text") if content and isinstance(content[0], dict) else None
225
+ if text is None:
226
+ return result
227
+ try:
228
+ return json.loads(text)
229
+ except json.JSONDecodeError:
230
+ return result
231
+
232
+
233
+ class MCPClient:
234
+ """Single entrypoint for all silpo_* tool calls: `client.call(tool, args)`.
235
+ Handles token load/refresh/first-login transparently.
236
+ """
237
+
238
+ def __init__(
239
+ self,
240
+ server_url: str = SERVER_URL,
241
+ token_store: TokenStore | None = None,
242
+ call_tool_http=call_tool_http,
243
+ login=pkce_browser_login,
244
+ refresh=refresh_token_http,
245
+ now=time.time,
246
+ ):
247
+ self.server_url = server_url
248
+ self.token_store = token_store or TokenStore()
249
+ self.call_tool_http = call_tool_http
250
+ self.login = login
251
+ self.refresh = refresh
252
+ self.now = now
253
+
254
+ def call(self, tool: str, args: dict | None = None) -> dict:
255
+ access_token = self._ensure_token()
256
+ return self.call_tool_http(self.server_url, tool, args or {}, access_token)
257
+
258
+ def _ensure_token(self) -> str:
259
+ token = self.token_store.load()
260
+ if token is None:
261
+ token = self.login()
262
+ self.token_store.save(token)
263
+ elif token["expires_at"] <= self.now():
264
+ token = self.refresh(token["refresh_token"])
265
+ self.token_store.save(token)
266
+ return token["access_token"]
@@ -0,0 +1,197 @@
1
+ """Cart Context Resolver: resolves the real cart/delivery context
2
+ (`shoppingCartId`, `branchId`, `companyId`, `deliveryType`, `timeslot`) that
3
+ almost every product-facing MCP tool requires (`silpo_get_replacements`,
4
+ `silpo_get_products`, `silpo_find_products_batch`, `silpo_get_product_details`,
5
+ `silpo_get_similar_products`, `silpo_add_or_update_cart_products`).
6
+
7
+ Real schema (see ../../docs/mcp_schema.md's "Cart tools" section, live-verified):
8
+ - `silpo_get_my_shopping_cart` takes no args and returns ONLY
9
+ `{"success", "shoppingCartId"}` -- no cart contents.
10
+ - `silpo_get_shopping_cart_by_id({"shoppingCartId"})` returns the actual
11
+ cart: `cart.shipments[0].branchId`/`.companyId`, `cart.deliveryType`,
12
+ `cart.timeslot.start`/`.end`, `cart.calculation.validations[]`.
13
+
14
+ `cart.calculation.validations[]` reports real problems (out-of-stock items,
15
+ stale timeslots) -- surfaced to the user here via `print_fn`, never silently
16
+ dropped, but never blocks the run (deeper handling is out of scope for this
17
+ ticket per issue #17).
18
+
19
+ `CartContext.products` carries `cart.shipments[0].products` (each with
20
+ `productId`/`companyId`/`branchId`/`quantity`/... per the schema above) so
21
+ the Cart Writer's non-empty-cart guard (#19) can read real cart contents
22
+ without a second `silpo_get_shopping_cart_by_id` call.
23
+
24
+ Nothing else downstream consumes this module's output yet -- that wiring
25
+ lands in the Substitution Resolver fix (#18) and Promo Optimizer redesign
26
+ (#20).
27
+
28
+ Issue #29 -- no-shipments address fallback: a fresh account or a cleared
29
+ cart has `cart.shipments == []`, so `branchId`/`companyId`/`deliveryType`
30
+ would otherwise resolve to `None`, breaking every downstream MCP call that
31
+ needs real branch/delivery context (Substitution Resolver already skips its
32
+ own calls entirely in that case -- see substitution_resolver.py's
33
+ no-cart-context guard). When shipments are empty, this resolver now runs
34
+ the Address Resolver (`address_resolver.resolve_address`) to get a
35
+ confirmed address, then reads `ResolvedAddress.delivery_types` -- the raw
36
+ `silpo_get_available_delivery_types` response `resolve_address` already
37
+ fetches for that address's coordinates -- to fill in real `branchId`/
38
+ `deliveryType` (`companyId` is never available from this response -- see
39
+ `_branch_context_from_delivery_types`). `silpo_get_available_delivery_types`'s
40
+ real response shape (`{"options": [{"deliveryType", "branchId",
41
+ "description"}]}`) was live-verified in issue #37, after this ticket first
42
+ shipped with a guessed, wrong key name (`"deliveryTypes"`) -- fixed here.
43
+
44
+ Callers that already resolved an address themselves (`reorder`'s pipeline,
45
+ via `cli.py`) must pass it as `resolved_address=` so this fallback reuses it
46
+ instead of prompting the user a second time. Callers with no address of
47
+ their own (future `cart`/`deals`/etc. commands) can omit it -- the fallback
48
+ then runs `resolve_address`'s own interactive confirm/pick/new-address flow,
49
+ using `log_store`/`input_fn`/`print_fn` passed through for that purpose.
50
+
51
+ Issue #27 -- `CartContext.total_after_discounts` mirrors
52
+ `cart.calculation.totalAfterDiscounts`, the amount the user actually pays
53
+ (per docs/mcp_schema.md's "Cart tools" section: `total` is pre-discount).
54
+ CartContext previously exposed no total at all; the Cart Viewer (issue #27)
55
+ needs this for its payable-total line.
56
+ """
57
+
58
+ from dataclasses import dataclass, field
59
+
60
+ from silpo_agent.address_resolver import resolve_address
61
+ from silpo_agent.log_store import ReorderLogStore
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class CartContext:
66
+ shopping_cart_id: str | None
67
+ branch_id: str | None
68
+ company_id: str | None
69
+ delivery_type: str | None
70
+ timeslot_start: str | None
71
+ timeslot_end: str | None
72
+ validations: list[dict] = field(default_factory=list)
73
+ products: list[dict] = field(default_factory=list)
74
+ # Raw fields below exist only so promo_optimizer.py (#20) can call
75
+ # silpo_update_shopping_cart, whose own tool description requires
76
+ # shipments/address/timeslot/deliveryType to be copied verbatim from
77
+ # silpo_get_shopping_cart_by_id's response, not reconstructed.
78
+ # bonus_available mirrors the response's top-level "loyalty.bonusAvailable"
79
+ # (same value the cart's "loyalty" node reports, per docs/mcp_schema.md).
80
+ bonus_available: float | None = None
81
+ timeslot: dict | None = None
82
+ address: dict | None = None
83
+ shipments: list[dict] = field(default_factory=list)
84
+ # Payable total (issue #27): cart.calculation.totalAfterDiscounts, the
85
+ # amount actually charged -- never the pre-discount "total".
86
+ total_after_discounts: float | None = None
87
+
88
+
89
+ def confirm_no_blocking_validations(cart_context: CartContext, *, input_fn=None, print_fn=None) -> bool:
90
+ """Real gate for mutating commands (reorder/smart-cart/cart edit), not
91
+ read-only ones: `resolve_cart_context` already surfaces every validation
92
+ via `print_fn` regardless, but never blocks (see its own docstring).
93
+ An error-level validation (e.g. `timeslot.not_found`) means the
94
+ delivery context a mutation is about to search/add against is stale or
95
+ broken -- ask before proceeding, same warn-and-proceed-or-abort pattern
96
+ as the Cart Writer's non-empty-cart guard. Warning/info-level
97
+ validations don't gate; only `level == "error"` does."""
98
+ input_fn = input_fn or input
99
+ print_fn = print_fn or print
100
+
101
+ errors = [v for v in cart_context.validations if v.get("level") == "error"]
102
+ if not errors:
103
+ return True
104
+
105
+ print_fn(f"Warning: {len(errors)} cart validation error(s) found (see above) -- delivery context may be stale.")
106
+ answer = input_fn("Continue anyway? [y/N] ").strip().lower()
107
+ return answer in ("y", "yes")
108
+
109
+
110
+ def _empty_context(shopping_cart_id: str | None = None) -> CartContext:
111
+ return CartContext(
112
+ shopping_cart_id=shopping_cart_id,
113
+ branch_id=None,
114
+ company_id=None,
115
+ delivery_type=None,
116
+ timeslot_start=None,
117
+ timeslot_end=None,
118
+ validations=[],
119
+ products=[],
120
+ )
121
+
122
+
123
+ def _branch_context_from_delivery_types(response: dict | None) -> tuple[str | None, str | None, str | None]:
124
+ """(branch_id, company_id, delivery_type) extraction from a
125
+ `silpo_get_available_delivery_types` response. Real, live-verified shape
126
+ (docs/mcp_schema.md, issue #37): `{"options": [{"deliveryType",
127
+ "branchId", "description"}]}` -- no `companyId` anywhere in this
128
+ response, so company_id is always None from this path. Prefers a
129
+ `DeliveryHome` option, falling back to the first option."""
130
+ if not isinstance(response, dict):
131
+ return None, None, None
132
+
133
+ options = response.get("options")
134
+ if not isinstance(options, list) or not options:
135
+ return None, None, None
136
+
137
+ chosen = next((o for o in options if isinstance(o, dict) and o.get("deliveryType") == "DeliveryHome"), options[0])
138
+ if not isinstance(chosen, dict):
139
+ return None, None, None
140
+
141
+ return chosen.get("branchId"), None, chosen.get("deliveryType")
142
+
143
+
144
+ def resolve_cart_context(
145
+ client, *, print_fn=None, input_fn=None, log_store=None, resolved_address=None
146
+ ) -> CartContext:
147
+ print_fn = print_fn or print
148
+
149
+ my_cart = client.call("silpo_get_my_shopping_cart") or {}
150
+ shopping_cart_id = my_cart.get("shoppingCartId")
151
+ if not shopping_cart_id:
152
+ return _empty_context()
153
+
154
+ response = client.call("silpo_get_shopping_cart_by_id", {"shoppingCartId": shopping_cart_id}) or {}
155
+ cart = response.get("cart") or {}
156
+ loyalty = response.get("loyalty") or {}
157
+
158
+ shipments = cart.get("shipments") or []
159
+ shipment = shipments[0] if shipments else {}
160
+ timeslot = cart.get("timeslot") or {}
161
+ calculation = cart.get("calculation") or {}
162
+ validations = calculation.get("validations") or []
163
+
164
+ for validation in validations:
165
+ print_fn(f"Cart validation [{validation.get('level')}]: {validation.get('message')}")
166
+
167
+ branch_id = shipment.get("branchId")
168
+ company_id = shipment.get("companyId")
169
+ delivery_type = cart.get("deliveryType")
170
+
171
+ if not shipments:
172
+ # Fresh account / cleared cart: no delivery context established yet.
173
+ # Fall back to the Address Resolver + silpo_get_available_delivery_types
174
+ # (reused off ResolvedAddress.delivery_types) for real branch/delivery
175
+ # context (issue #29). Reuse the caller's already-resolved address
176
+ # (reorder's pipeline) instead of prompting the user a second time.
177
+ address = resolved_address
178
+ if address is None:
179
+ address = resolve_address(client, log_store or ReorderLogStore(), input_fn=input_fn, print_fn=print_fn)
180
+ if address is not None:
181
+ branch_id, company_id, delivery_type = _branch_context_from_delivery_types(address.delivery_types)
182
+
183
+ return CartContext(
184
+ shopping_cart_id=shopping_cart_id,
185
+ branch_id=branch_id,
186
+ company_id=company_id,
187
+ delivery_type=delivery_type,
188
+ timeslot_start=timeslot.get("start"),
189
+ timeslot_end=timeslot.get("end"),
190
+ validations=validations,
191
+ products=shipment.get("products") or [],
192
+ bonus_available=loyalty.get("bonusAvailable"),
193
+ timeslot=cart.get("timeslot"),
194
+ address=cart.get("address"),
195
+ shipments=shipments,
196
+ total_after_discounts=calculation.get("totalAfterDiscounts"),
197
+ )