portage-ucp-webmcp 0.1.0 → 0.1.1
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +54 -1
- data/README.md +94 -5
- data/lib/portage/ucp/webmcp/assets/registrar.js +72 -12
- data/lib/portage/ucp/webmcp/page_wait.rb +84 -0
- data/lib/portage/ucp/webmcp/rack/call_endpoint.rb +144 -51
- data/lib/portage/ucp/webmcp/rack/request_limits.rb +55 -0
- data/lib/portage/ucp/webmcp/registrar.rb +12 -1
- data/lib/portage/ucp/webmcp/transport.rb +13 -8
- data/lib/portage/ucp/webmcp/version.rb +1 -1
- data/lib/portage/ucp/webmcp.rb +1 -0
- metadata +34 -4
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 0af5e77acced08e6ebf2e42ab60bf83281af6d61adb5c1b793d76814eea6585f
|
|
4
|
+
data.tar.gz: f430fb109a83774a3a8b531af4946269986c5f0aae6ad0d93cf12216088afd4f
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 90e4e18799cb69f1bcec89cee2839f71fbaa11caea7628c100d3dbf814f016d0dbe3e60391cf6c33de3301b0f84694d0c568c1ebf2a505335bbaebe09bd9c220
|
|
7
|
+
data.tar.gz: 8006c6d4107d530bc606f8ce5cd7e8aba1131b30d6bdccf78f544d89db7a8c9225c10076860856d3ef0838ec83fe4384b0b576f14a28912e379ff349ddaa95bb
|
data/CHANGELOG.md
CHANGED
|
@@ -4,7 +4,60 @@ All notable changes to this project are documented here. Format loosely follows
|
|
|
4
4
|
[Keep a Changelog](https://keepachangelog.com/en/1.0.0/); this project is
|
|
5
5
|
pre-1.0, so APIs may still shift between minor versions.
|
|
6
6
|
|
|
7
|
-
## [0.1.
|
|
7
|
+
## [0.1.1] - 2026-09-24
|
|
8
|
+
|
|
9
|
+
- `Rack::CallEndpoint` resolves the caller through core's
|
|
10
|
+
`Rack::ForwardedRequest`: `X-Forwarded-*`/`Forwarded` are trusted only
|
|
11
|
+
from a configured `trusted_proxies` list, `server_context[:client_ip]`
|
|
12
|
+
(seen by the rate limiter and authenticator) is the right-most untrusted
|
|
13
|
+
hop, and `X-Forwarded-Host` never widens `allowed_origins`. Requires
|
|
14
|
+
`portage-ucp` `~> 0.10`.
|
|
15
|
+
- An outbound call now waits out a tool that answers the page isn't ready,
|
|
16
|
+
as it already waited out one the page dropped. Shopify storefronts reload
|
|
17
|
+
after their own `add_to_cart`/`cancel_cart` and, until they're back, every
|
|
18
|
+
cart tool answers "Standard Actions are not available… Try again" (as an
|
|
19
|
+
`isError` result, a JSON string or a thrown error), which surfaced as
|
|
20
|
+
`ServerError` (seen live on thelightyard.co.uk and burton.com).
|
|
21
|
+
Only the messages in `PageWait::NOT_READY` are retried; any other tool
|
|
22
|
+
error is still raised at once, so a mutation can't run twice. The default
|
|
23
|
+
`reregister_wait:` goes from 2s to 5s: with several browsers busy the tools
|
|
24
|
+
took up to ~3s to come back.
|
|
25
|
+
|
|
26
|
+
- `Rack::CallEndpoint` no longer raises `TypeError` when a `tools/call` body
|
|
27
|
+
sends `params` as a string, number or boolean instead of an object; it
|
|
28
|
+
answers `-32602 Invalid params` like any other bad call. A top-level
|
|
29
|
+
JSON-RPC batch (an array) and a non-string `method` were already handled
|
|
30
|
+
without crashing; both now have specs.
|
|
31
|
+
- `Rack::CallEndpoint` takes `max_body_bytes:` (default 1MiB). A
|
|
32
|
+
`Content-Length` over the cap is refused with `413` before anything is
|
|
33
|
+
read; otherwise at most `max_body_bytes + 1` bytes are ever read off the
|
|
34
|
+
body, so a missing or understated `Content-Length` can't be used to buffer
|
|
35
|
+
an unbounded body first.
|
|
36
|
+
- `Rack::CallEndpoint` takes `call_timeout:` (default 30s, `nil` disables it),
|
|
37
|
+
bounding one dispatch into the catalog's `Mcp::Server#handle` so a slow
|
|
38
|
+
adapter call can't hold a browser's `fetch` open indefinitely. Every
|
|
39
|
+
rejection this endpoint answers — origin/method/content-type/size checks
|
|
40
|
+
included — now shares one JSON-RPC error envelope shape.
|
|
41
|
+
- `registrar.js` no longer races a Turbo/SPA reload against itself: a second
|
|
42
|
+
`GET /webmcp.js` now awaits the previous generation's own in-flight
|
|
43
|
+
`registerTool` calls (and that generation's `unregister`) before
|
|
44
|
+
registering the same names again, bounded by `reregister_wait_ms:`
|
|
45
|
+
(default 2000) so a previous generation that never settles can't block the
|
|
46
|
+
page forever. Previously, a fast-enough reload could start registering
|
|
47
|
+
before the first generation had actually dropped anything, and the second
|
|
48
|
+
generation's calls would collide on every tool name.
|
|
49
|
+
- Security review: added a spec confirming `ScriptEvaluator` can't be broken
|
|
50
|
+
out of by a tool name or argument containing JS-breaking characters (it's
|
|
51
|
+
JSON-encoded, never interpolated into the expression's own syntax).
|
|
52
|
+
README: new "Content-Security-Policy" and "CSRF posture" sections, and a
|
|
53
|
+
"Request limits" section documenting `max_body_bytes:`/`call_timeout:`.
|
|
54
|
+
- `spec/portage/ucp/webmcp/real_browser_spec.rb`: registrar.js register ->
|
|
55
|
+
tool call -> re-register against a real, headless Chrome (via a new
|
|
56
|
+
`ferrum` dev dependency), not just the `:node` specs' stand-in tab.
|
|
57
|
+
Excluded by default (slow, needs Chrome installed); run with
|
|
58
|
+
`REAL_BROWSER=1 bundle exec rspec spec/portage/ucp/webmcp/real_browser_spec.rb`.
|
|
59
|
+
|
|
60
|
+
## [0.1.0] - 2026-09-23
|
|
8
61
|
|
|
9
62
|
- Initial release. WebMCP as a transport to the existing `Adapter` contract.
|
|
10
63
|
- The registrar reports a non-JSON reply from its endpoint (a proxy's HTML
|
data/README.md
CHANGED
|
@@ -83,6 +83,13 @@ What the catalog exposes:
|
|
|
83
83
|
`Rack::CallEndpoint` enforces the same filter on the server side. An action the
|
|
84
84
|
page doesn't register can't be reached by POSTing its name.
|
|
85
85
|
|
|
86
|
+
A second `GET /webmcp.js` (a Turbo/SPA reload re-running the script tag)
|
|
87
|
+
re-registers cleanly: it waits for the previous generation's own in-flight
|
|
88
|
+
`registerTool` calls to settle and unregister before registering the same
|
|
89
|
+
names again, bounded by `registrar_options: { reregister_wait_ms: }` (default
|
|
90
|
+
2000) so a previous generation that never settles can't block the page
|
|
91
|
+
forever.
|
|
92
|
+
|
|
86
93
|
### Security
|
|
87
94
|
|
|
88
95
|
The endpoint is browser-facing and the page's cookies go with every call. For
|
|
@@ -117,6 +124,73 @@ Portage::Ucp::WebMcp::Rack::App.new(
|
|
|
117
124
|
The endpoint then answers the CORS preflight and sends credentialed CORS
|
|
118
125
|
headers for that origin only.
|
|
119
126
|
|
|
127
|
+
### Request limits
|
|
128
|
+
|
|
129
|
+
Two more limits bound a single `POST /webmcp`, on top of the `Origin`/method/
|
|
130
|
+
content-type checks above. Every rejection — these two, the checks above, and
|
|
131
|
+
a JSON-RPC error `dispatch` itself returns — answers with the same JSON-RPC
|
|
132
|
+
error envelope, so a caller never needs to branch on HTTP status to read why
|
|
133
|
+
a call failed.
|
|
134
|
+
|
|
135
|
+
- **`max_body_bytes:`** (default 1MiB). A `Content-Length` over the cap is
|
|
136
|
+
refused with `413` before anything is read. Otherwise at most
|
|
137
|
+
`max_body_bytes + 1` bytes are ever read off the request body, so a body
|
|
138
|
+
with no `Content-Length` (or one that under-reports) still can't be
|
|
139
|
+
buffered in full first.
|
|
140
|
+
- **`call_timeout:`** (default 30 seconds, `nil` disables it). Bounds one
|
|
141
|
+
`tools/call`/`tools/list` dispatch into the catalog's `Mcp::Server#handle`.
|
|
142
|
+
A call that runs past it answers a JSON-RPC error rather than holding the
|
|
143
|
+
browser's `fetch` (and the request thread) open indefinitely. This is a
|
|
144
|
+
floor under the endpoint, not a replacement for your own `Adapter`/HTTP
|
|
145
|
+
client timeouts — a slow adapter call still ties up the thread until it
|
|
146
|
+
fires.
|
|
147
|
+
|
|
148
|
+
```ruby
|
|
149
|
+
Portage::Ucp::WebMcp::Rack::App.new(
|
|
150
|
+
catalog: catalog,
|
|
151
|
+
call_options: { max_body_bytes: 262_144, call_timeout: 10 }
|
|
152
|
+
)
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### Content-Security-Policy
|
|
156
|
+
|
|
157
|
+
The registrar's script and its `fetch` calls need two directives, if your
|
|
158
|
+
store sets a CSP:
|
|
159
|
+
|
|
160
|
+
- **`script-src`**: allow the origin `GET /webmcp.js` is served from (usually
|
|
161
|
+
your own, `'self'`). The script has no inline `<script>` body — it's a
|
|
162
|
+
`src=` include — so no `'unsafe-inline'` or nonce is needed for it.
|
|
163
|
+
- **`connect-src`**: allow the origin `POST /webmcp` targets. For a
|
|
164
|
+
same-origin endpoint, `'self'` already covers it. For the cross-origin
|
|
165
|
+
pattern above (`registrar_options: { endpoint: "https://api.shop.example/..." }`),
|
|
166
|
+
add that origin explicitly: `connect-src 'self' https://api.shop.example`.
|
|
167
|
+
Also add it for every origin passed to `exposed_to:` if that agent surface
|
|
168
|
+
itself calls the endpoint from a different frame's document.
|
|
169
|
+
|
|
170
|
+
Nothing here needs `'unsafe-eval'`: the registrar only calls `fetch` and
|
|
171
|
+
`document.modelContext.registerTool`, never `eval` or `new Function`.
|
|
172
|
+
|
|
173
|
+
### CSRF posture
|
|
174
|
+
|
|
175
|
+
`allowed_origins`/`Origin` checking (above) is the endpoint's primary CSRF
|
|
176
|
+
defense: a browser attaches the real `Origin` on every `fetch`, and page
|
|
177
|
+
script can't override it, so a cross-site page's request is rejected before
|
|
178
|
+
your `Authenticator` ever sees it — the same protection `SameSite` cookies
|
|
179
|
+
give a classic form POST, enforced here explicitly since the endpoint has to
|
|
180
|
+
work from a cross-origin storefront too (`allowed_origins:`).
|
|
181
|
+
|
|
182
|
+
If your `Authenticator` reads a session cookie (cookie-auth, `credentials:
|
|
183
|
+
"same-origin"` or `"include"`), also set a CSRF token, the same as you would
|
|
184
|
+
for any other cookie-authenticated POST endpoint: put it on the page's
|
|
185
|
+
requests with `registrar_options: { headers: { "x-csrf-token" => token } }`
|
|
186
|
+
and check `server_context[:request]` for it in your `Authenticator`, exactly
|
|
187
|
+
as `spec/support/store.rb` does in this gem's own specs. `Origin` checking
|
|
188
|
+
alone is not a substitute for this when the endpoint's `Authenticator` trusts
|
|
189
|
+
a cookie: a same-origin `Origin` only proves the request came from a page on
|
|
190
|
+
your site, not that the page is the one your store served (an XSS on another
|
|
191
|
+
page of the same origin, or a subdomain sharing the cookie's domain, can
|
|
192
|
+
still fetch same-origin).
|
|
193
|
+
|
|
120
194
|
### Browsers without WebMCP
|
|
121
195
|
|
|
122
196
|
When the page has no `modelContext`, the registrar does nothing. It records
|
|
@@ -199,8 +273,12 @@ something the consumer can list.
|
|
|
199
273
|
`executeTool` resolves to one) is parsed. Anything else is returned as it is.
|
|
200
274
|
- **Re-registration.** Some pages drop all their tools and register them again
|
|
201
275
|
while they re-render. A call to a tool that vanished that way waits up to
|
|
202
|
-
`reregister_wait:` (default
|
|
203
|
-
The call never ran the first time, so the retry is safe. The wait
|
|
276
|
+
`reregister_wait:` (default 5 seconds) for it to come back, then retries.
|
|
277
|
+
The call never ran the first time, so the retry is safe. The same wait
|
|
278
|
+
covers a tool that is registered but answers that the page isn't ready
|
|
279
|
+
(`PageWait::NOT_READY`: Shopify's "Standard Actions are not available",
|
|
280
|
+
which its storefronts answer while they reload after their own
|
|
281
|
+
`add_to_cart` or `cancel_cart`). No other tool error is retried. The wait blocks
|
|
204
282
|
the calling thread; see "Timeouts" below.
|
|
205
283
|
|
|
206
284
|
### Timeouts
|
|
@@ -212,8 +290,9 @@ Two limits bound an outbound call, and both block the thread that made it:
|
|
|
212
290
|
30 seconds) to `evaluate_async`. Playwright and Selenium use the page's or
|
|
213
291
|
driver's own script timeout, so set it there. A driver that times out
|
|
214
292
|
raises, and the error surfaces as `BridgeError`.
|
|
215
|
-
- **`reregister_wait:`** (default
|
|
216
|
-
reregister_wait:)`) bounds the wait for a tool the page dropped mid-call
|
|
293
|
+
- **`reregister_wait:`** (default 5 seconds, `WebMcp.connect(...,
|
|
294
|
+
reregister_wait:)`) bounds the wait for a tool the page dropped mid-call,
|
|
295
|
+
or one that answered "not ready".
|
|
217
296
|
It's a plain `sleep`, polling every 0.25 seconds. One monotonic deadline
|
|
218
297
|
covers the whole call: it's set before the first attempt, a retry never
|
|
219
298
|
resets it, the retried calls count against it, and no sleep runs past it.
|
|
@@ -257,7 +336,7 @@ still catch them.
|
|
|
257
336
|
|---|---|
|
|
258
337
|
| `WebMcp::BridgeError` | The page has no WebMCP surface, the driver failed, or the result couldn't be read. It quotes at most 300 characters of the driver's own error. |
|
|
259
338
|
| `WebMcp::ToolNotFoundError` | No page tool answers the action. `#available` lists what the page registers. |
|
|
260
|
-
| `Client::ServerError` | The tool ran and failed: `isError`,
|
|
339
|
+
| `Client::ServerError` | The tool ran and failed: `isError`, the page's tool threw, or the endpoint's own `call_timeout:` fired. |
|
|
261
340
|
|
|
262
341
|
## Development
|
|
263
342
|
|
|
@@ -273,3 +352,13 @@ the real `Rack::App`. This makes the round-trip specs go page, then endpoint,
|
|
|
273
352
|
then `Mcp::Server`, then `ReferenceAdapter`, with nothing mocked. They also
|
|
274
353
|
check that WebMCP returns the same documents as the in-process Loopback
|
|
275
354
|
transport. These specs are skipped when `node` isn't installed.
|
|
355
|
+
|
|
356
|
+
`spec/portage/ucp/webmcp/real_browser_spec.rb` runs the same register ->
|
|
357
|
+
call -> re-register sequence against a real, headless Chrome (via `ferrum`)
|
|
358
|
+
instead of the node stand-in, for a second confirmation against an actual
|
|
359
|
+
browser's WebMCP/fetch behavior. It's slow and needs Chrome or Chromium
|
|
360
|
+
installed, so it's excluded by default:
|
|
361
|
+
|
|
362
|
+
```bash
|
|
363
|
+
REAL_BROWSER=1 bundle exec rspec spec/portage/ucp/webmcp/real_browser_spec.rb
|
|
364
|
+
```
|
|
@@ -19,15 +19,39 @@
|
|
|
19
19
|
var state = { registered: [], errors: [], reason: null, unregister: unregister };
|
|
20
20
|
var controller = typeof AbortController === "function" ? new AbortController() : null;
|
|
21
21
|
var handles = [];
|
|
22
|
+
var pending = [];
|
|
22
23
|
var nextId = 0;
|
|
23
24
|
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
|
|
25
|
+
// Bounded wait, in ms, for the previous generation's own registerTool
|
|
26
|
+
// calls (still in flight when a Turbo/SPA reload re-runs this script tag)
|
|
27
|
+
// to settle and unregister before this generation registers the same
|
|
28
|
+
// names. registerTool is async, so a second load can otherwise start
|
|
29
|
+
// registering before the first generation's unregister has actually
|
|
30
|
+
// dropped anything, colliding on every name. Same shape as Transport's
|
|
31
|
+
// reregister_wait: one deadline, never reset, a stuck previous generation
|
|
32
|
+
// costs at most this much (see CHANGELOG's 0e8d49c and the README's
|
|
33
|
+
// "Timeouts").
|
|
34
|
+
var REREGISTER_WAIT_MS = (config && config.reregisterWaitMs) || 2000;
|
|
35
|
+
|
|
36
|
+
function timeoutAfter(ms) {
|
|
37
|
+
return new Promise(function (resolve) { setTimeout(resolve, ms); });
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Drop the previous generation's registrations before this one starts.
|
|
41
|
+
// `unregister()` itself waits out that generation's own pending
|
|
42
|
+
// registerTool calls (see below), so this is only racing a previous
|
|
43
|
+
// generation that never settles at all.
|
|
44
|
+
var previous = root.portageWebMcp;
|
|
45
|
+
var previousDone = previous && typeof previous.unregister === "function"
|
|
46
|
+
? Promise.race([previous.unregister(), timeoutAfter(REREGISTER_WAIT_MS)])
|
|
47
|
+
: Promise.resolve();
|
|
27
48
|
root.portageWebMcp = state;
|
|
28
49
|
|
|
29
50
|
// Current spec: `document.modelContext`. Earlier drafts, and the browser
|
|
30
|
-
// builds that shipped them, used `navigator.modelContext`.
|
|
51
|
+
// builds that shipped them, used `navigator.modelContext`. Neither
|
|
52
|
+
// `document` nor `navigator` is guaranteed to exist on every host this
|
|
53
|
+
// script can be evaluated in (a worker, a test harness), so both reads are
|
|
54
|
+
// optional-chained by hand rather than assumed.
|
|
31
55
|
var context = (doc && doc.modelContext) || (nav && nav.modelContext);
|
|
32
56
|
if (!context || typeof context.registerTool !== "function") {
|
|
33
57
|
state.reason = "no_model_context";
|
|
@@ -103,31 +127,67 @@
|
|
|
103
127
|
}
|
|
104
128
|
|
|
105
129
|
function register(tool) {
|
|
130
|
+
var settled;
|
|
106
131
|
try {
|
|
107
132
|
var handle = context.registerTool(descriptor(tool), registerOptions());
|
|
108
|
-
Promise.resolve(handle).then(function (resolved) {
|
|
109
|
-
if (resolved && typeof resolved.unregister === "function") handles.push(resolved);
|
|
133
|
+
settled = Promise.resolve(handle).then(function (resolved) {
|
|
134
|
+
if (resolved && typeof resolved.unregister === "function") handles.push({ name: tool.name, handle: resolved });
|
|
110
135
|
state.registered.push(tool.name);
|
|
111
136
|
}, function (error) {
|
|
112
137
|
state.errors.push({ tool: tool.name, message: String((error && error.message) || error) });
|
|
113
138
|
});
|
|
114
139
|
} catch (error) {
|
|
115
140
|
state.errors.push({ tool: tool.name, message: String((error && error.message) || error) });
|
|
141
|
+
settled = Promise.resolve();
|
|
116
142
|
}
|
|
143
|
+
pending.push(settled);
|
|
117
144
|
}
|
|
118
145
|
|
|
119
146
|
// Spec surface unregisters on the AbortSignal passed at registration;
|
|
120
147
|
// earlier drafts returned a handle with `unregister()` or offered
|
|
121
148
|
// `unregisterTool(name)`. All three are tried — each is a no-op where the
|
|
122
149
|
// browser doesn't implement it.
|
|
150
|
+
//
|
|
151
|
+
// Waits out this generation's own pending registerTool calls first (each
|
|
152
|
+
// wrapped so one rejecting can't stall the others), so a caller — or the
|
|
153
|
+
// next generation's script, racing this promise above — never unregisters
|
|
154
|
+
// a name that hasn't finished registering yet, which would otherwise leave
|
|
155
|
+
// it orphaned on `context` with nothing in `handles` to drop it.
|
|
156
|
+
//
|
|
157
|
+
// By the time those pending calls settle, a newer generation may already
|
|
158
|
+
// have taken over `root.portageWebMcp` (this is exactly the slow-previous-
|
|
159
|
+
// generation case REREGISTER_WAIT_MS bounds the *wait* for, not the
|
|
160
|
+
// *cleanup*): if this generation's own `registerTool` call was slower than
|
|
161
|
+
// that bound, its belated success races the new generation's registration
|
|
162
|
+
// of the same name. Cleanup here must not delete a name the current
|
|
163
|
+
// generation has since (re-)registered — the legacy `unregisterTool(name)`
|
|
164
|
+
// fallback in particular can't tell "this call belongs to my stale
|
|
165
|
+
// registration" from "this name now belongs to the current generation", so
|
|
166
|
+
// it's skipped for any name the current generation now owns.
|
|
123
167
|
function unregister() {
|
|
124
168
|
if (controller) controller.abort();
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
169
|
+
var settled = Promise.all(pending.map(function (p) { return p.catch(function () {}); }));
|
|
170
|
+
return settled.then(function () {
|
|
171
|
+
var current = root.portageWebMcp;
|
|
172
|
+
var superseded = current !== state;
|
|
173
|
+
function ownedByCurrentGeneration(name) {
|
|
174
|
+
return superseded && current && current.registered && current.registered.indexOf(name) !== -1;
|
|
175
|
+
}
|
|
176
|
+
handles.forEach(function (entry) {
|
|
177
|
+
if (ownedByCurrentGeneration(entry.name)) return;
|
|
178
|
+
try { entry.handle.unregister(); } catch (_e) { /* already gone */ }
|
|
179
|
+
});
|
|
180
|
+
if (context && typeof context.unregisterTool === "function") {
|
|
181
|
+
config.tools.forEach(function (tool) {
|
|
182
|
+
if (ownedByCurrentGeneration(tool.name)) return;
|
|
183
|
+
try { context.unregisterTool(tool.name); } catch (_e) { /* already gone */ }
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
state.registered = [];
|
|
187
|
+
});
|
|
130
188
|
}
|
|
131
189
|
|
|
132
|
-
|
|
190
|
+
previousDone.then(function () {
|
|
191
|
+
config.tools.forEach(register);
|
|
192
|
+
});
|
|
133
193
|
})(__PORTAGE_WEBMCP_CONFIG__);
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
module Portage
|
|
2
|
+
module Ucp
|
|
3
|
+
module WebMcp
|
|
4
|
+
# One tool call's wait for a page that can't take it yet (see
|
|
5
|
+
# Transport#execute): the call is sent again until it lands or one
|
|
6
|
+
# deadline, set when the wait starts, runs out. Two answers mean the
|
|
7
|
+
# call never ran, so sending it again can't run it twice:
|
|
8
|
+
#
|
|
9
|
+
# - ToolNotFoundError: the page dropped the tool mid-re-render.
|
|
10
|
+
# - One of NOT_READY, thrown by the tool or returned as an `isError`
|
|
11
|
+
# result. Shopify storefronts answer "Standard Actions are not
|
|
12
|
+
# available. Ensure Shopify Standard Actions are available before
|
|
13
|
+
# calling cart tools. Recovery: Try again - this is usually a
|
|
14
|
+
# transient error." for a moment after their own add_to_cart or
|
|
15
|
+
# cancel_cart (confirmed live 2026-09-24 on thelightyard.co.uk and
|
|
16
|
+
# burton.com).
|
|
17
|
+
#
|
|
18
|
+
# Every other error is raised at once: retrying it could run a
|
|
19
|
+
# mutation twice.
|
|
20
|
+
class PageWait
|
|
21
|
+
NOT_READY = [/Standard Actions are not available/].freeze
|
|
22
|
+
RETRY = Object.new.freeze
|
|
23
|
+
private_constant :RETRY
|
|
24
|
+
|
|
25
|
+
def self.not_ready?(text) = !text.nil? && NOT_READY.any? { |pattern| pattern.match?(text) }
|
|
26
|
+
|
|
27
|
+
# @param raw a CallToolResult Hash, or the same as a JSON string (how
|
|
28
|
+
# Shopify storefronts' tools answer through the page's WebMCP
|
|
29
|
+
# surface).
|
|
30
|
+
def self.not_ready_result?(raw)
|
|
31
|
+
raw = parse(raw) if raw.is_a?(String)
|
|
32
|
+
return false unless raw.is_a?(Hash) && raw["isError"]
|
|
33
|
+
|
|
34
|
+
not_ready?(Portage::Ucp::Client::ToolResult.text(raw["content"], symbol_keys: false).to_s)
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def self.parse(text)
|
|
38
|
+
JSON.parse(text)
|
|
39
|
+
rescue JSON::ParserError
|
|
40
|
+
nil
|
|
41
|
+
end
|
|
42
|
+
private_class_method :parse
|
|
43
|
+
|
|
44
|
+
# @param now [#call] a monotonic clock, in seconds.
|
|
45
|
+
# @param sleep [#call] sleeps the seconds it's given.
|
|
46
|
+
def initialize(wait:, poll:, now:, sleep:)
|
|
47
|
+
@poll = poll
|
|
48
|
+
@now = now
|
|
49
|
+
@sleep = sleep
|
|
50
|
+
@deadline = now.call + wait
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# @param gone [#call] builds the error to raise when the tool is
|
|
54
|
+
# still missing at the deadline.
|
|
55
|
+
# @yield sends the call once; its value is the call's result.
|
|
56
|
+
def call(gone:, &send_call)
|
|
57
|
+
loop do
|
|
58
|
+
raw = attempt(gone, &send_call)
|
|
59
|
+
return raw unless raw.equal?(RETRY)
|
|
60
|
+
|
|
61
|
+
@sleep.call((@deadline - @now.call).clamp(0, @poll))
|
|
62
|
+
end
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
private
|
|
66
|
+
|
|
67
|
+
def attempt(gone)
|
|
68
|
+
raw = yield
|
|
69
|
+
self.class.not_ready_result?(raw) && !expired? ? RETRY : raw
|
|
70
|
+
rescue ToolNotFoundError
|
|
71
|
+
raise gone.call if expired?
|
|
72
|
+
|
|
73
|
+
RETRY
|
|
74
|
+
rescue Portage::Ucp::Client::ServerError => e
|
|
75
|
+
raise unless self.class.not_ready?(e.message) && !expired?
|
|
76
|
+
|
|
77
|
+
RETRY
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
def expired? = @now.call >= @deadline
|
|
81
|
+
end
|
|
82
|
+
end
|
|
83
|
+
end
|
|
84
|
+
end
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
require "json"
|
|
2
2
|
require "rack"
|
|
3
|
+
require_relative "request_limits"
|
|
3
4
|
|
|
4
5
|
module Portage
|
|
5
6
|
module Ucp
|
|
@@ -10,15 +11,14 @@ module Portage
|
|
|
10
11
|
# Portage::Ucp::Mcp::Server — the same Authenticator, RateLimiter,
|
|
11
12
|
# Dispatcher and WireEnvelope stdio and Streamable HTTP go through.
|
|
12
13
|
#
|
|
13
|
-
# Browser-facing, so it is stricter than a plain MCP endpoint:
|
|
14
|
-
#
|
|
15
|
-
#
|
|
16
|
-
#
|
|
17
|
-
#
|
|
18
|
-
#
|
|
19
|
-
#
|
|
20
|
-
#
|
|
21
|
-
# catalog exposes.
|
|
14
|
+
# Browser-facing, so it is stricter than a plain MCP endpoint: JSON
|
|
15
|
+
# bodies only (a cross-site `<form>` can't reach it without a CORS
|
|
16
|
+
# preflight); an `Origin` matching `allowed_origins` (default: this
|
|
17
|
+
# request's own origin) is required, since the page's cookies ride
|
|
18
|
+
# along and an Authenticator reading them would otherwise be open to
|
|
19
|
+
# CSRF; only tools/call and tools/list, and only for actions the
|
|
20
|
+
# catalog exposes; and both the body size and the call itself are
|
|
21
|
+
# bounded (`max_body_bytes:`, `call_timeout:`).
|
|
22
22
|
#
|
|
23
23
|
# The Authenticator's server_context carries `transport: "webmcp"`,
|
|
24
24
|
# `request:` (the Rack::Request, for session cookies or a CSRF
|
|
@@ -27,51 +27,133 @@ module Portage
|
|
|
27
27
|
METHODS = %w[tools/call tools/list].freeze
|
|
28
28
|
JSON_HEADERS = { "content-type" => "application/json", "cache-control" => "no-store" }.freeze
|
|
29
29
|
|
|
30
|
+
# One JSON-RPC envelope shape for every failure path: a request that
|
|
31
|
+
# never reached `Mcp::Server` (bad origin, bad params, an oversized
|
|
32
|
+
# body) and one that ran there and timed out both answer this way.
|
|
33
|
+
PARSE_ERROR = -32_700
|
|
34
|
+
INVALID_REQUEST = -32_600
|
|
35
|
+
METHOD_NOT_FOUND = -32_601
|
|
36
|
+
INVALID_PARAMS = -32_602
|
|
37
|
+
SERVER_ERROR = -32_000
|
|
38
|
+
|
|
30
39
|
# @param allowed_origins [Array<String>, nil] exact origins
|
|
31
40
|
# ("https://shop.example"); nil allows only the endpoint's own.
|
|
41
|
+
# Checked against the real `Origin` header always — see
|
|
42
|
+
# #origin_allowed? and `forwarded_host_allowed:` below.
|
|
32
43
|
# @param require_origin [Boolean] reject requests with no `Origin`
|
|
33
|
-
# header
|
|
34
|
-
#
|
|
35
|
-
#
|
|
36
|
-
|
|
44
|
+
# header (every browser sends one on a POST fetch); turn off only
|
|
45
|
+
# for a non-browser caller (point it at the MCP endpoint instead).
|
|
46
|
+
# @param max_body_bytes [Integer] see RequestLimits.
|
|
47
|
+
# @param call_timeout [Numeric, nil] see RequestLimits.
|
|
48
|
+
# @param trusted_proxies [Array<String>] CIDRs of the consumer's
|
|
49
|
+
# own reverse proxy/load balancer (docs/plans/proxy-support.md
|
|
50
|
+
# Phase 3) — a consumer behind one sets this, e.g.
|
|
51
|
+
# `CallEndpoint.new(catalog: catalog, trusted_proxies:
|
|
52
|
+
# ["10.0.0.0/8"])`. Fail-closed: empty (the default) means every
|
|
53
|
+
# `X-Forwarded-*`/`Forwarded` header is ignored, unchanged from
|
|
54
|
+
# before this option existed. See Rack::ForwardedRequest.
|
|
55
|
+
# @param forwarded_host_allowed [Array<String>] host[:port] values
|
|
56
|
+
# `X-Forwarded-Host`/`Forwarded;host=` is allowed to replace
|
|
57
|
+
# "the endpoint's own origin" with (what #origin_allowed? treats
|
|
58
|
+
# as same-origin) — only from a trusted peer, and only ever
|
|
59
|
+
# *replacing* what "own origin" means, never adding to
|
|
60
|
+
# `allowed_origins` itself. A spoofed X-Forwarded-Host that
|
|
61
|
+
# isn't on this list (or didn't come from a trusted peer) has no
|
|
62
|
+
# effect at all.
|
|
63
|
+
# @param passthrough_headers [Array<String>] inbound header names
|
|
64
|
+
# allowlisted to reach outbound calls a tool makes while this
|
|
65
|
+
# request is being served (Support::Connection, via the
|
|
66
|
+
# fiber-local Support::PassthroughContext) — from a trusted peer
|
|
67
|
+
# only. Never a protected header (raises at construction time).
|
|
68
|
+
# @param passthrough_forwarded ["append", "replace", "drop"] see
|
|
69
|
+
# Support::PassthroughContext.
|
|
70
|
+
def initialize(catalog:, allowed_origins: nil, require_origin: true, trusted_proxies: [],
|
|
71
|
+
forwarded_host_allowed: [], passthrough_headers: [], passthrough_forwarded: "drop",
|
|
72
|
+
**limit_opts)
|
|
37
73
|
@catalog = catalog
|
|
38
74
|
@allowed_origins = allowed_origins&.map { |origin| origin.to_s.chomp("/") }
|
|
39
75
|
@require_origin = require_origin
|
|
76
|
+
@limits = RequestLimits.new(**limit_opts)
|
|
77
|
+
@trusted_proxies = trusted_proxies
|
|
78
|
+
@forwarded_host_allowed = forwarded_host_allowed
|
|
79
|
+
@passthrough_headers = passthrough_headers
|
|
80
|
+
@passthrough_forwarded = passthrough_forwarded
|
|
81
|
+
Portage::Ucp::Rack::ForwardedRequest.validate_passthrough!(@passthrough_headers)
|
|
40
82
|
end
|
|
41
83
|
|
|
42
84
|
def call(env)
|
|
43
85
|
request = ::Rack::Request.new(env)
|
|
44
|
-
|
|
45
|
-
return
|
|
46
|
-
return http_error(
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
86
|
+
forwarded = Portage::Ucp::Rack::ForwardedRequest.new(request, trusted_proxies: @trusted_proxies)
|
|
87
|
+
return preflight(request, forwarded) if request.options?
|
|
88
|
+
return http_error(request, 405, INVALID_REQUEST, "method not allowed", "allow" => "POST, OPTIONS") \
|
|
89
|
+
unless request.post?
|
|
90
|
+
return http_error(request, 403, INVALID_REQUEST, "origin not allowed") \
|
|
91
|
+
unless origin_allowed?(request, forwarded)
|
|
92
|
+
return http_error(request, 415, INVALID_REQUEST, "content-type must be application/json") \
|
|
93
|
+
unless request.media_type == "application/json"
|
|
94
|
+
return http_error(request, 413, SERVER_ERROR, "request body too large") \
|
|
95
|
+
if @limits.body_too_large?(request)
|
|
96
|
+
|
|
97
|
+
handle(request, forwarded)
|
|
50
98
|
end
|
|
51
99
|
|
|
52
100
|
private
|
|
53
101
|
|
|
54
|
-
def handle(request)
|
|
102
|
+
def handle(request, forwarded)
|
|
55
103
|
payload = parse(request)
|
|
56
|
-
return
|
|
104
|
+
return http_error(request, 413, SERVER_ERROR, "body too large") if payload == RequestLimits::TOO_LARGE
|
|
105
|
+
return respond(request, rpc_error(nil, PARSE_ERROR, "Parse error")) unless payload.is_a?(Hash)
|
|
57
106
|
|
|
58
|
-
respond(request, dispatch(request, payload))
|
|
107
|
+
respond(request, dispatch(request, forwarded, payload))
|
|
59
108
|
end
|
|
60
109
|
|
|
61
|
-
def dispatch(request, payload)
|
|
110
|
+
def dispatch(request, forwarded, payload)
|
|
62
111
|
id = payload[:id]
|
|
63
|
-
method = payload[:method]
|
|
64
|
-
return rpc_error(id,
|
|
112
|
+
method = payload[:method]
|
|
113
|
+
return rpc_error(id, METHOD_NOT_FOUND, "Method not found: #{method}") \
|
|
114
|
+
unless method.is_a?(String) && METHODS.include?(method)
|
|
65
115
|
return tools_list(id) if method == "tools/list"
|
|
66
116
|
|
|
67
|
-
name = payload
|
|
68
|
-
return rpc_error(id,
|
|
117
|
+
name = tool_name(payload[:params])
|
|
118
|
+
return rpc_error(id, INVALID_PARAMS, "Invalid params") if name.nil?
|
|
119
|
+
return rpc_error(id, INVALID_PARAMS, "Tool not exposed over WebMCP: #{name}") \
|
|
120
|
+
unless @catalog.exposes?(name)
|
|
121
|
+
|
|
122
|
+
result = with_passthrough(forwarded) do
|
|
123
|
+
@limits.call_with_timeout { server_for(request, forwarded).handle(payload) }
|
|
124
|
+
end
|
|
125
|
+
result == RequestLimits::TIMED_OUT ? rpc_error(id, SERVER_ERROR, "tool call timed out") : result
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# Only from a trusted peer, and only when there's actually
|
|
129
|
+
# something configured to pass through — an untrusted peer's
|
|
130
|
+
# request runs with no PassthroughContext at all, same as if
|
|
131
|
+
# trusted_proxies had never been set.
|
|
132
|
+
def with_passthrough(forwarded, &)
|
|
133
|
+
return yield unless forwarded.peer_trusted? && @passthrough_headers.any?
|
|
134
|
+
|
|
135
|
+
headers = forwarded.passthrough_headers(@passthrough_headers)
|
|
136
|
+
Portage::Ucp::Support::PassthroughContext.with(headers: headers, forwarded: @passthrough_forwarded,
|
|
137
|
+
chain_entry: forwarded.client_ip, &)
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# `params` on a well-formed `tools/call` is a Hash (or absent); a
|
|
141
|
+
# String/Integer/boolean there used to reach `payload.dig(:params,
|
|
142
|
+
# :name)`, which raises TypeError once `:params` isn't itself
|
|
143
|
+
# dig-able. `nil` here means "invalid", not "no name" — the caller
|
|
144
|
+
# can't tell those apart from an empty string.
|
|
145
|
+
def tool_name(params)
|
|
146
|
+
return "" if params.nil?
|
|
147
|
+
return nil unless params.is_a?(Hash)
|
|
69
148
|
|
|
70
|
-
|
|
149
|
+
params[:name].to_s
|
|
71
150
|
end
|
|
72
151
|
|
|
73
152
|
def parse(request)
|
|
74
|
-
|
|
153
|
+
raw = @limits.read_body(request)
|
|
154
|
+
return RequestLimits::TOO_LARGE if raw == RequestLimits::TOO_LARGE
|
|
155
|
+
|
|
156
|
+
JSON.parse(raw, symbolize_names: true)
|
|
75
157
|
rescue JSON::ParserError
|
|
76
158
|
nil
|
|
77
159
|
end
|
|
@@ -89,37 +171,43 @@ module Portage
|
|
|
89
171
|
# MCP::Server holds one server_context for its lifetime; a shallow
|
|
90
172
|
# copy per request gives each call its own without rebuilding the
|
|
91
173
|
# tool set or sharing state across concurrent requests.
|
|
92
|
-
|
|
174
|
+
#
|
|
175
|
+
# `client_ip` is the ForwardedRequest-resolved one (right-most
|
|
176
|
+
# untrusted hop from a trusted peer, the plain socket peer
|
|
177
|
+
# otherwise) — this is how a host app's RateLimiter/Authenticator
|
|
178
|
+
# reach the real client rather than the reverse proxy's own
|
|
179
|
+
# address (docs/plans/proxy-support.md Phase 3).
|
|
180
|
+
def server_for(request, forwarded)
|
|
93
181
|
@catalog.server.dup.tap do |server|
|
|
94
182
|
server.server_context = { transport: "webmcp", request: request,
|
|
95
|
-
origin: request.get_header("HTTP_ORIGIN")
|
|
183
|
+
origin: request.get_header("HTTP_ORIGIN"),
|
|
184
|
+
client_ip: forwarded.client_ip }
|
|
96
185
|
end
|
|
97
186
|
end
|
|
98
187
|
|
|
99
|
-
|
|
188
|
+
# `Origin` itself is always the real header — never replaced or
|
|
189
|
+
# widened by anything forwarded. Only what counts as "our own
|
|
190
|
+
# origin" (the right-hand side of the comparison, for the
|
|
191
|
+
# `allowed_origins.nil?` default case) can move, and only to a
|
|
192
|
+
# host explicitly listed in `forwarded_host_allowed`, from a
|
|
193
|
+
# trusted peer. A spoofed X-Forwarded-Host that fails either
|
|
194
|
+
# check leaves this exactly as if it were never sent.
|
|
195
|
+
def origin_allowed?(request, forwarded)
|
|
100
196
|
origin = request.get_header("HTTP_ORIGIN")
|
|
101
197
|
return !@require_origin if origin.nil? || origin.empty?
|
|
102
198
|
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
def allowed_origins(request)
|
|
107
|
-
@allowed_origins || [request.base_url]
|
|
108
|
-
end
|
|
109
|
-
|
|
110
|
-
def json?(request)
|
|
111
|
-
request.media_type == "application/json"
|
|
199
|
+
own_origin = forwarded.own_origin(forwarded_host_allowed: @forwarded_host_allowed)
|
|
200
|
+
(@allowed_origins || [own_origin]).include?(origin.chomp("/"))
|
|
112
201
|
end
|
|
113
202
|
|
|
114
|
-
def preflight(request)
|
|
115
|
-
return http_error(403, "origin not allowed")
|
|
203
|
+
def preflight(request, forwarded)
|
|
204
|
+
return http_error(request, 403, INVALID_REQUEST, "origin not allowed") \
|
|
205
|
+
unless origin_allowed?(request, forwarded)
|
|
116
206
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
"access-control-max-age" => "600"
|
|
122
|
-
)
|
|
207
|
+
allow_headers = request.get_header("HTTP_ACCESS_CONTROL_REQUEST_HEADERS") || "content-type, accept"
|
|
208
|
+
headers = cors_headers(request).merge("access-control-allow-methods" => "POST, OPTIONS",
|
|
209
|
+
"access-control-allow-headers" => allow_headers,
|
|
210
|
+
"access-control-max-age" => "600")
|
|
123
211
|
[204, headers, []]
|
|
124
212
|
end
|
|
125
213
|
|
|
@@ -143,8 +231,13 @@ module Portage
|
|
|
143
231
|
{ jsonrpc: "2.0", id: id, error: { code: code, message: message } }
|
|
144
232
|
end
|
|
145
233
|
|
|
146
|
-
|
|
147
|
-
|
|
234
|
+
# Every rejection — CORS/method/content-type/size checks that never
|
|
235
|
+
# reach `dispatch`, same as a JSON-RPC error `dispatch` itself
|
|
236
|
+
# returns — answers with the same envelope shape, so a caller
|
|
237
|
+
# doesn't need to branch on HTTP status to read the error.
|
|
238
|
+
def http_error(request, status, code, message, extra_headers = {})
|
|
239
|
+
headers = JSON_HEADERS.merge(cors_headers(request)).merge(extra_headers)
|
|
240
|
+
[status, headers, [JSON.generate(rpc_error(nil, code, message))]]
|
|
148
241
|
end
|
|
149
242
|
end
|
|
150
243
|
end
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
require "timeout"
|
|
2
|
+
|
|
3
|
+
module Portage
|
|
4
|
+
module Ucp
|
|
5
|
+
module WebMcp
|
|
6
|
+
module Rack
|
|
7
|
+
# Bounds one CallEndpoint request: how much of its body is ever read,
|
|
8
|
+
# and how long the dispatched call is allowed to run. Split out of
|
|
9
|
+
# CallEndpoint so its own class stays about routing, CORS and
|
|
10
|
+
# JSON-RPC framing.
|
|
11
|
+
class RequestLimits
|
|
12
|
+
DEFAULT_MAX_BODY_BYTES = 1_048_576
|
|
13
|
+
DEFAULT_CALL_TIMEOUT = 30
|
|
14
|
+
|
|
15
|
+
TOO_LARGE = :too_large
|
|
16
|
+
TIMED_OUT = :timed_out
|
|
17
|
+
|
|
18
|
+
def initialize(max_body_bytes: DEFAULT_MAX_BODY_BYTES, call_timeout: DEFAULT_CALL_TIMEOUT)
|
|
19
|
+
@max_body_bytes = max_body_bytes
|
|
20
|
+
@call_timeout = call_timeout
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Fast rejection from `Content-Length`, before anything is read.
|
|
24
|
+
def body_too_large?(request)
|
|
25
|
+
length = request.content_length
|
|
26
|
+
!length.nil? && length.to_i > @max_body_bytes
|
|
27
|
+
end
|
|
28
|
+
|
|
29
|
+
# At most max_body_bytes + 1 bytes are ever read off the socket, so
|
|
30
|
+
# a request with no `Content-Length` (or one that under-reports)
|
|
31
|
+
# can't be used to buffer an unbounded body first. Returns TOO_LARGE
|
|
32
|
+
# rather than the body once it's clear the cap was exceeded.
|
|
33
|
+
def read_body(request)
|
|
34
|
+
raw = request.body.read(@max_body_bytes + 1)
|
|
35
|
+
return TOO_LARGE if raw && raw.bytesize > @max_body_bytes
|
|
36
|
+
|
|
37
|
+
raw.to_s
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# Bounds one call. `nil` call_timeout disables it (Adapter/HTTP
|
|
41
|
+
# timeouts still apply); otherwise yields TIMED_OUT past the
|
|
42
|
+
# deadline instead of raising, so the caller answers a normal
|
|
43
|
+
# JSON-RPC error rather than an uncaught Timeout::Error.
|
|
44
|
+
def call_with_timeout(&)
|
|
45
|
+
return yield unless @call_timeout
|
|
46
|
+
|
|
47
|
+
::Timeout.timeout(@call_timeout, &)
|
|
48
|
+
rescue ::Timeout::Error
|
|
49
|
+
TIMED_OUT
|
|
50
|
+
end
|
|
51
|
+
end
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
end
|
|
@@ -21,8 +21,16 @@ module Portage
|
|
|
21
21
|
# @param include_polyfill [Boolean] prepend assets/polyfill.js, so
|
|
22
22
|
# browsers without native WebMCP still get a spec-shaped
|
|
23
23
|
# `document.modelContext` for an agent-driven browser to read.
|
|
24
|
+
# @param reregister_wait_ms [Integer, nil] how long a re-registration
|
|
25
|
+
# (a Turbo/SPA reload re-running the script tag) waits for the
|
|
26
|
+
# previous generation's own in-flight registerTool calls to settle
|
|
27
|
+
# before this generation registers the same names, so the two
|
|
28
|
+
# can't race and collide. Default (registrar.js's own): 2000.
|
|
29
|
+
# rubocop:disable Metrics/ParameterLists -- one page-script config
|
|
30
|
+
# option per keyword, each independently optional; a options hash
|
|
31
|
+
# would just move the same seven names one level down.
|
|
24
32
|
def initialize(catalog:, endpoint:, credentials: "same-origin", headers: {}, exposed_to: nil,
|
|
25
|
-
include_polyfill: false)
|
|
33
|
+
include_polyfill: false, reregister_wait_ms: nil)
|
|
26
34
|
valid = CREDENTIALS.include?(credentials)
|
|
27
35
|
raise ArgumentError, "credentials must be one of #{CREDENTIALS.join(', ')}" unless valid
|
|
28
36
|
|
|
@@ -32,13 +40,16 @@ module Portage
|
|
|
32
40
|
@headers = headers
|
|
33
41
|
@exposed_to = exposed_to
|
|
34
42
|
@include_polyfill = include_polyfill
|
|
43
|
+
@reregister_wait_ms = reregister_wait_ms
|
|
35
44
|
end
|
|
45
|
+
# rubocop:enable Metrics/ParameterLists
|
|
36
46
|
|
|
37
47
|
def config
|
|
38
48
|
{
|
|
39
49
|
"endpoint" => @endpoint, "credentials" => @credentials,
|
|
40
50
|
"headers" => @headers.to_h { |k, v| [k.to_s, v.to_s] },
|
|
41
51
|
"exposedTo" => @exposed_to,
|
|
52
|
+
"reregisterWaitMs" => @reregister_wait_ms,
|
|
42
53
|
"tools" => @catalog.tools
|
|
43
54
|
}.compact
|
|
44
55
|
end
|
|
@@ -31,7 +31,11 @@ module Portage
|
|
|
31
31
|
WIRES = %i[auto flat ucp].freeze
|
|
32
32
|
# How long a call waits for a tool the page dropped mid-re-render to
|
|
33
33
|
# come back (see #execute), and how often it looks.
|
|
34
|
-
|
|
34
|
+
# Long enough for a Shopify storefront to reload after its own
|
|
35
|
+
# add_to_cart/cancel_cart: its tools answer again 1-1.5s after the
|
|
36
|
+
# mutation returns on an idle machine, up to ~3s with several
|
|
37
|
+
# browsers busy (measured live 2026-09-24), so 2s ran out first.
|
|
38
|
+
REREGISTER_WAIT = 5.0
|
|
35
39
|
REREGISTER_POLL = 0.25
|
|
36
40
|
|
|
37
41
|
attr_reader :bridge
|
|
@@ -82,15 +86,16 @@ module Portage
|
|
|
82
86
|
# the retried bridge calls count against it, and no sleep runs past
|
|
83
87
|
# it. So a miss costs at most `reregister_wait:` plus the one bridge
|
|
84
88
|
# call in flight when it expires.
|
|
89
|
+
#
|
|
90
|
+
# A tool that answers with one of PageWait::NOT_READY gets the same
|
|
91
|
+
# wait, under the same deadline: the page registers it but can't run
|
|
92
|
+
# it yet. Past the deadline that answer is reported as the page gave
|
|
93
|
+
# it.
|
|
85
94
|
def execute(action, tool_name, input)
|
|
86
|
-
|
|
87
|
-
|
|
95
|
+
wait = PageWait.new(wait: @reregister_wait, poll: REREGISTER_POLL, now: method(:monotonic_now),
|
|
96
|
+
sleep: method(:sleep))
|
|
97
|
+
wait.call(gone: -> { refresh!.then { not_found(action, [tool_name]) } }) do
|
|
88
98
|
@bridge.execute_tool(tool_name, input)
|
|
89
|
-
rescue ToolNotFoundError
|
|
90
|
-
raise(refresh!.then { not_found(action, [tool_name]) }) if monotonic_now >= deadline
|
|
91
|
-
|
|
92
|
-
sleep((deadline - monotonic_now).clamp(0, REREGISTER_POLL))
|
|
93
|
-
retry
|
|
94
99
|
end
|
|
95
100
|
end
|
|
96
101
|
|
data/lib/portage/ucp/webmcp.rb
CHANGED
|
@@ -11,6 +11,7 @@ require_relative "webmcp/rack/script_endpoint"
|
|
|
11
11
|
require_relative "webmcp/rack/app"
|
|
12
12
|
require_relative "webmcp/bridges/script_evaluator"
|
|
13
13
|
require_relative "webmcp/jsonable"
|
|
14
|
+
require_relative "webmcp/page_wait"
|
|
14
15
|
require_relative "webmcp/transport"
|
|
15
16
|
|
|
16
17
|
module Portage
|
metadata
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: portage-ucp-webmcp
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 0.1.
|
|
4
|
+
version: 0.1.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- Tom Whitbread
|
|
8
8
|
autorequire:
|
|
9
9
|
bindir: bin
|
|
10
10
|
cert_chain: []
|
|
11
|
-
date: 2026-09-
|
|
11
|
+
date: 2026-09-25 00:00:00.000000000 Z
|
|
12
12
|
dependencies:
|
|
13
13
|
- !ruby/object:Gem::Dependency
|
|
14
14
|
name: portage-ucp
|
|
@@ -16,14 +16,14 @@ dependencies:
|
|
|
16
16
|
requirements:
|
|
17
17
|
- - "~>"
|
|
18
18
|
- !ruby/object:Gem::Version
|
|
19
|
-
version: '0.
|
|
19
|
+
version: '0.10'
|
|
20
20
|
type: :runtime
|
|
21
21
|
prerelease: false
|
|
22
22
|
version_requirements: !ruby/object:Gem::Requirement
|
|
23
23
|
requirements:
|
|
24
24
|
- - "~>"
|
|
25
25
|
- !ruby/object:Gem::Version
|
|
26
|
-
version: '0.
|
|
26
|
+
version: '0.10'
|
|
27
27
|
- !ruby/object:Gem::Dependency
|
|
28
28
|
name: portage-ucp-client
|
|
29
29
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -58,6 +58,20 @@ dependencies:
|
|
|
58
58
|
- - "~>"
|
|
59
59
|
- !ruby/object:Gem::Version
|
|
60
60
|
version: '3.0'
|
|
61
|
+
- !ruby/object:Gem::Dependency
|
|
62
|
+
name: ferrum
|
|
63
|
+
requirement: !ruby/object:Gem::Requirement
|
|
64
|
+
requirements:
|
|
65
|
+
- - "~>"
|
|
66
|
+
- !ruby/object:Gem::Version
|
|
67
|
+
version: '0.15'
|
|
68
|
+
type: :development
|
|
69
|
+
prerelease: false
|
|
70
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
71
|
+
requirements:
|
|
72
|
+
- - "~>"
|
|
73
|
+
- !ruby/object:Gem::Version
|
|
74
|
+
version: '0.15'
|
|
61
75
|
- !ruby/object:Gem::Dependency
|
|
62
76
|
name: rack-test
|
|
63
77
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -114,6 +128,20 @@ dependencies:
|
|
|
114
128
|
- - "~>"
|
|
115
129
|
- !ruby/object:Gem::Version
|
|
116
130
|
version: '3.24'
|
|
131
|
+
- !ruby/object:Gem::Dependency
|
|
132
|
+
name: webrick
|
|
133
|
+
requirement: !ruby/object:Gem::Requirement
|
|
134
|
+
requirements:
|
|
135
|
+
- - "~>"
|
|
136
|
+
- !ruby/object:Gem::Version
|
|
137
|
+
version: '1.8'
|
|
138
|
+
type: :development
|
|
139
|
+
prerelease: false
|
|
140
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
141
|
+
requirements:
|
|
142
|
+
- - "~>"
|
|
143
|
+
- !ruby/object:Gem::Version
|
|
144
|
+
version: '1.8'
|
|
117
145
|
- !ruby/object:Gem::Dependency
|
|
118
146
|
name: yard
|
|
119
147
|
requirement: !ruby/object:Gem::Requirement
|
|
@@ -151,8 +179,10 @@ files:
|
|
|
151
179
|
- lib/portage/ucp/webmcp/bridges/script_evaluator.rb
|
|
152
180
|
- lib/portage/ucp/webmcp/errors.rb
|
|
153
181
|
- lib/portage/ucp/webmcp/jsonable.rb
|
|
182
|
+
- lib/portage/ucp/webmcp/page_wait.rb
|
|
154
183
|
- lib/portage/ucp/webmcp/rack/app.rb
|
|
155
184
|
- lib/portage/ucp/webmcp/rack/call_endpoint.rb
|
|
185
|
+
- lib/portage/ucp/webmcp/rack/request_limits.rb
|
|
156
186
|
- lib/portage/ucp/webmcp/rack/script_endpoint.rb
|
|
157
187
|
- lib/portage/ucp/webmcp/registrar.rb
|
|
158
188
|
- lib/portage/ucp/webmcp/tool_catalog.rb
|