forewit 0.0.0-stage → 0.0.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.
package/src/remote.mjs ADDED
@@ -0,0 +1,479 @@
1
+ // Forewit remote MCP server: read only, stateless Streamable HTTP.
2
+ // Data: the site's published JSON (snapshot plus round files, joined by the site's own data layer) and read only
3
+ // eth_call reads of the pinned ledger. Third party text (market titles, labels, tags, profile names) is only ever
4
+ // returned inside fields whose names start with "untrusted_".
5
+ import { createServer as createHttpServer } from 'node:http';
6
+ import { readFile } from 'node:fs/promises';
7
+ import { resolve, sep } from 'node:path';
8
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
9
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
10
+ import { z } from 'zod';
11
+ import { joinRounds, liveRound, phase, leaderboard, crowdVsMarket, K, MIN_ROUNDS, MIN_BASELINE_QUESTIONS, BRIER_MAX } from '../vendor/web/data.mjs';
12
+ import { cleanText } from '../vendor/web/question.mjs';
13
+ import { loadRound, ethCall, SIG, decodeReveal, phaseOf } from '../vendor/agent/forewit.mjs';
14
+ import { encodeCall, wordUint, wordAddress, decodeWords, wordToBytes32 } from '../vendor/agent/lib/keccak.mjs';
15
+ import { NETWORKS, MIN_BPS, MAX_BPS, MAX_QUESTIONS, RISK_WARNING } from '../vendor/agent/config.mjs';
16
+ import { ok, guarded, paginate, cursorInput, address, roundId, VERSION } from './common.mjs';
17
+
18
+ const SCORING = JSON.parse(await readFile(new URL('../vendor/scoring.json', import.meta.url), 'utf8'));
19
+ export const DEFAULT_DATA = 'https://forewit.xyz/data/';
20
+ const DATA_TTL_MS = 60_000;
21
+ const CHAIN_TTL_MS = 30_000;
22
+ const MAX_JSON = 4 << 20;
23
+ const STATUS = { revealed: 1, scored: 2, forfeited: 4 };
24
+ const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
25
+
26
+ // Data loading
27
+
28
+ async function readJson(base, path) {
29
+ if (!/^[a-z0-9_/]+\.json$/i.test(path) || path.includes('//')) throw new Error('published data lists an unexpected file path');
30
+ let text;
31
+ if (/^https:\/\//i.test(base)) {
32
+ const res = await fetch(new URL(path, base), { signal: AbortSignal.timeout(10_000), redirect: 'error' });
33
+ if (!res.ok) throw new Error(`published data ${path}: HTTP ${res.status}`);
34
+ text = await res.text();
35
+ } else {
36
+ const file = resolve(base, path);
37
+ if (!file.startsWith(resolve(base) + sep)) throw new Error('published data path escapes the data folder');
38
+ text = await readFile(file, 'utf8');
39
+ }
40
+ if (text.length > MAX_JSON) throw new Error(`published data ${path} is too large`);
41
+ return JSON.parse(text);
42
+ }
43
+
44
+ /** The pinned network whose chain id and ledger match the published snapshot; refuses anything else. */
45
+ export function pinnedNetwork(snapshot) {
46
+ const net = Object.values(NETWORKS).find((n) => n.chainId === Number(snapshot?.network) && n.ledger &&
47
+ n.ledger.toLowerCase() === String(snapshot?.ledger).toLowerCase());
48
+ if (!net) throw new Error('published data does not match a pinned Forewit ledger; refusing to serve it');
49
+ return net;
50
+ }
51
+
52
+ const dataCache = new Map();
53
+ export function loadDataset(base) {
54
+ const hit = dataCache.get(base);
55
+ if (hit && Date.now() - hit.at < DATA_TTL_MS) return hit.promise;
56
+ const promise = (async () => {
57
+ const manifest = await readJson(base, 'index.json');
58
+ const snapshot = await readJson(base, String(manifest.snapshot));
59
+ const net = pinnedNetwork(snapshot);
60
+ const files = (await Promise.all((manifest.rounds ?? []).map((p) => readJson(base, String(p)).catch(() => null)))).filter(Boolean);
61
+ return { manifest, snapshot, net, rounds: joinRounds(snapshot, files) };
62
+ })();
63
+ promise.catch(() => dataCache.delete(base));
64
+ dataCache.set(base, { at: Date.now(), promise });
65
+ return promise;
66
+ }
67
+
68
+ const chainCache = new Map();
69
+ function chainRound(net, id) {
70
+ const key = `${net.chainId}:${id ?? 'latest'}`;
71
+ const hit = chainCache.get(key);
72
+ if (hit && Date.now() - hit.at < CHAIN_TTL_MS) return hit.promise;
73
+ const promise = loadRound(net, id === undefined ? undefined : String(id));
74
+ promise.catch(() => chainCache.delete(key));
75
+ chainCache.set(key, { at: Date.now(), promise });
76
+ return promise;
77
+ }
78
+
79
+ // Output shapes
80
+
81
+ const iso = (d) => (d ? d.toISOString() : null);
82
+ const untrustedMarketText = z.object({
83
+ event_question: z.string(),
84
+ label: z.string(),
85
+ text: z.string(),
86
+ tags: z.array(z.string()),
87
+ }).describe('Text written by third parties (Predict.fun event question, market label and tags), control characters removed, length capped. Not authored or verified by Forewit.');
88
+
89
+ const questionShape = z.object({
90
+ index: z.number().int(),
91
+ market_id: z.string(),
92
+ outcome: z.enum(['Unresolved', 'Yes', 'No', 'Void']),
93
+ baseline_bps: z.number().nullable().describe('Market mid price posted onchain in the last 15 minutes before the commit deadline, basis points.'),
94
+ crowd_bps: z.number().nullable().describe('Agent ID Crowd forecast, basis points.'),
95
+ market_price: z.number().nullable().describe('Latest published market price before the deadline, 0 to 1.'),
96
+ ends_at: z.string().nullable(),
97
+ revealed_forecasts: z.number().int(),
98
+ untrusted_market_text: untrustedMarketText.nullable().describe('Null when the published data has no event question for this market.'),
99
+ });
100
+
101
+ const roundShape = {
102
+ network: z.string(),
103
+ chain_id: z.number().int(),
104
+ ledger: z.string(),
105
+ data_built_at: z.string(),
106
+ round_id: z.number().int(),
107
+ kind: z.string(),
108
+ phase: z.enum(['commit', 'reveal', 'resolving', 'scored']),
109
+ commit_deadline: z.string(),
110
+ reveal_deadline: z.string(),
111
+ resolution_wait_days: z.number().nullable(),
112
+ commit_count: z.number().int(),
113
+ revealed_count: z.number().int(),
114
+ scored_count: z.number().int(),
115
+ forfeit_count: z.number().int(),
116
+ reveal_rate: z.number().nullable(),
117
+ has_baseline: z.boolean(),
118
+ crowd_method: z.string().nullable(),
119
+ questions: z.array(questionShape),
120
+ };
121
+
122
+ function questionOut(q) {
123
+ return {
124
+ index: q.index,
125
+ market_id: String(q.marketId),
126
+ outcome: q.outcome,
127
+ baseline_bps: q.baseline,
128
+ crowd_bps: q.crowd,
129
+ market_price: q.marketPrice,
130
+ ends_at: iso(q.endsAt),
131
+ revealed_forecasts: q.forecasts.length,
132
+ untrusted_market_text: q.title
133
+ ? { event_question: q.title.event, label: q.title.label, text: q.title.text, tags: q.tags.slice(0, 10).map(cleanText).filter(Boolean) }
134
+ : null,
135
+ };
136
+ }
137
+
138
+ function roundOut(ds, r) {
139
+ return {
140
+ network: ds.net.name,
141
+ chain_id: ds.net.chainId,
142
+ ledger: ds.net.ledger,
143
+ data_built_at: String(ds.snapshot.builtAt),
144
+ round_id: r.id,
145
+ kind: cleanText(r.kind),
146
+ phase: phase(r, Date.now()),
147
+ commit_deadline: iso(r.commitDeadline),
148
+ reveal_deadline: iso(r.revealDeadline),
149
+ resolution_wait_days: r.resolutionWaitDays,
150
+ commit_count: r.commitCount,
151
+ revealed_count: r.revealedCount,
152
+ scored_count: r.scoredCount,
153
+ forfeit_count: r.forfeitCount,
154
+ reveal_rate: r.revealRate,
155
+ has_baseline: r.hasBaseline,
156
+ crowd_method: r.crowdMethod,
157
+ questions: r.questions.map(questionOut),
158
+ };
159
+ }
160
+
161
+ const findRound = (ds, id) => {
162
+ const r = ds.rounds.find((x) => x.id === id);
163
+ if (!r) throw new Error(`round ${id} is not in the published data (latest published round: ${ds.rounds[0]?.id ?? 'none'})`);
164
+ return r;
165
+ };
166
+
167
+ // Leaderboard: opt in public profiles only, operator wallets never listed.
168
+ function publicRows(snapshot) {
169
+ const ops = new Set((snapshot.operators ?? []).map((a) => String(a).toLowerCase()));
170
+ const lb = leaderboard(snapshot);
171
+ const rows = lb.rows.filter((r) => !ops.has(r.addr));
172
+ let rank = 0;
173
+ return {
174
+ forecasters: lb.forecasters,
175
+ rows: rows.map((r) => ({
176
+ rank: r.ranked ? ++rank : null,
177
+ address: r.addr,
178
+ ranked: r.ranked,
179
+ rounds: r.rounds,
180
+ rounds_committed: r.roundsCommitted,
181
+ rounds_revealed: r.roundsRevealed,
182
+ questions: r.questions,
183
+ baseline_questions: r.baselineQuestions,
184
+ mean_brier: r.meanBrier,
185
+ shrunk_skill: r.shrunkSkill,
186
+ participation: r.participation,
187
+ calibration_error: r.calibrationError,
188
+ post_baseline_flag: r.postBaselineFlag,
189
+ untrusted_profile_name: r.name == null ? null : cleanText(r.name) || null,
190
+ })),
191
+ };
192
+ }
193
+
194
+ const rowShape = z.object({
195
+ rank: z.number().int().nullable(),
196
+ address: z.string(),
197
+ ranked: z.boolean(),
198
+ rounds: z.number().int(),
199
+ rounds_committed: z.number().int(),
200
+ rounds_revealed: z.number().int(),
201
+ questions: z.number().int(),
202
+ baseline_questions: z.number().int(),
203
+ mean_brier: z.number().nullable(),
204
+ shrunk_skill: z.number(),
205
+ participation: z.number().nullable(),
206
+ calibration_error: z.number().nullable(),
207
+ post_baseline_flag: z.boolean(),
208
+ untrusted_profile_name: z.string().nullable().describe('Agent ID name the forecaster chose for the public profile; third party text.'),
209
+ });
210
+
211
+ function flattenBlocks(blocks) {
212
+ return blocks.flatMap((b) => (typeof b === 'string' ? [b] : b.h ? [b.h] : b.strong ? [b.strong] : b.list ?? b.ol ?? []));
213
+ }
214
+
215
+ /** One McpServer with the eight read only tools. `data` is an https base URL or a local folder of published JSON. */
216
+ export function createRemoteServer({ data = process.env.FOREWIT_DATA || DEFAULT_DATA } = {}) {
217
+ const server = new McpServer({ name: 'forewit', version: VERSION, title: 'Forewit (read only)' });
218
+ const tool = (name, config, fn) =>
219
+ server.registerTool(name, { ...config, inputSchema: z.object(config.inputSchema ?? {}).strict(), outputSchema: z.object(config.outputSchema), annotations: { ...READ_ONLY, title: config.title } }, guarded(fn));
220
+ const ds = () => loadDataset(data);
221
+
222
+ tool('get_current_round', {
223
+ title: 'Current round',
224
+ description: 'The featured Forewit round: the one open for commits with the nearest deadline, else the one in its reveal window, else the newest. Includes every question with its baseline, crowd and outcome.',
225
+ outputSchema: roundShape,
226
+ }, async () => {
227
+ const d = await ds();
228
+ const r = liveRound(d.rounds, Date.now());
229
+ if (!r) throw new Error('no rounds are published yet');
230
+ return ok(roundOut(d, r));
231
+ });
232
+
233
+ tool('get_round', {
234
+ title: 'Round by id',
235
+ description: 'One Forewit round by id, with deadlines, counts and every question.',
236
+ inputSchema: { round_id: roundId },
237
+ outputSchema: roundShape,
238
+ }, async ({ round_id }) => {
239
+ const d = await ds();
240
+ return ok(roundOut(d, findRound(d, round_id)));
241
+ });
242
+
243
+ tool('get_question', {
244
+ title: 'Question',
245
+ description: 'One question of a round: the parent event question and market label, baseline, crowd, market price and outcome. Fails when the published data has no event question for it.',
246
+ inputSchema: { round_id: roundId, index: z.number().int().min(0).max(MAX_QUESTIONS - 1) },
247
+ outputSchema: { round_id: z.number().int(), ...questionShape.shape, untrusted_market_text: untrustedMarketText },
248
+ }, async ({ round_id, index }) => {
249
+ const d = await ds();
250
+ const q = findRound(d, round_id).questions[index];
251
+ if (!q) throw new Error(`round ${round_id} has no question ${index}`);
252
+ if (!q.title) throw new Error(`round ${round_id} question ${index} has no event question in the published data, so it is not presented`);
253
+ return ok({ round_id, ...questionOut(q) });
254
+ });
255
+
256
+ tool('get_baseline', {
257
+ title: 'Baseline',
258
+ description: 'The market baseline of a round read from the ledger contract (eth_call), with a check against the published data.',
259
+ inputSchema: { round_id: roundId },
260
+ outputSchema: {
261
+ network: z.string(), ledger: z.string(), round_id: z.number().int(), source: z.literal('chain'),
262
+ baseline_set: z.boolean(), baseline_bps: z.array(z.number().int()).nullable(),
263
+ published_data_agrees: z.boolean().nullable().describe('Null when the round is not in the published data yet.'),
264
+ },
265
+ }, async ({ round_id }) => {
266
+ const d = await ds();
267
+ const { round } = await chainRound(d.net, round_id);
268
+ const n = round.questionCount;
269
+ const bps = round.baselineSet ? Array.from({ length: n }, (_, i) => Number((round.baselinePacked >> BigInt(16 * i)) & 0xffffn)) : null;
270
+ const pub = d.rounds.find((r) => r.id === round_id);
271
+ const pubBps = pub ? (pub.hasBaseline ? pub.questions.map((q) => q.baseline) : null) : undefined;
272
+ return ok({
273
+ network: d.net.name, ledger: d.net.ledger, round_id, source: 'chain', baseline_set: round.baselineSet, baseline_bps: bps,
274
+ published_data_agrees: pubBps === undefined ? null : JSON.stringify(pubBps) === JSON.stringify(bps),
275
+ });
276
+ });
277
+
278
+ tool('get_crowd', {
279
+ title: 'Agent ID Crowd versus market',
280
+ description: 'Brier score of the Agent ID Crowd against the market baseline on resolved questions, overall and per round (newest first, paginated).',
281
+ inputSchema: cursorInput,
282
+ outputSchema: {
283
+ overall: z.object({ crowd_brier: z.number().nullable(), market_brier: z.number().nullable(), questions: z.number().int() }),
284
+ rounds: z.array(z.object({ round_id: z.number().int(), crowd_method: z.string().nullable(), crowd_bps: z.array(z.number().nullable()), crowd_brier: z.number().nullable(), market_brier: z.number().nullable(), questions: z.number().int() })),
285
+ next_cursor: z.string().nullable(),
286
+ },
287
+ }, async (args) => {
288
+ const d = await ds();
289
+ const all = crowdVsMarket(d.rounds);
290
+ const { page, next_cursor } = paginate(d.rounds, args);
291
+ return ok({
292
+ overall: { crowd_brier: all.crowd, market_brier: all.market, questions: all.n },
293
+ rounds: page.map((r) => {
294
+ const c = crowdVsMarket([r]);
295
+ return { round_id: r.id, crowd_method: r.crowdMethod, crowd_bps: r.questions.map((q) => q.crowd), crowd_brier: c.crowd, market_brier: c.market, questions: c.n };
296
+ }),
297
+ next_cursor,
298
+ });
299
+ });
300
+
301
+ tool('get_leaderboard', {
302
+ title: 'Leaderboard',
303
+ description: 'Forecasters who opted in to a public profile, ranked by shrunk skill against the market. Operator wallets are never listed. Paginated.',
304
+ inputSchema: cursorInput,
305
+ outputSchema: {
306
+ forecasters: z.number().int().describe('All forecasters with any activity, public or not.'),
307
+ public_count: z.number().int(),
308
+ rows: z.array(rowShape),
309
+ next_cursor: z.string().nullable(),
310
+ },
311
+ }, async (args) => {
312
+ const d = await ds();
313
+ const { forecasters, rows } = publicRows(d.snapshot);
314
+ const { page, next_cursor } = paginate(rows, args);
315
+ return ok({ forecasters, public_count: rows.length, rows: page, next_cursor });
316
+ });
317
+
318
+ tool('get_my_status', {
319
+ title: 'Status of a wallet',
320
+ description: 'For one wallet address: commit and reveal status in the latest round read from the ledger, per round history from the published data (newest first, paginated), and the leaderboard row when the profile is public.',
321
+ inputSchema: { address, ...cursorInput },
322
+ outputSchema: {
323
+ address: z.string(),
324
+ current: z.object({
325
+ round_id: z.number().int(), phase: z.enum(['commit open', 'reveal open', 'closed']),
326
+ committed: z.boolean(), commit_hash: z.string().nullable(), revealed: z.boolean(), scored: z.boolean(), forfeited: z.boolean(),
327
+ }),
328
+ history: z.array(z.object({
329
+ round_id: z.number().int(), committed: z.boolean(), revealed: z.boolean(), result: z.enum(['scored', 'forfeited', 'pending']),
330
+ questions: z.number().int().nullable(), brier: z.number().nullable(), skill: z.number().nullable(),
331
+ })),
332
+ leaderboard: rowShape.nullable(),
333
+ next_cursor: z.string().nullable(),
334
+ },
335
+ }, async ({ address: addr, ...page }) => {
336
+ const d = await ds();
337
+ const a = addr.toLowerCase();
338
+ const { id, now, round } = await chainRound(d.net);
339
+ const [c] = decodeWords(await ethCall(d.net, encodeCall(SIG.getCommit, [wordUint(id), wordAddress(addr)])));
340
+ const { status } = decodeReveal(await ethCall(d.net, encodeCall(SIG.getReveal, [wordUint(id), wordAddress(addr)])));
341
+ const mine = d.snapshot.rounds
342
+ .filter((r) => r.committers.some((x) => x.toLowerCase() === a))
343
+ .sort((x, y) => Number(y.roundId) - Number(x.roundId))
344
+ .map((r) => {
345
+ const s = Object.entries(r.scored).find(([k]) => k.toLowerCase() === a)?.[1];
346
+ const f = Object.entries(r.forfeited).find(([k]) => k.toLowerCase() === a)?.[1];
347
+ const sums = s ?? f;
348
+ return {
349
+ round_id: Number(r.roundId),
350
+ committed: true,
351
+ revealed: r.revealed.some((x) => x.toLowerCase() === a),
352
+ result: s ? 'scored' : f ? 'forfeited' : 'pending',
353
+ questions: sums ? Number(sums.questions) : null,
354
+ brier: sums ? Number(sums.brier) / Number(sums.questions || 1) / BRIER_MAX : null,
355
+ skill: sums ? Number(sums.skill) / Number(sums.questions || 1) / BRIER_MAX : null,
356
+ };
357
+ });
358
+ const { page: history, next_cursor } = paginate(mine, page);
359
+ return ok({
360
+ address: a,
361
+ current: {
362
+ round_id: id, phase: phaseOf(round, now), committed: c !== 0n, commit_hash: c === 0n ? null : wordToBytes32(c),
363
+ revealed: !!(status & STATUS.revealed), scored: !!(status & STATUS.scored), forfeited: !!(status & STATUS.forfeited),
364
+ },
365
+ history,
366
+ leaderboard: publicRows(d.snapshot).rows.find((r) => r.address === a) ?? null,
367
+ next_cursor,
368
+ });
369
+ });
370
+
371
+ tool('explain_scoring', {
372
+ title: 'Scoring rules',
373
+ description: 'How Forewit scores forecasts (Brier, baseline, skill, forfeits, leaderboard rank) and the constants used, in English or Simplified Chinese.',
374
+ inputSchema: { lang: z.enum(['en', 'zh']).optional().describe('Language, default en.') },
375
+ outputSchema: {
376
+ lang: z.enum(['en', 'zh']),
377
+ title: z.string(),
378
+ rules: z.array(z.string()),
379
+ constants: z.object({
380
+ brier_max: z.number(), shrink_k: z.number(), min_rounds_ranked: z.number(), min_baseline_questions_ranked: z.number(),
381
+ min_bps: z.number(), max_bps: z.number(), max_questions: z.number(),
382
+ }),
383
+ risk_warning: z.string(),
384
+ },
385
+ }, async ({ lang = 'en' }) => ok({
386
+ lang,
387
+ title: SCORING[lang].title,
388
+ rules: flattenBlocks(SCORING[lang].blocks),
389
+ constants: { brier_max: BRIER_MAX, shrink_k: K, min_rounds_ranked: MIN_ROUNDS, min_baseline_questions_ranked: MIN_BASELINE_QUESTIONS, min_bps: MIN_BPS, max_bps: MAX_BPS, max_questions: MAX_QUESTIONS },
390
+ risk_warning: RISK_WARNING,
391
+ }));
392
+
393
+ return server;
394
+ }
395
+
396
+ // HTTP
397
+
398
+ const DEFAULT_ORIGINS = ['https://forewit.xyz', 'https://www.forewit.xyz'];
399
+
400
+ /**
401
+ * Starts the stateless Streamable HTTP endpoint at POST /mcp. One McpServer and transport per request.
402
+ * Origin: requests without an Origin header (non browser clients) pass; any Origin must be on the allowlist.
403
+ */
404
+ export function startHttp({
405
+ port = Number(process.env.PORT) || 8787,
406
+ host = process.env.HOST || '127.0.0.1',
407
+ allowedOrigins = process.env.FOREWIT_ALLOWED_ORIGINS ? process.env.FOREWIT_ALLOWED_ORIGINS.split(',').map((s) => s.trim()).filter(Boolean) : DEFAULT_ORIGINS,
408
+ rateLimit = Number(process.env.FOREWIT_RATE_LIMIT) || 60,
409
+ windowMs = 60_000,
410
+ maxBody = 64 * 1024,
411
+ data,
412
+ } = {}) {
413
+ const origins = new Set(allowedOrigins);
414
+ // shortcut: in memory fixed window per socket address; behind a proxy every client shares one address, move limits to the proxy then.
415
+ const hits = new Map();
416
+ const limited = (ip) => {
417
+ const now = Date.now();
418
+ if (hits.size > 10_000) hits.clear();
419
+ const h = hits.get(ip);
420
+ if (!h || now - h.start >= windowMs) { hits.set(ip, { start: now, n: 1 }); return false; }
421
+ return ++h.n > rateLimit;
422
+ };
423
+ const reject = (res, code, message) => {
424
+ if (!res.headersSent) res.writeHead(code, { 'content-type': 'application/json', 'cache-control': 'no-store' });
425
+ res.end(JSON.stringify({ jsonrpc: '2.0', error: { code: -32000, message }, id: null }));
426
+ };
427
+
428
+ const http = createHttpServer(async (req, res) => {
429
+ try {
430
+ const path = new URL(req.url ?? '/', 'http://localhost').pathname;
431
+ if (path !== '/mcp') return reject(res, 404, 'not found; the endpoint is POST /mcp');
432
+ const origin = req.headers.origin;
433
+ if (origin !== undefined && !origins.has(origin)) return reject(res, 403, 'origin not allowed');
434
+ if (origin) {
435
+ res.setHeader('access-control-allow-origin', origin);
436
+ res.setHeader('vary', 'Origin');
437
+ }
438
+ if (req.method === 'OPTIONS') {
439
+ res.writeHead(204, { 'access-control-allow-methods': 'POST', 'access-control-allow-headers': 'content-type, accept, mcp-protocol-version', 'access-control-max-age': '600' });
440
+ return res.end();
441
+ }
442
+ if (limited(req.socket.remoteAddress ?? 'unknown')) {
443
+ res.setHeader('retry-after', String(Math.ceil(windowMs / 1000)));
444
+ return reject(res, 429, 'rate limit exceeded');
445
+ }
446
+ if (req.method !== 'POST') {
447
+ res.setHeader('allow', 'POST, OPTIONS');
448
+ return reject(res, 405, 'method not allowed; this server is stateless and accepts POST only');
449
+ }
450
+ if (Number(req.headers['content-length'] ?? 0) > maxBody) return reject(res, 413, 'request body too large');
451
+ const chunks = [];
452
+ let size = 0;
453
+ for await (const chunk of req) {
454
+ size += chunk.length;
455
+ if (size > maxBody) return reject(res, 413, 'request body too large');
456
+ chunks.push(chunk);
457
+ }
458
+ let body;
459
+ try {
460
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
461
+ } catch {
462
+ return reject(res, 400, 'parse error: body is not JSON');
463
+ }
464
+ const mcp = createRemoteServer({ data });
465
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
466
+ res.on('close', () => { transport.close(); mcp.close(); });
467
+ res.setHeader('cache-control', 'no-store');
468
+ await mcp.connect(transport);
469
+ await transport.handleRequest(req, res, body);
470
+ } catch (err) {
471
+ console.error('forewit mcp remote:', err instanceof Error ? err.message : err);
472
+ reject(res, 500, 'internal error');
473
+ }
474
+ });
475
+ return new Promise((ok, no) => {
476
+ http.once('error', no);
477
+ http.listen(port, host, () => ok(http));
478
+ });
479
+ }
@@ -0,0 +1,33 @@
1
+ // Pinned network constants. The CLI only ever builds calls to these ledger addresses; there is no override flag.
2
+ // Mainnet ledger is null until it is deployed and verified; while it is null the CLI refuses mainnet writes.
3
+
4
+ export const NETWORKS = Object.freeze({
5
+ mainnet: Object.freeze({
6
+ name: 'mainnet',
7
+ chainId: 56,
8
+ ledger: null,
9
+ rpc: 'https://bsc-rpc.publicnode.com',
10
+ explorer: 'https://bscscan.com',
11
+ }),
12
+ testnet: Object.freeze({
13
+ name: 'testnet',
14
+ chainId: 97,
15
+ ledger: '0xa4975e89d4Eb797AcC151D05634E2f7c58Ac12E1', // instance E (Forewit build); A to D are deprecated,
16
+ rpc: 'https://bsc-testnet-rpc.publicnode.com',
17
+ explorer: 'https://testnet.bscscan.com',
18
+ }),
19
+ });
20
+
21
+ // Mainnet becomes the default automatically once its ledger address is pinned above.
22
+ export const DEFAULT_NETWORK = NETWORKS.mainnet.ledger ? 'mainnet' : 'testnet';
23
+
24
+ // The Binance Agentic Wallet (baw) signs on BSC mainnet only.
25
+ export const BAW_CHAIN_IDS = Object.freeze([56]);
26
+
27
+ export const MIN_BPS = 100; // 1%
28
+ export const MAX_BPS = 9900; // 99%
29
+ export const MAX_QUESTIONS = 16;
30
+
31
+ // Spec 7.3, verbatim.
32
+ export const RISK_WARNING =
33
+ 'Forecasting scores only. Not financial advice. Forewit does not take bets, hold funds or pay returns. Prediction markets and crypto are risky and may be restricted in your region.';