|
| 1 | +"""Per-call helpers shared by every tool: who is calling, in what units, |
| 2 | +and how to run synchronous SQLAlchemy work without blocking the event loop. |
| 3 | +
|
| 4 | +Tools are `async def` and do their database work through `run_sync`, which |
| 5 | +hands the callable to anyio's worker thread pool. anyio copies the current |
| 6 | +context into the thread, so both fastapi_sqlalchemy's request-scoped |
| 7 | +`db.session` and the SDK's `auth_context_var` are visible inside. |
| 8 | +""" |
| 9 | + |
| 10 | +import functools |
| 11 | +from dataclasses import dataclass |
| 12 | +from typing import Callable, TypeVar |
| 13 | + |
| 14 | +import anyio |
| 15 | +from fastapi_sqlalchemy import db |
| 16 | +from mcp.server.auth.middleware.auth_context import get_access_token |
| 17 | +from mcp.server.mcpserver.exceptions import ToolError as _SDKToolError |
| 18 | + |
| 19 | +from models.base import User |
| 20 | +from oauth import tokens as oauth_tokens |
| 21 | +from utils.weight import convert_weight |
| 22 | + |
| 23 | +T = TypeVar("T") |
| 24 | + |
| 25 | +GRAMS_PER_UNIT = {"g": 1.0, "kg": 1000.0, "oz": 28.3495, "lb": 453.592} |
| 26 | + |
| 27 | + |
| 28 | +class ToolError(_SDKToolError): |
| 29 | + """Raised inside a tool; the SDK turns it into an isError tool result the |
| 30 | + model can read and relay. Keep messages actionable for the end user. |
| 31 | +
|
| 32 | + Must subclass the SDK's ToolError: any other exception type is reported |
| 33 | + to the client as an opaque "Error executing tool" with the message |
| 34 | + withheld (so crashes never leak internals), which is exactly wrong for |
| 35 | + the "trip not found, call list_trips" class of message. |
| 36 | + """ |
| 37 | + |
| 38 | + |
| 39 | +async def run_sync(fn: Callable[..., T], *args, **kwargs) -> T: |
| 40 | + return await anyio.to_thread.run_sync(functools.partial(fn, *args, **kwargs)) |
| 41 | + |
| 42 | + |
| 43 | +@dataclass |
| 44 | +class Caller: |
| 45 | + user: User |
| 46 | + scopes: list[str] |
| 47 | + client_id: str |
| 48 | + |
| 49 | + @property |
| 50 | + def unit(self) -> str: |
| 51 | + """Display unit for per-item weights, from the user's preference.""" |
| 52 | + return "oz" if (self.user.unit_weight or "METRIC") == "IMPERIAL" else "g" |
| 53 | + |
| 54 | + @property |
| 55 | + def big_unit(self) -> str: |
| 56 | + """Display unit for totals.""" |
| 57 | + return "lb" if self.unit == "oz" else "kg" |
| 58 | + |
| 59 | + @property |
| 60 | + def can_write(self) -> bool: |
| 61 | + return oauth_tokens.SCOPE_WRITE in self.scopes |
| 62 | + |
| 63 | + |
| 64 | +def current_caller() -> Caller: |
| 65 | + """Resolve the authenticated user for this tool call. Sync — call via |
| 66 | + run_sync or from inside another sync function.""" |
| 67 | + token = get_access_token() |
| 68 | + if token is None or token.subject is None: |
| 69 | + raise ToolError("Not authenticated.") |
| 70 | + user = db.session.query(User).filter_by(id=int(token.subject)).first() |
| 71 | + if user is None or user.deactivated or user.banned: |
| 72 | + raise ToolError("This Packstack account is not available.") |
| 73 | + return Caller(user=user, scopes=list(token.scopes), client_id=token.client_id) |
| 74 | + |
| 75 | + |
| 76 | +# --------------------------------------------------------------------------- |
| 77 | +# Weight formatting. Every weight a tool returns carries grams (for arithmetic |
| 78 | +# the model can trust) and the user's display unit (for talking to the user). |
| 79 | +# --------------------------------------------------------------------------- |
| 80 | + |
| 81 | +def to_grams(weight, unit) -> float: |
| 82 | + if weight is None: |
| 83 | + return 0.0 |
| 84 | + return float(weight) * GRAMS_PER_UNIT.get(unit or "g", 1.0) |
| 85 | + |
| 86 | + |
| 87 | +def weight_fields(grams: float, caller: Caller, big: bool = False) -> dict: |
| 88 | + unit = caller.big_unit if big else caller.unit |
| 89 | + value = convert_weight(grams, "g", unit) |
| 90 | + return { |
| 91 | + "grams": round(grams, 1), |
| 92 | + "display": f"{value:,.2f} {unit}" if big else f"{value:,.1f} {unit}", |
| 93 | + } |
| 94 | + |
| 95 | + |
| 96 | +def item_summary(item, caller: Caller) -> dict: |
| 97 | + """The shape every tool uses for a gear item. Never includes internal |
| 98 | + foreign keys, sort orders or removed/deleted flags.""" |
| 99 | + brand = item.brand.name if item.brand else None |
| 100 | + product = item.product.name if item.product else None |
| 101 | + variant = item.product_variant.name if item.product_variant else None |
| 102 | + category = (item.category.category.name |
| 103 | + if item.category and item.category.category else None) |
| 104 | + grams = to_grams(item.weight, item.unit) |
| 105 | + return { |
| 106 | + "item_id": item.id, |
| 107 | + "name": item.name, |
| 108 | + "brand": brand, |
| 109 | + "product": " ".join(p for p in (product, variant) if p) or None, |
| 110 | + "category": category or "Uncategorized", |
| 111 | + "weight": weight_fields(grams, caller), |
| 112 | + "weight_entered": item.weight is not None, |
| 113 | + "consumable": bool(item.consumable), |
| 114 | + "calories": float(item.calories) if item.calories else None, |
| 115 | + "price": float(item.price) if item.price else None, |
| 116 | + "notes": item.notes or None, |
| 117 | + "product_url": item.product_url or None, |
| 118 | + "archived": bool(item.removed), |
| 119 | + "status": item.status or "active", |
| 120 | + } |
0 commit comments