solvapay 0.1.0.dev4__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.
@@ -0,0 +1,220 @@
1
+ """What a paid MCP tool's handler receives and returns.
2
+
3
+ A handler gets a ``ResponseContext`` and returns ``ctx.respond(data, ...)``.
4
+ The SDK turns that into the MCP tool result, the same shape the TypeScript
5
+ SDK's ``buildPayableHandler`` produces.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ from collections.abc import Awaitable, Callable
12
+ from dataclasses import dataclass, field
13
+ from typing import Any, Literal
14
+
15
+ from mcp.types import CallToolResult, EmbeddedResource, TextContent, TextResourceContents
16
+
17
+ from .._js import UNDEFINED, get
18
+ from ..paywall import PaywallStateKind, build_nudge_message, credit_signals
19
+ from ..paywall.decide import FreeLimit, PaywallError
20
+
21
+ Json = dict[str, Any]
22
+ NudgeKind = Literal["low-balance", "cycle-ending", "approaching-limit"]
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Nudge:
27
+ """A soft prompt appended to a successful result, such as a low balance."""
28
+
29
+ kind: NudgeKind
30
+ message: str = ""
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class CustomerSnapshot:
35
+ """The customer as the limits check before this call saw them (up to 10 s old)."""
36
+
37
+ ref: str
38
+ balance: float | None
39
+ is_credit_based: bool
40
+ remaining: float | None
41
+ within_limits: bool
42
+ overage: bool
43
+ plan: Json | None
44
+ _refresh: Callable[[], Awaitable[CustomerSnapshot]] = field(repr=False)
45
+
46
+ async def fresh(self) -> CustomerSnapshot:
47
+ """Asks the API again, bypassing the cache."""
48
+ return await self._refresh()
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class ResponseResult:
53
+ """What ``ctx.respond`` returns. Return it from the handler as is."""
54
+
55
+ data: Any
56
+ text: str | None
57
+ nudge: Nudge | None
58
+ data_in_text: bool
59
+ emitted: list[Json]
60
+ limits: Json | None
61
+
62
+
63
+ def _snapshot(
64
+ customer_ref: str,
65
+ limits: Json | None,
66
+ plan: Json | None,
67
+ refresh: Callable[[], Awaitable[CustomerSnapshot]],
68
+ ) -> CustomerSnapshot:
69
+ signals = credit_signals(limits)
70
+ balance = signals.get("creditBalance", UNDEFINED)
71
+ remaining = get(limits, "remaining")
72
+ return CustomerSnapshot(
73
+ ref=customer_ref,
74
+ balance=None if balance is UNDEFINED else balance,
75
+ is_credit_based=bool(signals["isCreditBased"]),
76
+ remaining=None if remaining is UNDEFINED else remaining,
77
+ within_limits=bool(get(limits, "withinLimits")) if limits else True,
78
+ overage=get(limits, "overage") is True,
79
+ plan=plan,
80
+ _refresh=refresh,
81
+ )
82
+
83
+
84
+ class ResponseContext:
85
+ """The paid tool's view of the customer and its way to answer."""
86
+
87
+ def __init__(
88
+ self,
89
+ *,
90
+ customer_ref: str,
91
+ limits: Json | None,
92
+ product: str,
93
+ check_limits: Callable[[Json], Awaitable[Json]],
94
+ free_limit: FreeLimit | None = None,
95
+ ) -> None:
96
+ self._limits = limits
97
+ self._emitted: list[Json] = []
98
+ self.product: Json = {"reference": product, "name": product}
99
+ plan_ref = get(limits, "planRef")
100
+ plan = {"reference": plan_ref} if isinstance(plan_ref, str) and plan_ref else None
101
+
102
+ async def refresh() -> CustomerSnapshot:
103
+ body: Json = {
104
+ "customerRef": customer_ref,
105
+ "productRef": product,
106
+ "meterName": free_limit.meter if free_limit else "requests",
107
+ }
108
+ if free_limit:
109
+ body["freeAllowance"] = free_limit.wire()
110
+ return _snapshot(customer_ref, await check_limits(body), plan, refresh)
111
+
112
+ self.customer = _snapshot(customer_ref, limits, plan, refresh)
113
+
114
+ def respond(
115
+ self,
116
+ data: Any,
117
+ *,
118
+ text: str | None = None,
119
+ nudge: Nudge | None = None,
120
+ data_in_text: bool = True,
121
+ ) -> ResponseResult:
122
+ """The tool's answer. ``text`` replaces the JSON in the first content block;
123
+ ``nudge`` appends a soft prompt (default copy when its message is empty)."""
124
+ return ResponseResult(
125
+ data=data,
126
+ text=text,
127
+ nudge=nudge,
128
+ data_in_text=data_in_text,
129
+ emitted=list(self._emitted),
130
+ limits=self._limits,
131
+ )
132
+
133
+ def gate(self, reason: str | None = None) -> None:
134
+ """Stops the call and shows a paywall instead."""
135
+ message = reason or "Payment required"
136
+ raise PaywallError(
137
+ {
138
+ "kind": "payment_required",
139
+ "product": self.product["reference"],
140
+ "checkoutUrl": "",
141
+ "message": message,
142
+ }
143
+ )
144
+
145
+ async def emit(self, block: Json) -> None:
146
+ """Queues a content block (text, image or resource) ahead of the answer."""
147
+ self._emitted.append(block)
148
+
149
+
150
+ def gate_result(gate: Json) -> CallToolResult:
151
+ """A paywall as a tool result: not an error, the message as text, the gate as data."""
152
+ return CallToolResult(
153
+ content=[TextContent(type="text", text=str(gate["message"]))],
154
+ structured_content=gate,
155
+ is_error=False,
156
+ )
157
+
158
+
159
+ def tool_error_result(error: str, status: int, details: str | None = None) -> CallToolResult:
160
+ """``toolErrorResult``: the recovery text first, the ``{error, status, details}`` envelope
161
+ as structured content."""
162
+ envelope: Json = {"error": error, "status": status}
163
+ if details is not None:
164
+ envelope["details"] = details
165
+ return CallToolResult(
166
+ content=[TextContent(type="text", text=details if details is not None else error)],
167
+ structured_content=envelope,
168
+ is_error=True,
169
+ )
170
+
171
+
172
+ def error_result(message: str) -> CallToolResult:
173
+ return CallToolResult(
174
+ content=[
175
+ TextContent(
176
+ type="text", text=json.dumps({"success": False, "error": message}, indent=2)
177
+ )
178
+ ],
179
+ is_error=True,
180
+ )
181
+
182
+
183
+ def _json(data: Any) -> str:
184
+ return json.dumps(data, separators=(",", ":"), ensure_ascii=False)
185
+
186
+
187
+ def unwrap(result: ResponseResult) -> CallToolResult:
188
+ """The tool result for a ``ResponseResult``, as the TypeScript SDK builds it."""
189
+ if not isinstance(result, ResponseResult):
190
+ raise TypeError(
191
+ "A paid tool's handler must return ctx.respond(data, ...), "
192
+ f"not {type(result).__name__}."
193
+ )
194
+ base_text = result.text if isinstance(result.text, str) else _json(result.data)
195
+ primary = base_text
196
+ nudge_text: str | None = None
197
+ if result.nudge is not None:
198
+ credit_based = bool(credit_signals(result.limits)["isCreditBased"])
199
+ fallback: PaywallStateKind = (
200
+ "topup_required"
201
+ if result.nudge.kind == "low-balance" and credit_based
202
+ else "upgrade_required"
203
+ )
204
+ nudge_text = result.nudge.message or build_nudge_message(fallback, result.limits)
205
+ primary = f"{base_text}\n\n{nudge_text}" if base_text else nudge_text
206
+
207
+ content: list[Any] = [*result.emitted, TextContent(type="text", text=primary)]
208
+ if (isinstance(result.text, str) or nudge_text is not None) and result.data_in_text:
209
+ content.append(TextContent(type="text", text=_json(result.data)))
210
+ if nudge_text is not None:
211
+ content.append(
212
+ EmbeddedResource(
213
+ type="resource",
214
+ resource=TextResourceContents(
215
+ uri="solvapay://nudge", mime_type="text/plain", text=nudge_text
216
+ ),
217
+ )
218
+ )
219
+ structured = result.data if isinstance(result.data, dict) else None
220
+ return CallToolResult(content=content, structured_content=structured, is_error=False)
solvapay/mcp/server.py ADDED
@@ -0,0 +1,343 @@
1
+ """``create_solvapay_mcp_server``: an MCP server with SolvaPay sign-in and paid tools.
2
+
3
+ ```python
4
+ from solvapay import create_solvapay
5
+ from solvapay.mcp import ResponseContext, create_solvapay_mcp_server
6
+
7
+ mcp = create_solvapay_mcp_server(
8
+ solvapay=create_solvapay(),
9
+ product_ref="prd_…",
10
+ public_base_url="https://research.example.com",
11
+ )
12
+
13
+ async def quote(symbol: str, ctx: ResponseContext):
14
+ return ctx.respond({"symbol": symbol, "price": 101.5})
15
+
16
+ mcp.register_payable("quote", handler=quote, description="Latest price for a symbol.")
17
+
18
+ app = mcp.http_app() # serve with uvicorn: the MCP endpoint is /mcp
19
+ ```
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence
26
+ from typing import Any
27
+ from urllib.parse import urlsplit
28
+
29
+ import httpx
30
+ from mcp.server.lowlevel.helper_types import ReadResourceContents
31
+ from mcp.server.mcpserver import Context, MCPServer
32
+ from mcp.server.transport_security import TransportSecuritySettings
33
+ from mcp.types import InputRequiredResult, ToolAnnotations
34
+ from pydantic import AnyUrl
35
+ from starlette.applications import Starlette
36
+ from starlette.requests import Request
37
+ from starlette.responses import Response
38
+
39
+ from ..errors import SolvaPayError
40
+ from ..paywall.decide import FreeLimit
41
+ from ..solvapay import SolvaPay
42
+ from .app import (
43
+ BOOTSTRAP_MIME_TYPE,
44
+ BOOTSTRAP_URI,
45
+ BypassWhen,
46
+ HideToolsByAudience,
47
+ app_resource,
48
+ default_resource_uri,
49
+ merge_csp,
50
+ widget_html,
51
+ )
52
+ from .auth import SignInMiddleware, SolvaPayTokenVerifier, not_found, oauth_bridge_routes
53
+ from .bootstrap import ADVERTISED_VIEWS, ViewKind, build_bootstrap_payload, derive_default_view
54
+ from .intent import _resolve_customer, register_intent_tools
55
+ from .tools import (
56
+ GetCustomerRef,
57
+ Handler,
58
+ default_customer_ref,
59
+ register_free_tool,
60
+ register_payable_tool,
61
+ )
62
+ from .transport import register_transport_tools
63
+
64
+ Json = dict[str, Any]
65
+
66
+ BootstrapReader = Callable[[Context[Any, Any]], Awaitable[str]]
67
+
68
+
69
+ class _AppServer(MCPServer[Any]):
70
+ """An ``MCPServer`` that reads ``solvapay://bootstrap.json`` for the caller.
71
+
72
+ The snapshot depends on who asks, and ``MCPServer`` hands a static resource no
73
+ request context, so the read is answered here, where the context is known.
74
+ """
75
+
76
+ bootstrap_reader: BootstrapReader | None = None
77
+
78
+ async def read_resource(
79
+ self, uri: AnyUrl | str, context: Context[Any, Any] | None = None
80
+ ) -> Iterable[ReadResourceContents] | InputRequiredResult:
81
+ if self.bootstrap_reader is not None and str(uri) == BOOTSTRAP_URI:
82
+ text = await self.bootstrap_reader(context or Context(mcp_server=self))
83
+ return [ReadResourceContents(content=text, mime_type=BOOTSTRAP_MIME_TYPE)]
84
+ return await super().read_resource(uri, context)
85
+
86
+
87
+ async def _not_found(_request: Request, _error: Exception) -> Response:
88
+ return not_found()
89
+
90
+
91
+ class SolvaPayMcpServer:
92
+ """An ``MCPServer`` (``.server``) plus helpers bound to its SolvaPay product."""
93
+
94
+ def __init__(
95
+ self,
96
+ *,
97
+ server: MCPServer,
98
+ solvapay: SolvaPay,
99
+ product_ref: str,
100
+ mcp_path: str,
101
+ public_base_url: str,
102
+ resource_uri: str,
103
+ token_verifier: SolvaPayTokenVerifier,
104
+ ) -> None:
105
+ self.server = server
106
+ self.token_verifier = token_verifier
107
+ self.solvapay = solvapay
108
+ self.product_ref = product_ref
109
+ self.mcp_path = mcp_path
110
+ self.public_base_url = public_base_url
111
+ self.resource_uri = resource_uri
112
+ self._free_meters: dict[str, tuple[FreeLimit, list[str]]] = {}
113
+
114
+ def register_payable(
115
+ self,
116
+ name: str,
117
+ *,
118
+ handler: Handler,
119
+ description: str | None = None,
120
+ title: str | None = None,
121
+ annotations: ToolAnnotations | None = None,
122
+ meta: Json | None = None,
123
+ product: str | None = None,
124
+ get_customer_ref: GetCustomerRef | None = None,
125
+ ) -> None:
126
+ """A paid tool on this server's product (or ``product``)."""
127
+ register_payable_tool(
128
+ self.server,
129
+ name,
130
+ solvapay=self.solvapay,
131
+ handler=handler,
132
+ product=product or self.product_ref,
133
+ description=description,
134
+ title=title,
135
+ annotations=annotations,
136
+ meta=meta,
137
+ get_customer_ref=get_customer_ref,
138
+ )
139
+
140
+ def register_free(
141
+ self,
142
+ name: str,
143
+ *,
144
+ handler: Handler,
145
+ limit: FreeLimit,
146
+ description: str | None = None,
147
+ title: str | None = None,
148
+ annotations: ToolAnnotations | None = None,
149
+ meta: Json | None = None,
150
+ product: str | None = None,
151
+ get_customer_ref: GetCustomerRef | None = None,
152
+ ) -> None:
153
+ """A free tool. Tools that name the same meter must declare the same limit."""
154
+ existing = self._free_meters.get(limit.meter)
155
+ if existing and existing[0] != limit:
156
+ raise SolvaPayError(
157
+ f"Free tools '{', '.join(existing[1])}' and '{name}' declare meter "
158
+ f"'{limit.meter}' with different caps",
159
+ code="invalid_free_limit",
160
+ )
161
+ shared_with = list(existing[1]) if existing else []
162
+ if existing:
163
+ existing[1].append(name)
164
+ else:
165
+ self._free_meters[limit.meter] = (limit, [name])
166
+ register_free_tool(
167
+ self.server,
168
+ name,
169
+ solvapay=self.solvapay,
170
+ handler=handler,
171
+ limit=limit,
172
+ product=product or self.product_ref,
173
+ description=description,
174
+ title=title,
175
+ annotations=annotations,
176
+ meta=meta,
177
+ get_customer_ref=get_customer_ref,
178
+ shared_with=shared_with,
179
+ )
180
+
181
+ def http_app(self, **options: Any) -> Starlette:
182
+ """The ASGI app: the MCP endpoint at ``mcp_path`` plus the sign-in routes.
183
+
184
+ The MCP endpoint answers only a customer whose bearer token SolvaPay
185
+ verifies (``SignInMiddleware``); any other request gets a 401 that points at
186
+ ``/.well-known/oauth-protected-resource``. A path nothing serves is a 404
187
+ ``not_found``.
188
+
189
+ DNS-rebinding protection stays on, allowing this server's public host
190
+ (from ``public_base_url``) and localhost. Without the public host, the
191
+ MCP SDK answers every request through the public URL (a tunnel, a
192
+ load balancer) with 421. Pass ``transport_security`` to set your own.
193
+ """
194
+ options.setdefault("transport_security", self.transport_security())
195
+ app = self.server.streamable_http_app(streamable_http_path=self.mcp_path, **options)
196
+ app.add_exception_handler(404, _not_found)
197
+ app.add_middleware(
198
+ SignInMiddleware,
199
+ mcp_path=self.mcp_path,
200
+ public_base_url=self.public_base_url,
201
+ verifier=self.token_verifier,
202
+ )
203
+ return app
204
+
205
+ def transport_security(self) -> TransportSecuritySettings:
206
+ public = urlsplit(self.public_base_url)
207
+ host = public.netloc
208
+ origin = f"{public.scheme}://{host}"
209
+ return TransportSecuritySettings(
210
+ enable_dns_rebinding_protection=True,
211
+ allowed_hosts=[host, "127.0.0.1:*", "localhost:*", "[::1]:*"],
212
+ allowed_origins=[origin, "http://127.0.0.1:*", "http://localhost:*", "http://[::1]:*"],
213
+ )
214
+
215
+
216
+ def create_solvapay_mcp_server(
217
+ *,
218
+ solvapay: SolvaPay,
219
+ public_base_url: str,
220
+ product_ref: str | None = None,
221
+ name: str = "solvapay-mcp",
222
+ version: str = "1.0.0",
223
+ instructions: str | None = None,
224
+ mcp_path: str = "/mcp",
225
+ oauth_paths: dict[str, str] | None = None,
226
+ http_client: httpx.AsyncClient | None = None,
227
+ views: list[ViewKind] | None = None,
228
+ get_customer_ref: GetCustomerRef | None = None,
229
+ resource_uri: str | None = None,
230
+ csp: Mapping[str, Sequence[str]] | None = None,
231
+ hide_tools_by_audience: Sequence[str] | None = None,
232
+ hide_tools_bypass: BypassWhen | None = None,
233
+ ) -> SolvaPayMcpServer:
234
+ """An MCP server whose customers sign in with SolvaPay.
235
+
236
+ ``public_base_url`` is where clients reach this server (an ngrok URL in
237
+ development). It is the OAuth issuer clients see, and where Stripe sends the
238
+ customer back after 3-D Secure.
239
+
240
+ The server comes with SolvaPay's built-in tools, as the TypeScript server does:
241
+ ``account`` (checkout, account and top-up views; ``views`` picks which, and an
242
+ empty list leaves the tool out) and ``activate_plan``, the ``/upgrade``,
243
+ ``/manage_account``, ``/topup`` and ``/activate_plan`` prompts, and the
244
+ ``docs://solvapay/overview.md`` resource. ``get_customer_ref`` overrides who the
245
+ customer is for them; by default it is the verified access token's.
246
+
247
+ On MCP Apps hosts (ChatGPT, Claude) ``account`` opens the SolvaPay widget,
248
+ served at ``resource_uri`` (default ``ui://<name>/mcp-app.html``). The widget
249
+ calls six transport tools (``create_payment_intent``, ``process_payment``,
250
+ ``create_hosted_session``, ``set_renewal``, ``attach_business_details``,
251
+ ``get_history``) and reads ``solvapay://bootstrap.json``. ``csp`` adds domains to
252
+ the widget's Content Security Policy (``resourceDomains``, ``connectDomains``,
253
+ ``frameDomains``) on top of Stripe's and the SolvaPay API's.
254
+
255
+ ``hide_tools_by_audience=["ui"]`` leaves the transport tools out of
256
+ ``tools/list`` for hosts that ignore ``_meta.ui.visibility``. They stay
257
+ callable. ChatGPT always gets the full list (its iframe can only call listed
258
+ tools); ``hide_tools_bypass`` replaces that check.
259
+ """
260
+ if not public_base_url.startswith(("https://", "http://")):
261
+ raise SolvaPayError("public_base_url must be an http(s) URL", code="invalid_argument")
262
+ product = solvapay.require_product(product_ref)
263
+ base = public_base_url.rstrip("/")
264
+ api_base_url = solvapay.api.api_base_url
265
+ uri = resource_uri or default_resource_uri(name)
266
+ enabled_views = ADVERTISED_VIEWS if views is None else views
267
+ resolve = get_customer_ref or default_customer_ref
268
+
269
+ # Sign-in is SignInMiddleware's (see http_app), not the MCP SDK's: it answers
270
+ # unauthenticated requests and serves discovery as the TypeScript SDK does.
271
+ server = _AppServer(
272
+ name=name,
273
+ version=version,
274
+ instructions=instructions,
275
+ middleware=[HideToolsByAudience(hide_tools_by_audience, hide_tools_bypass)]
276
+ if hide_tools_by_audience
277
+ else None,
278
+ )
279
+ for route in oauth_bridge_routes(
280
+ public_base_url=base,
281
+ api_base_url=api_base_url,
282
+ product_ref=product,
283
+ paths=oauth_paths,
284
+ http_client=http_client,
285
+ ):
286
+ server.custom_route(route.path, methods=sorted(route.methods or []))(route.endpoint)
287
+ register_intent_tools(
288
+ server,
289
+ solvapay=solvapay,
290
+ product_ref=product,
291
+ public_base_url=public_base_url,
292
+ views=enabled_views,
293
+ get_customer_ref=get_customer_ref,
294
+ resource_uri=uri,
295
+ )
296
+ register_transport_tools(
297
+ server,
298
+ solvapay=solvapay,
299
+ product_ref=product,
300
+ resource_uri=uri,
301
+ get_customer_ref=get_customer_ref,
302
+ )
303
+ server.add_resource(app_resource(uri, merge_csp(csp, api_base_url), widget_html()))
304
+
305
+ async def read_bootstrap(context: Context[Any, Any]) -> str:
306
+ # The snapshot `account` answers when `view` is omitted.
307
+ customer_ref = await _resolve_customer(resolve, {}, context)
308
+ data = await build_bootstrap_payload(
309
+ solvapay,
310
+ view="account",
311
+ product_ref=product,
312
+ public_base_url=public_base_url,
313
+ customer_ref=customer_ref,
314
+ )
315
+ data["view"] = derive_default_view(data, enabled_views)
316
+ return json.dumps(data, separators=(",", ":"), ensure_ascii=False)
317
+
318
+ server.bootstrap_reader = read_bootstrap
319
+
320
+ def answered_by_server() -> str:
321
+ raise SolvaPayError(
322
+ f"{BOOTSTRAP_URI} is read through the SolvaPay MCP server", code="unexpected_read"
323
+ )
324
+
325
+ server.resource(
326
+ BOOTSTRAP_URI,
327
+ name="SolvaPay bootstrap",
328
+ title="SolvaPay bootstrap",
329
+ description=(
330
+ "Current merchant/product/plans/customer snapshot for the embedded UI. Widgets "
331
+ "read this idempotently when the host scrubs structuredContent from tool results."
332
+ ),
333
+ mime_type=BOOTSTRAP_MIME_TYPE,
334
+ )(answered_by_server)
335
+ return SolvaPayMcpServer(
336
+ server=server,
337
+ solvapay=solvapay,
338
+ product_ref=product,
339
+ mcp_path=mcp_path,
340
+ public_base_url=base,
341
+ resource_uri=uri,
342
+ token_verifier=SolvaPayTokenVerifier(api_base_url=api_base_url, http_client=http_client),
343
+ )