Skip to content

Commit bc62edf

Browse files
timeleft--claude
andcommitted
fix(mcp): bound and narrow the first-load diagnostics
Corrects measurement defects in the first-load instrumentation and scopes it as a bounded experiment for iaser-ai#335. - Request inspection reads a tee of the request alongside the handler, up to 64 KiB actually read, so a missing or wrong Content-Length can no longer make it read or wait for the whole body. The beacon reads at most 8 KiB the same way and accepts 120 reports a minute per instance. - JSON-RPC errors are decoded from JSON and SSE bodies up to 64 KiB rather than matched by pattern. The stream outcome is `drained`, `cancelled` or `failed` on this side; it does not claim delivery to the host. - Card diagnostics run only in a diagnostic card. The early script reads an `ansari-diagnostics` head address and reports by itself at load, pagehide and timeout, so a bundle that never runs is still reported. The closed card's early script does nothing and writes no console line. - `view.prepared` records the served card's address, size, diagnostic state and connect origins; reports are logged as client-authored. - Trials record the deployment release and the first attempt and Retry as separate windows. The timeline flags mixed clients, overlapping trials and other releases as ambiguous, and words findings as observations. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 1dd3ead commit bc62edf

12 files changed

Lines changed: 429 additions & 197 deletions

‎apps/mcp/README.md‎

Lines changed: 44 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -95,53 +95,64 @@ The Worker takes the variables in the table below as Wrangler `vars` or secrets,
9595
| `MCP_ALLOWED_ORIGINS` | Comma-separated allowed browser origin hostnames. A configured list replaces defaults; an explicitly empty list permits no Origin header value. Requests without Origin remain supported. |
9696
| `MCP_RESPONSE_MODE` | `json` for modern MCP final-answer-only responses; otherwise SSE, which supports client-requested progress notifications. Older-host compatibility responses may use SSE. |
9797
| `ANSARI_RELEASE` | Optional safe release identifier, embedded in served HTML and health/log records. |
98-
| `MCP_VIEW_DIAGNOSTICS_ORIGIN` | Set only on a deployment being diagnosed: its own public origin, such as `https://ansari-mcp-development.up.railway.app`. The card may then connect to that one origin and reports its start-up milestones to `POST /diag/view`; this changes the card's bytes and so its address. Unset, the card, its address and its closed permissions are unchanged and the route does not exist. A value that is not a bare `https` origin (`http` only for localhost) stops startup. See [First-load diagnosis](#first-load-diagnosis). |
98+
| `MCP_VIEW_DIAGNOSTICS_ORIGIN` | Set only on a deployment being diagnosed: its own public origin, such as `https://ansari-mcp-development.up.railway.app`. The card may then connect to that one origin and reports its start-up milestones to `POST /diag/view`; this changes the card's bytes, address and permissions. Unset, the card, its address and its closed permissions are unchanged and the route does not exist. A value that is not a bare `https` origin (`http` only for localhost) stops startup. See [First-load diagnosis](#first-load-diagnosis). |
9999

100100
`POST /mcp` serves stateless MCP requests through Hono and the official MCP request handler. Modern requests need no initialization; older hosts can use the handler’s stateless compatibility path. No MCP session IDs, session map, expiry timer or replay store are retained. `GET /mcp` and `DELETE /mcp` return 405. `/health` exposes the release. The HTML is supplied by the hosting target (read from `dist/` at Node start, bundled into the Worker), revision-stamped and fingerprinted once before the first request is served: the release is stamped first, so equal final bytes have equal identities and a release change legitimately changes the hash. Each request creates its own lightweight MCP server using that prepared view; resource bytes and identity stay fixed until restart. No demo, font server, alternative renderer or historical resource is served. Tool calls have a fresh 60-second budget; timeout yields a safe error and leaves subsequent calls usable. The same lifetime signal aborts the upstream fetch and response-body read when the request ends or the budget expires.
101101

102102
Closing a request server releases its budget even if it was never connected to a transport. On SIGINT or SIGTERM the listener stops accepting requests, closes MCP handlers and HTTP connections, and exits; unfinished calls are interrupted, including older-host SSE calls. Fetch cancellation does not guarantee that the remote backend has stopped processing. Caller-disconnect propagation depends on the host transport; the local Workers runtime does not establish immediate upstream cancellation from a client disconnect. Actual fetch cancellation at the request deadline is covered on both hosting targets.
103103

104104
## First-load diagnosis
105105

106-
Issue #335: in Claude web and ChatGPT web the host's own error replaced the card on first load, and one Retry
107-
recovered it. The card's own failure texts never appeared, so the host gave up before the card showed anything. These
108-
records tell the possible causes apart.
109-
110-
**Server, always on.** Each `/mcp` exchange writes an `mcp.request` line when it arrives and an `mcp.response` line
111-
when it ends, joined by `rid`. The request line names the JSON-RPC method; for a card read, the address read and
112-
whether it is the one served now (`uriCurrent`); for the opening handshake, the client's name, version and protocol;
113-
for a tool call, the tool name. The response line has the HTTP status, any JSON-RPC error code (a stale card read is
114-
error `-32602` inside an HTTP 200), bytes sent, time to headers and total time, and whether the response was
115-
`complete`, `cancelled` by the client or `failed`. Handler errors are logged by name and code. No question, answer or
116-
other parameter value is logged.
117-
118-
**Card, always on.** A small script runs before the bundle and records when it started, any error, unhandled
119-
rejection or content-policy violation, and when the host's messages arrive (first message, tool input, tool result,
120-
cancellation, teardown request), by method name only. The stack's hooks add when fonts loaded, when the host context
121-
was delivered, how starting ended and when the first answer or problem was rendered. The card writes each report as an
122-
`[ansari-view]` console line in its frame. One violation is expected on every load: zod's `new Function('')`
123-
capability probe under the card's `script-src`, which it catches.
124-
125-
**Card beacon, diagnosed deployment only.** With `MCP_VIEW_DIAGNOSTICS_ORIGIN` set, the card also sends each report
126-
to `POST /diag/view` when it starts or fails, renders its first answer or problem, is put away, or has not started
127-
after 15 seconds. The server accepts only the fixed report shape (milestones, enumerated failures, error names) and
128-
logs it as `view.report`, with the host sandbox's origin name.
129-
130-
**Trials.** Run one trial per new conversation, with the deployment live for hours (`aged`) and right after a
131-
redeploy (`fresh`):
106+
A bounded experiment for issue #335, not a permanent observability design. In Claude web and ChatGPT web the host's
107+
own error replaced the card on first load and one Retry recovered it; the card's own failure texts never appeared, so
108+
the host gave up before the card showed anything. The aim is to locate the first missing step between the card read,
109+
the card's start, the host handshake, tool-result arrival and the first rendered answer, where that step can be
110+
observed at all. After the trials, this is removed or narrowed to what proved useful.
111+
112+
**Server records, always on.** Each `/mcp` exchange writes `mcp.request` and `mcp.response` lines joined by `rid`. The
113+
request is inspected from a copy, alongside the handler and up to 64 KiB actually read, so inspection never holds up
114+
or alters the exchange; a larger body is recorded as `oversize`. The request line names the JSON-RPC method; for a card
115+
read, the address read and whether it is the one this instance serves (`uriCurrent`); for the handshake, the client's
116+
name, version and protocol; for a tool call, the tool name. The response line has the HTTP status, bytes, time to
117+
headers and total time, and `stream`: whether this side's response stream was `drained`, `cancelled` or `failed`. That
118+
is not proof the host received or rendered it. Responses up to 64 KiB are decoded as JSON-RPC for an error code; a
119+
stale card read is `-32602` inside an HTTP 200. At start, `view.prepared` records the served card's address, size,
120+
whether it is a diagnostic card and its connect origins. Handler errors are logged by name and code. These records hold
121+
no question, answer or other parameter value.
122+
123+
**Card reports, diagnostic card only.** With `MCP_VIEW_DIAGNOSTICS_ORIGIN` set, the served card carries an
124+
`ansari-diagnostics` address in its head, may connect to that one origin, and changes bytes, address and permissions.
125+
Compare its trials with the closed card's rather than assuming they behave the same. An early script, which runs
126+
before the bundle is parsed, records errors, unhandled rejections, content-policy violations and when the host's
127+
messages arrive (first message, tool input, tool result, cancellation, teardown request), by method name only. The
128+
stack's hooks add font loading, host-context delivery, how starting ended and the first rendered answer or problem. The
129+
early script reports by itself at `load`, at `pagehide` and after 15 s without a start, so a bundle that never runs is
130+
still reported; the bundle adds reports when the card is ready, fails, or renders its first answer or problem. Each
131+
report is an `[ansari-view]` console line and a beacon to `POST /diag/view`. The route accepts only the fixed report
132+
shape, at most 8 KiB and 120 reports a minute per instance, and logs `view.report` with `clientAuthored: true`: the
133+
shape limits what is logged, but anyone who can reach the route can send a report. Report fields are milestones,
134+
enumerated failures and error names; the stack still prints a callback's own error to the console, as before. One
135+
violation is expected on every load: zod's `new Function('')` capability probe under the card's `script-src`, which it
136+
catches. The closed card's early script does nothing.
137+
138+
**Trials.** Use the deployment for nothing else while a trial runs. Run one trial per new conversation, with the
139+
deployment live for hours (`aged`) and right after a redeploy (`fresh`), and with the diagnostic and the closed card.
140+
The trial script records the deployment's release and the first attempt and Retry as separate windows:
132141

133142
```sh
134-
bash scripts/first-load-trial.sh claude aged
135-
bash scripts/first-load-trial.sh chatgpt fresh
136-
# Railway: deployment and edge HTTP logs for the trial window, then one timeline per trial.
143+
bash scripts/first-load-trial.sh https://ansari-mcp-development.up.railway.app claude aged diagnostic
144+
# Railway: deployment and edge HTTP logs covering the trials, then one timeline per trial.
137145
railway logs --deployment --json --since 1h > test-results/first-load/app.jsonl
138146
railway logs --http --json --since 1h > test-results/first-load/edge.jsonl
139147
node scripts/first-load-timeline.mjs test-results/first-load/trials.jsonl test-results/first-load/app.jsonl test-results/first-load/edge.jsonl
140148
```
141149

142-
The timeline flags a card read that never reached the server, a card address that is not the current deploy's, a card
143-
read that was cancelled or slow, a card whose host asked to tear it down before it was ready, a card that never heard
144-
from the host, and a slow start.
150+
Records are attributed to an attempt by time only; neither `rid` nor a card's id links to the host's attempt. The
151+
timeline lists what was observed in each window and flags windows with more than one MCP client, overlapping trials or
152+
another release as ambiguous. A finding such as "no host message observed by its last report" says only that. Two
153+
controlled cases have known answers: a stale card read (`resources/read` of an earlier address, answered `-32602`) and
154+
a bundle that fails before it runs (covered by the browser checks: a `load` report without `main` and with the
155+
`SyntaxError`).
145156

146157
## Workspace and container
147158

‎apps/mcp/scripts/first-load-timeline.mjs‎

Lines changed: 47 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@
55
// Each log file holds JSON lines in any of three forms: the application's own records (`event`, with `at`),
66
// Railway deployment logs (`railway logs --deployment --json`: `timestamp` and the record in `message`), or Railway
77
// edge HTTP logs (`railway logs --http --json`: `timestamp`, path, status, duration and bytes).
8+
//
9+
// Records are attributed to a trial by time only: neither a server `rid` nor a card id links to the host's attempt.
10+
// The timeline therefore says what was observed in each window, flags windows whose traffic may not be the trial's,
11+
// and never claims that something did not happen anywhere.
812
import {readFileSync} from 'node:fs';
913

1014
const [trialsFile, ...logFiles] = process.argv.slice(2);
@@ -15,7 +19,8 @@ if (!trialsFile || logFiles.length === 0) {
1519
const lines = file => readFileSync(file, 'utf8').split('\n').filter(line => line.trim()).flatMap(line => {
1620
try { return [JSON.parse(line)]; } catch { return []; }
1721
});
18-
const MARGIN_MS = 5_000;
22+
/** Records before the first window's start that still belong to it (discovery right before sending). */
23+
const LEAD_MS = 2_000;
1924

2025
/** One normalized entry: when, what kind, and the fields worth printing. */
2126
function normalize(raw) {
@@ -29,14 +34,15 @@ function normalize(raw) {
2934
return undefined;
3035
}
3136
const entries = logFiles.flatMap(lines).map(normalize).filter(entry => entry && typeof entry.at === 'number').sort((a, b) => a.at - b.at);
32-
const diagnosticsSeen = entries.some(entry => entry.event === 'view.report');
37+
const trials = lines(trialsFile);
3338

3439
function describe(entry, zero) {
3540
const t = `+${((entry.at - zero) / 1000).toFixed(2)}s`.padStart(9);
3641
switch (entry.event) {
3742
case 'mcp.request': return `${t} → ${entry.rpc}${entry.uri ? ` ${entry.uri}${entry.uriCurrent === false ? ' (NOT CURRENT)' : ''}` : ''}${entry.client ? ` client=${entry.client}/${entry.clientVersion}` : ''} [${entry.rid}]`;
38-
case 'mcp.response': return `${t} ← ${entry.rpc} ${entry.status} ${entry.outcome} ${entry.bytes}B headers=${entry.headersMs}ms total=${entry.ms}ms${entry.errorCode === undefined ? '' : ` error=${entry.errorCode}`} [${entry.rid}]`;
43+
case 'mcp.response': return `${t} ← ${entry.rpc} ${entry.status} stream=${entry.stream} ${entry.bytes}B headers=${entry.headersMs}ms total=${entry.ms}ms${entry.errorCode === undefined ? '' : ` error=${entry.errorCode}`} [${entry.rid}]`;
3944
case 'view.report': return `${t} ◆ card ${entry.view} ${entry.reason}${entry.failure ? ` failure=${entry.failure}` : ''} host=${entry.host ?? '?'} origin=${entry.origin} marks=${JSON.stringify(entry.marks)}${entry.errors?.length ? ` errors=${JSON.stringify(entry.errors)}` : ''}`;
45+
case 'view.prepared': return `${t} ◇ serving ${entry.uri} ${entry.bytes}B diagnostics=${entry.diagnostics}`;
4046
case 'edge': {
4147
const pick = ['method', 'path', 'httpStatus', 'totalDuration', 'responseTime', 'txBytes', 'rxBytes', 'clientUa', 'responseDetails'];
4248
return `${t} ▸ edge ${pick.map(key => entry[key] ?? entry.attributes?.[key]).filter(value => value !== undefined).join(' ')}`;
@@ -45,34 +51,58 @@ function describe(entry, zero) {
4551
}
4652
}
4753

48-
/** What the window shows, as findings tied to the hypotheses in #335. */
49-
function findings(window) {
54+
/** What one attempt's window shows. Each finding is an observation in that window, not a claim about the host. */
55+
function findings(window, card) {
5056
const out = [];
5157
const reads = window.filter(entry => entry.event === 'mcp.request' && entry.rpc === 'resources/read');
5258
const readEnds = window.filter(entry => entry.event === 'mcp.response' && entry.rpc === 'resources/read');
53-
if (reads.length === 0) out.push('no card read reached the server in this window (the host used a cached card, or never asked)');
54-
if (reads.some(entry => entry.uriCurrent === false)) out.push('a card address that is not the current deploy\'s was read (stale discovery)');
55-
for (const end of readEnds) if (end.outcome !== 'complete') out.push(`a card read was ${end.outcome} after ${end.ms}ms and ${end.bytes}B`);
59+
if (reads.length === 0) out.push('no card read was observed at the server in this window');
60+
if (reads.some(entry => entry.uriCurrent === false)) out.push('a card address that is not the one this instance serves was read');
61+
for (const end of readEnds) if (end.stream !== 'drained') out.push(`a card read stream was ${end.stream} after ${end.ms}ms and ${end.bytes}B`);
62+
for (const end of readEnds) if (end.errorCode !== undefined) out.push(`a card read answered JSON-RPC error ${end.errorCode}`);
5663
const slow = readEnds.filter(end => end.ms > 2_000);
57-
if (slow.length) out.push(`card reads slower than 2s: ${slow.map(end => `${end.ms}ms`).join(', ')}`);
64+
if (slow.length) out.push(`card read streams slower than 2s on this side: ${slow.map(end => `${end.ms}ms`).join(', ')}`);
5865
const cards = new Map();
5966
for (const entry of window.filter(item => item.event === 'view.report')) cards.set(entry.view, entry);
60-
if (diagnosticsSeen) out.push(`${cards.size} card instance(s) reported`);
67+
if (card === 'diagnostic') out.push(`${cards.size} card instance(s) reported in this window${cards.size === 0 ? ' (none observed: a card may not have run, or its report did not arrive)' : ''}`);
6168
for (const [id, last] of cards) {
6269
const m = last.marks ?? {};
63-
if (m.teardownRequested !== undefined && m.ready === undefined) out.push(`card ${id}: the host asked to tear it down before it was ready`);
70+
if (m.main === undefined) out.push(`card ${id}: the bundle had not evaluated by its last report (${last.reason})`);
71+
if (m.teardownRequested !== undefined && m.ready === undefined) out.push(`card ${id}: the host asked for teardown before the card was ready, as of its last report`);
6472
if (last.failure) out.push(`card ${id}: start failed (${last.failure})`);
6573
if (m.ready !== undefined && m.script !== undefined && m.ready - m.script > 3_000) out.push(`card ${id}: ${Math.round(m.ready - m.script)}ms from script start to ready`);
66-
if (m.hostMessage === undefined) out.push(`card ${id}: no message from the host ever arrived`);
74+
if (m.hostMessage === undefined) out.push(`card ${id}: no host message observed by its last report (${last.reason})`);
6775
}
6876
return out;
6977
}
7078

71-
for (const trial of lines(trialsFile)) {
79+
/** Signs that a window holds traffic other than this trial's, so its records cannot be attributed with confidence. */
80+
function ambiguity(window, trial) {
81+
const out = [];
82+
const clients = new Set(window.filter(entry => entry.event === 'mcp.request' && entry.client).map(entry => `${entry.client}/${entry.clientVersion}`));
83+
if (clients.size > 1) out.push(`${clients.size} different MCP clients: ${[...clients].join(', ')}`);
84+
const overlapping = trials.filter(other => other !== trial && Date.parse(other.start) < Date.parse(trial.end) && Date.parse(other.end) > Date.parse(trial.start));
85+
if (overlapping.length) out.push(`${overlapping.length} other trial(s) overlap this one`);
86+
const releases = new Set(window.filter(entry => entry.release).map(entry => entry.release));
87+
if (trial.release && trial.release !== 'unknown' && releases.size && ![...releases].every(release => release === trial.release)) out.push(`records from releases ${[...releases].join(', ')}, trial recorded ${trial.release}`);
88+
return out;
89+
}
90+
91+
for (const trial of trials) {
7292
const start = Date.parse(trial.start);
7393
const end = Date.parse(trial.end);
74-
const window = entries.filter(entry => entry.at >= start - MARGIN_MS && entry.at <= end + MARGIN_MS);
75-
console.log(`\n=== ${trial.host} / ${trial.deploy} / ${trial.label}: first=${trial.first} retry=${trial.retry} (${trial.start} → ${trial.end})`);
76-
for (const entry of window) console.log(describe(entry, start));
77-
for (const finding of findings(window)) console.log(` ! ${finding}`);
94+
const retryAt = trial.retryAt ? Date.parse(trial.retryAt) : undefined;
95+
const all = entries.filter(entry => entry.at >= start - LEAD_MS && entry.at <= end);
96+
const serving = entries.filter(entry => entry.event === 'view.prepared' && entry.at <= end).at(-1);
97+
console.log(`\n=== ${trial.host} / ${trial.deploy} / ${trial.card ?? '?'} card / ${trial.label}: first=${trial.first} retry=${trial.retry}`);
98+
console.log(` release ${trial.release ?? '?'} at ${trial.origin ?? '?'}; serving ${serving ? `${serving.uri} (${serving.bytes}B, diagnostics=${serving.diagnostics})` : 'not observed in these logs'}`);
99+
for (const warning of ambiguity(all, trial)) console.log(` ? AMBIGUOUS: ${warning}`);
100+
const attempts = [['first attempt', start - LEAD_MS, retryAt ?? end]];
101+
if (retryAt !== undefined) attempts.push(['retry', retryAt, end]);
102+
for (const [name, from, to] of attempts) {
103+
const window = entries.filter(entry => entry.at >= from && entry.at < to || (to === end && entry.at === end));
104+
console.log(` -- ${name} (${new Date(from).toISOString()} → ${new Date(to).toISOString()})`);
105+
for (const entry of window) console.log(describe(entry, start));
106+
for (const finding of findings(window, trial.card)) console.log(` ! ${finding}`);
107+
}
78108
}

0 commit comments

Comments
 (0)