forewit 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +90 -2
- package/bin/forewit.mjs +24 -0
- package/package.json +36 -4
- package/src/common.mjs +39 -0
- package/src/local.mjs +204 -0
- package/src/remote.mjs +479 -0
- package/vendor/agent/config.mjs +34 -0
- package/vendor/agent/forewit.mjs +849 -0
- package/vendor/agent/lib/baw.mjs +175 -0
- package/vendor/agent/lib/keccak.mjs +120 -0
- package/vendor/agent/lib/question.mjs +25 -0
- package/vendor/agent/lib/secure_file.mjs +93 -0
- package/vendor/scoring.json +54 -0
- package/vendor/web/data.mjs +278 -0
- package/vendor/web/question.mjs +25 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Forewit contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,91 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Forewit MCP servers
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
0.1.0: BSC mainnet (ForecastLedger 0xd11e67ff70ACD42E01d79130f280162b00Bb09B6) by default, testnet with network testnet. Published from GitHub Actions with npm provenance.
|
|
4
|
+
|
|
5
|
+
Two Model Context Protocol servers for Forewit, the commit and reveal forecasting ledger for Agent ID holders on BNB Smart Chain. One npm package, `forewit`, with one bin:
|
|
6
|
+
|
|
7
|
+
* `forewit mcp`: local server over stdio. Prepares commit, reveal and profile transactions. Never signs, never sends, never runs baw.
|
|
8
|
+
* `forewit mcp remote`: read only server over stateless Streamable HTTP, for hosting at `https://mcp.forewit.xyz/mcp`.
|
|
9
|
+
* `forewit <round|forecast|commit|reveal|status|receipt|agent|schedule>`: the Forewit CLI (same code as `agent/forewit.mjs`).
|
|
10
|
+
|
|
11
|
+
Status: built and tested, not published to npm, not listed in the MCP Registry, not hosted. Mainnet is not deployed, so both servers target the BSC testnet ledger pinned in `agent/config.mjs` until the mainnet address is pinned there.
|
|
12
|
+
|
|
13
|
+
## Protocol and SDK
|
|
14
|
+
|
|
15
|
+
Supports MCP protocol 2025-11-25. Support for 2026-07-28 will come when the official MCP SDK adds it.
|
|
16
|
+
|
|
17
|
+
* SDK: `@modelcontextprotocol/sdk` 1.32.2 (latest on npm, 24 Nov 2026) with zod 4.6.7.
|
|
18
|
+
* Protocol: 2025-11-25. Neither `@modelcontextprotocol/sdk` 1.32.2 nor the split `@modelcontextprotocol/server` 2.4.0 negotiates revision 2026-07-28 yet (both list 2025-11-25 as their latest; a 2026-07-28 `initialize` is answered with 2025-11-25, which a 2026-07-28 client accepts or declines per the spec). Checked by sending `initialize` to both; the remote test asserts this fallback, so an SDK upgrade that adds 2026-07-28 shows up as a test change.
|
|
19
|
+
* Capabilities: tools only. No resources, prompts, logging, sampling, roots or elicitation.
|
|
20
|
+
|
|
21
|
+
## Remote server (read only)
|
|
22
|
+
|
|
23
|
+
Tools, all `readOnlyHint: true`, each with a strict input schema (`additionalProperties: false`) and an `outputSchema` with `structuredContent`:
|
|
24
|
+
|
|
25
|
+
* `get_current_round`: the featured round (open for commits with the nearest deadline, else in its reveal window, else the newest), with every question.
|
|
26
|
+
* `get_round {round_id}`
|
|
27
|
+
* `get_question {round_id, index}`: always includes the parent event question; a market with no event question is refused, never shown as a bare label.
|
|
28
|
+
* `get_baseline {round_id}`: read from the ledger by `eth_call`, compared with the published data.
|
|
29
|
+
* `get_crowd {cursor?, limit?}`: Agent ID Crowd versus market Brier, overall and per round.
|
|
30
|
+
* `get_leaderboard {cursor?, limit?}`: opt in public profiles only; operator wallets are filtered out even when public.
|
|
31
|
+
* `get_my_status {address, cursor?, limit?}`: latest round status from the ledger, history from the published data, the leaderboard row when public.
|
|
32
|
+
* `explain_scoring {lang?}`: the scoring page of the site (`en` or `zh`) plus the constants from the site's data layer and `agent/config.mjs`.
|
|
33
|
+
|
|
34
|
+
Data sources:
|
|
35
|
+
|
|
36
|
+
* The published site data (`index.json`, `snapshot.json`, `rounds/*.json`), joined by the site's own `web/src/lib/data.ts` (types stripped into `vendor/` at build time, so the numbers match the site). `FOREWIT_DATA` sets an https base URL or a local folder; default `https://forewit.xyz/data/`. Cached 60 s.
|
|
37
|
+
* Read only `eth_call` to the RPC pinned in `agent/config.mjs`. The snapshot's chain id and ledger must match a pinned network or nothing is served. Chain reads cached 30 s per round.
|
|
38
|
+
|
|
39
|
+
Untrusted text: market titles, labels and tags come back only inside `untrusted_market_text`, profile names only inside `untrusted_profile_name`. Control and bidi characters are stripped and length is capped (`agent/lib/question.mjs`). Error messages never echo market text.
|
|
40
|
+
|
|
41
|
+
HTTP hardening:
|
|
42
|
+
|
|
43
|
+
* `POST /mcp` only (stateless, JSON responses, one server and transport per request); other methods 405, other paths 404.
|
|
44
|
+
* Origin allowlist (`FOREWIT_ALLOWED_ORIGINS`, comma separated, default `https://forewit.xyz,https://www.forewit.xyz`). Requests without an Origin header (non browser clients) pass; any other Origin gets 403.
|
|
45
|
+
* Request body limit 64 KB (413). Rate limit per client address, default 60 requests per minute (`FOREWIT_RATE_LIMIT`, 429). Behind a reverse proxy all clients share one socket address, so the default becomes a global cap: raise `FOREWIT_RATE_LIMIT` there and enforce the per client limit at the proxy.
|
|
46
|
+
* No secrets: nothing to configure besides `PORT`, `HOST` (default 127.0.0.1), `FOREWIT_DATA`, `FOREWIT_ALLOWED_ORIGINS`, `FOREWIT_RATE_LIMIT`.
|
|
47
|
+
|
|
48
|
+
## Local server (stdio)
|
|
49
|
+
|
|
50
|
+
Run with `npx forewit mcp` (after publish) or `node mcp/bin/forewit.mjs mcp` from this repo. Client config:
|
|
51
|
+
|
|
52
|
+
```json
|
|
53
|
+
{ "mcpServers": { "forewit": { "command": "npx", "args": ["forewit", "mcp"] } } }
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Tools:
|
|
57
|
+
|
|
58
|
+
* `prepare_commit {from, probabilities_percent, round_id?, network?}`: reads the round from the ledger, refuses after the commit deadline or on a wrong question count, makes a 32 byte salt with `crypto.randomBytes`, checks the hash encoding against the ledger's `computeCommitHash` with a throwaway salt, saves the receipt to `~/.forewit/` with owner only permissions (`agent/lib/secure_file.mjs`, icacls on Windows), then returns the commit hash, calldata, `{to, value: "0", data}` and the exact `baw contract-call preview` command. The salt is not returned (`salt_returned: false`).
|
|
59
|
+
* `prepare_reveal {from, round_id?, network?}`: refused before the commit deadline (chain time). After it, finds the receipt matching the onchain commit and returns the reveal calldata. That calldata contains the salt by construction; it is returned only when the salt is about to be public onchain anyway.
|
|
60
|
+
* `prepare_profile {from, is_public, label?, network?}`: `setPublicProfile(bool,string)` calldata, checked against viem in the tests. Opting out always clears the name.
|
|
61
|
+
* `my_receipts {from?, round_id?, network?, include_salt?, cursor?, limit?}`: receipt metadata and file paths. Salts only with `include_salt: true`, for a private backup the user asked for, and only once every listed round is past its commit deadline (chain time on the receipt's pinned network); otherwise the call is a tool error. Files in `~/.forewit` that are not valid receipts are skipped and listed in `warnings` (file and reason), never failing the whole call.
|
|
62
|
+
|
|
63
|
+
Decision on salts: salts never enter agent context before the commit deadline. Before it, the salt plus forecast would let anyone reveal or copy the forecast, so it stays on disk; `prepare_reveal` and `my_receipts include_salt` are both refused until then. After the deadline the model sees a salt only in reveal calldata or when the user asks `my_receipts` for a backup.
|
|
64
|
+
|
|
65
|
+
Guarantees: no tool signs, sends or runs baw (a test runs the stdio server with a fake baw that leaves a marker file and asserts it never ran). stdout carries JSON RPC only; logs go to stderr (`console.log` is redirected). Network access is the pinned RPC only. A `home` folder is not a tool input, and neither are round file URLs.
|
|
66
|
+
|
|
67
|
+
`baw_can_sign_this_network` is false on testnet: baw signs on BSC mainnet (chain 56) only, so on testnet the preview command shows the format and the transaction object is what you send from a testnet wallet.
|
|
68
|
+
|
|
69
|
+
## Build and test
|
|
70
|
+
|
|
71
|
+
```sh
|
|
72
|
+
cd mcp
|
|
73
|
+
npm ci
|
|
74
|
+
npm test # builds vendor/ then runs node --test test/
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`npm run build` (also `prepack`) copies `agent/forewit.mjs`, `agent/config.mjs`, `agent/lib/*`, `web/src/lib/question.mjs`, the type stripped `web/src/lib/data.ts` and the scoring docs from both locales into `vendor/` (gitignored). Needs Node 22.13 or later for `module.stripTypeScriptTypes`.
|
|
78
|
+
|
|
79
|
+
## MCP Inspector run
|
|
80
|
+
|
|
81
|
+
Recorded in `mcp/INSPECTOR.md`.
|
|
82
|
+
|
|
83
|
+
## Ready for the publish step (owner approval needed, not done)
|
|
84
|
+
|
|
85
|
+
* `npm pack` output is checked (see `INSPECTOR.md`): bin, src, vendor, README only.
|
|
86
|
+
* Releases: tag vX.Y.Z matching package.json, then run the publish workflow on that tag (GitHub Actions trusted publishing with provenance; no npm token on any machine). 0.0.1 was a manual testnet preview.
|
|
87
|
+
* MCP Registry: needs a `server.json` and a namespace (`io.github.owaisahmad870/forewit` or a domain namespace `xyz.forewit/forewit` with DNS verification). Not created.
|
|
88
|
+
* Hosting the remote server: run `node bin/forewit.mjs mcp remote` behind TLS at `mcp.forewit.xyz`, with `HOST=0.0.0.0` and a proxy rate limit.
|
|
89
|
+
* Reserve the npm name `forewit` before the docs page goes live: the page tells users to run `npx forewit mcp`, and the name is unregistered today.
|
|
90
|
+
* Provenance needs a public repository and a publish workflow with `id-token: write`; neither exists yet.
|
|
91
|
+
* `agent/config.mjs` is copied at pack time: a package published before the mainnet ledger is pinned stays testnet only until republished.
|
package/bin/forewit.mjs
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// forewit mcp local stdio MCP server (prepares transactions, never signs)
|
|
3
|
+
// forewit mcp remote read only Streamable HTTP MCP server (PORT, HOST, FOREWIT_DATA, FOREWIT_ALLOWED_ORIGINS)
|
|
4
|
+
// forewit <anything else> the Forewit CLI (round, forecast, commit, reveal, status, receipt)
|
|
5
|
+
const [cmd, sub] = process.argv.slice(2);
|
|
6
|
+
|
|
7
|
+
if (cmd === 'mcp' && sub === 'remote') {
|
|
8
|
+
const { startHttp } = await import('../src/remote.mjs');
|
|
9
|
+
const http = await startHttp();
|
|
10
|
+
const a = http.address();
|
|
11
|
+
console.error(`forewit mcp remote: listening on http://${a.address}:${a.port}/mcp`);
|
|
12
|
+
} else if (cmd === 'mcp') {
|
|
13
|
+
console.log = console.error; // stdout carries JSON RPC only; any stray log goes to stderr
|
|
14
|
+
const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js');
|
|
15
|
+
const { createLocalServer } = await import('../src/local.mjs');
|
|
16
|
+
await createLocalServer().connect(new StdioServerTransport());
|
|
17
|
+
console.error('forewit mcp: local server on stdio');
|
|
18
|
+
} else {
|
|
19
|
+
const { main } = await import('../vendor/agent/forewit.mjs');
|
|
20
|
+
main(process.argv.slice(2)).catch((err) => {
|
|
21
|
+
console.error(`forewit: ${err.message}`);
|
|
22
|
+
process.exitCode = 1;
|
|
23
|
+
});
|
|
24
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,38 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "forewit",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Forewit MCP server and CLI: verifiable forecasting track record for Agent ID holders on BNB Smart Chain. Prepares calldata, never signs.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/owaisahmad870/forewit.git",
|
|
10
|
+
"directory": "mcp"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://forewit.xyz/#/docs/agents",
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=22"
|
|
15
|
+
},
|
|
16
|
+
"bin": {
|
|
17
|
+
"forewit": "bin/forewit.mjs"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"bin",
|
|
21
|
+
"src",
|
|
22
|
+
"vendor",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "node scripts/build.mjs",
|
|
27
|
+
"test": "node scripts/build.mjs && node --test test/",
|
|
28
|
+
"prepack": "node scripts/build.mjs"
|
|
29
|
+
},
|
|
30
|
+
"dependencies": {
|
|
31
|
+
"@modelcontextprotocol/sdk": "1.32.2",
|
|
32
|
+
"zod": "4.6.7"
|
|
33
|
+
},
|
|
34
|
+
"devDependencies": {
|
|
35
|
+
"viem": "2.58.4"
|
|
36
|
+
},
|
|
37
|
+
"mcpName": "io.github.owaisahmad870/forewit"
|
|
38
|
+
}
|
package/src/common.mjs
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Helpers shared by both Forewit MCP servers.
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
|
|
4
|
+
export const VERSION = '0.0.1';
|
|
5
|
+
|
|
6
|
+
/** Wraps structured output the way MCP 2025-06-18 and later expect: structuredContent plus the same JSON as text. */
|
|
7
|
+
export const ok = (data) => ({ structuredContent: data, content: [{ type: 'text', text: JSON.stringify(data) }] });
|
|
8
|
+
|
|
9
|
+
/** A tool execution error (isError true), never a protocol error. Messages never echo market text. */
|
|
10
|
+
export const fail = (message) => ({ isError: true, content: [{ type: 'text', text: message }] });
|
|
11
|
+
|
|
12
|
+
/** Runs a handler and turns any thrown Error into a tool execution error. */
|
|
13
|
+
export const guarded = (fn) => async (args, extra) => {
|
|
14
|
+
try {
|
|
15
|
+
return await fn(args, extra);
|
|
16
|
+
} catch (err) {
|
|
17
|
+
return fail(err instanceof Error ? err.message : String(err));
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// Cursor pagination: the cursor is an opaque base64url offset.
|
|
22
|
+
export const cursorInput = {
|
|
23
|
+
cursor: z.string().max(64).optional().describe('Opaque cursor from next_cursor of the previous page.'),
|
|
24
|
+
limit: z.number().int().min(1).max(100).optional().describe('Items per page, 1 to 100, default 25.'),
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export function paginate(items, { cursor, limit = 25 }) {
|
|
28
|
+
let start = 0;
|
|
29
|
+
if (cursor !== undefined) {
|
|
30
|
+
const text = Buffer.from(cursor, 'base64url').toString('utf8');
|
|
31
|
+
if (!/^\d{1,9}$/.test(text) || Number(text) > items.length) throw new Error('invalid cursor');
|
|
32
|
+
start = Number(text);
|
|
33
|
+
}
|
|
34
|
+
const end = start + limit;
|
|
35
|
+
return { page: items.slice(start, end), next_cursor: end < items.length ? Buffer.from(String(end)).toString('base64url') : null };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const address = z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 0x prefixed 20 byte hex address');
|
|
39
|
+
export const roundId = z.number().int().min(1).max(1e9);
|
package/src/local.mjs
ADDED
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// Forewit local MCP server (stdio). Prepares commit, reveal and profile transactions and lists local receipts.
|
|
2
|
+
// It never signs, never sends and never runs baw: it returns calldata and the baw preview command for the wallet owner.
|
|
3
|
+
// Network access: the pinned public RPC of the chosen network only (read only eth_call). Logs go to stderr only.
|
|
4
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import {
|
|
7
|
+
network, loadRound, chainNow, commitPlan, revealPlan, parseProbabilities, findReceipts, receiptDir, bawPreview,
|
|
8
|
+
} from '../vendor/agent/forewit.mjs';
|
|
9
|
+
import { selector, wordBool, wordUint } from '../vendor/agent/lib/keccak.mjs';
|
|
10
|
+
import { NETWORKS, DEFAULT_NETWORK, BAW_CHAIN_IDS, RISK_WARNING } from '../vendor/agent/config.mjs';
|
|
11
|
+
import { ok, guarded, paginate, cursorInput, address, roundId, VERSION } from './common.mjs';
|
|
12
|
+
|
|
13
|
+
const ANNOTATIONS = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
|
|
14
|
+
const networkInput = z.enum(['mainnet', 'testnet']).optional().describe(`Network, default ${DEFAULT_NETWORK}.`);
|
|
15
|
+
const iso = (s) => (s == null ? null : new Date(s * 1000).toISOString());
|
|
16
|
+
|
|
17
|
+
/** setPublicProfile(bool,string) calldata: a bool word, the string offset (0x40), then length and right padded UTF8 bytes. */
|
|
18
|
+
export function profileCalldata(isPublic, label) {
|
|
19
|
+
const bytes = Buffer.from(label, 'utf8');
|
|
20
|
+
const padded = Buffer.concat([bytes, Buffer.alloc((32 - (bytes.length % 32)) % 32)]);
|
|
21
|
+
return selector('setPublicProfile(bool,string)') + wordBool(isPublic) + wordUint(64) + wordUint(bytes.length) + padded.toString('hex');
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const txShape = z.object({
|
|
25
|
+
chain_id: z.number().int(),
|
|
26
|
+
to: z.string(),
|
|
27
|
+
value: z.literal('0'),
|
|
28
|
+
data: z.string(),
|
|
29
|
+
});
|
|
30
|
+
const walletShape = {
|
|
31
|
+
transaction: txShape,
|
|
32
|
+
baw_preview_command: z.string().describe('Binance Agentic Wallet preview command for this exact transaction. Preview only; executing needs the wallet owner.'),
|
|
33
|
+
baw_can_sign_this_network: z.boolean().describe(`baw signs on chain ${BAW_CHAIN_IDS.join(', ')} only.`),
|
|
34
|
+
risk_warning: z.string(),
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
function walletPart(net, from, data) {
|
|
38
|
+
return {
|
|
39
|
+
transaction: { chain_id: net.chainId, to: net.ledger, value: '0', data },
|
|
40
|
+
baw_preview_command: bawPreview({ chainId: net.chainId, from, to: net.ledger, data }),
|
|
41
|
+
baw_can_sign_this_network: BAW_CHAIN_IDS.includes(net.chainId),
|
|
42
|
+
risk_warning: RISK_WARNING,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const hex = (bytes) => z.string().regex(new RegExp(`^0x[0-9a-fA-F]{${bytes * 2}}$`));
|
|
47
|
+
const seconds = z.number().int().nonnegative();
|
|
48
|
+
// Shape a receipt file must have to be listed; anything else is skipped with a warning.
|
|
49
|
+
const receiptFile = z.object({
|
|
50
|
+
network: z.string(), chainId: z.number().int(), ledger: hex(20), roundId: z.number().int().positive(), forecaster: hex(20),
|
|
51
|
+
commitHash: hex(32), salt: hex(32), probabilitiesBps: z.array(z.number().int()).optional(),
|
|
52
|
+
commitDeadline: seconds.nullable(), revealDeadline: seconds.nullable().optional(), createdAt: z.string().optional(),
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
const roundInput = roundId.optional().describe('Round id, default the latest round on the ledger.');
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Salts never enter agent context before the commit deadline: with the salt and the forecast anyone could reveal or copy it.
|
|
59
|
+
* Checks chain time on each receipt's pinned network. Throws (a tool error) if any listed round is still open for commits.
|
|
60
|
+
* Returns the receipts whose deadline cannot be checked (unpinned ledger, for example a deprecated instance, or no deadline):
|
|
61
|
+
* their salt is withheld with a warning instead of blocking every other backup.
|
|
62
|
+
*/
|
|
63
|
+
async function saltGate(receipts, warnings) {
|
|
64
|
+
const nowByChain = new Map();
|
|
65
|
+
const withheld = new Set();
|
|
66
|
+
for (const r of receipts) {
|
|
67
|
+
const net = Object.values(NETWORKS).find((n) => n.chainId === r.chainId && n.ledger && n.ledger.toLowerCase() === r.ledger.toLowerCase());
|
|
68
|
+
if (!net || r.commitDeadline == null) {
|
|
69
|
+
withheld.add(r);
|
|
70
|
+
warnings.push({ file: r.file, reason: net ? 'no commit deadline in the receipt; salt withheld' : 'ledger is not a pinned Forewit ledger, so the commit deadline cannot be checked; salt withheld' });
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (!nowByChain.has(net.chainId)) nowByChain.set(net.chainId, await chainNow(net));
|
|
74
|
+
if (nowByChain.get(net.chainId) < r.commitDeadline) {
|
|
75
|
+
throw new Error(`round ${r.roundId} is open for commits until ${iso(r.commitDeadline)}; salts stay local until then. Use prepare_reveal after the deadline, or filter with round_id.`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return withheld;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** `home` is the folder that holds .forewit/ (default: the user's home directory). It is not a tool input. */
|
|
82
|
+
export function createLocalServer({ home } = {}) {
|
|
83
|
+
const server = new McpServer({ name: 'forewit-local', version: VERSION, title: 'Forewit (local, prepares transactions)' });
|
|
84
|
+
const tool = (name, config, fn, annotations = ANNOTATIONS) =>
|
|
85
|
+
server.registerTool(name, { ...config, inputSchema: z.object(config.inputSchema).strict(), outputSchema: z.object(config.outputSchema), annotations: { ...annotations, title: config.title } }, guarded(fn));
|
|
86
|
+
|
|
87
|
+
tool('prepare_commit', {
|
|
88
|
+
title: 'Prepare a commit',
|
|
89
|
+
description: 'Makes a random salt, saves the reveal receipt (salt included) in ~/.forewit with owner only access, and returns the commit hash, calldata and baw preview command. Probabilities are percentages, one per question, clamped to 1 to 99. The salt is not returned.',
|
|
90
|
+
inputSchema: {
|
|
91
|
+
from: address.describe('Agentic wallet address that will send the commit.'),
|
|
92
|
+
probabilities_percent: z.array(z.number().min(0).max(100)).min(1).max(16),
|
|
93
|
+
round_id: roundInput,
|
|
94
|
+
network: networkInput,
|
|
95
|
+
},
|
|
96
|
+
outputSchema: {
|
|
97
|
+
network: z.string(), ledger: z.string(), round_id: z.number().int(), from: z.string(),
|
|
98
|
+
commit_deadline: z.string(), reveal_deadline: z.string(),
|
|
99
|
+
probabilities_bps: z.array(z.number().int()), clamped_indexes: z.array(z.number().int()),
|
|
100
|
+
packed: z.string(), commit_hash: z.string(), already_committed: z.boolean(),
|
|
101
|
+
receipt_file: z.string(), salt_returned: z.literal(false),
|
|
102
|
+
...walletShape,
|
|
103
|
+
},
|
|
104
|
+
}, async ({ from, probabilities_percent, round_id, network: name }) => {
|
|
105
|
+
const net = network(name);
|
|
106
|
+
const { bps, clamped } = parseProbabilities(probabilities_percent.join(','));
|
|
107
|
+
const loaded = await loadRound(net, round_id === undefined ? undefined : String(round_id));
|
|
108
|
+
const { receipt, file, existing, data } = await commitPlan({ net, from, bps, home, loaded });
|
|
109
|
+
console.error(`forewit mcp: saved receipt for round ${loaded.id} at ${file}`);
|
|
110
|
+
return ok({
|
|
111
|
+
network: net.name, ledger: net.ledger, round_id: loaded.id, from,
|
|
112
|
+
commit_deadline: iso(loaded.round.commitDeadline), reveal_deadline: iso(loaded.round.revealDeadline),
|
|
113
|
+
probabilities_bps: bps, clamped_indexes: clamped, packed: receipt.packed, commit_hash: receipt.commitHash,
|
|
114
|
+
already_committed: existing, receipt_file: file, salt_returned: false,
|
|
115
|
+
...walletPart(net, from, data),
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
tool('prepare_reveal', {
|
|
120
|
+
title: 'Prepare a reveal',
|
|
121
|
+
description: 'After the commit deadline and before the reveal deadline: finds the local receipt that matches the onchain commit and returns the reveal calldata (which contains the salt, as the reveal must) and baw preview command. Refused while commits are still open.',
|
|
122
|
+
inputSchema: { from: address.describe('Wallet that made the commit.'), round_id: roundInput, network: networkInput },
|
|
123
|
+
outputSchema: {
|
|
124
|
+
network: z.string(), ledger: z.string(), round_id: z.number().int(), from: z.string(),
|
|
125
|
+
already_revealed: z.boolean(), reveal_deadline: z.string(),
|
|
126
|
+
probabilities_bps: z.array(z.number().int()).nullable(), commit_hash: z.string().nullable(), receipt_file: z.string().nullable(),
|
|
127
|
+
transaction: txShape.nullable(), baw_preview_command: z.string().nullable(), baw_can_sign_this_network: z.boolean(), risk_warning: z.string(),
|
|
128
|
+
},
|
|
129
|
+
}, async ({ from, round_id, network: name }) => {
|
|
130
|
+
const net = network(name);
|
|
131
|
+
const loaded = await loadRound(net, round_id === undefined ? undefined : String(round_id));
|
|
132
|
+
const plan = await revealPlan({ net, from, home, loaded });
|
|
133
|
+
const base = { network: net.name, ledger: net.ledger, round_id: loaded.id, from, reveal_deadline: iso(loaded.round.revealDeadline) };
|
|
134
|
+
if (plan.alreadyRevealed) {
|
|
135
|
+
return ok({ ...base, already_revealed: true, probabilities_bps: null, commit_hash: null, receipt_file: null, transaction: null, baw_preview_command: null, baw_can_sign_this_network: BAW_CHAIN_IDS.includes(net.chainId), risk_warning: RISK_WARNING });
|
|
136
|
+
}
|
|
137
|
+
return ok({ ...base, already_revealed: false, probabilities_bps: plan.bps, commit_hash: plan.onchain, receipt_file: plan.receipt.file, ...walletPart(net, from, plan.data) });
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
tool('prepare_profile', {
|
|
141
|
+
title: 'Prepare a profile change',
|
|
142
|
+
description: 'Returns calldata and the baw preview command for setPublicProfile: opt in to the public leaderboard (optionally showing your Agent ID name, without .ai) or opt out. Opting out clears the name.',
|
|
143
|
+
inputSchema: {
|
|
144
|
+
from: address.describe('Wallet that holds the Agent ID.'),
|
|
145
|
+
is_public: z.boolean(),
|
|
146
|
+
label: z.string().regex(/^[a-z0-9_-]{1,64}$/, 'Agent ID name in lowercase letters, digits, underscore or hyphen, without .ai').optional(),
|
|
147
|
+
network: networkInput,
|
|
148
|
+
},
|
|
149
|
+
outputSchema: { network: z.string(), ledger: z.string(), from: z.string(), is_public: z.boolean(), label: z.string(), ...walletShape },
|
|
150
|
+
}, async ({ from, is_public, label = '', network: name }) => {
|
|
151
|
+
const net = network(name);
|
|
152
|
+
const shown = is_public ? label : '';
|
|
153
|
+
return ok({ network: net.name, ledger: net.ledger, from, is_public, label: shown, ...walletPart(net, from, profileCalldata(is_public, shown)) });
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
tool('my_receipts', {
|
|
157
|
+
title: 'My receipts',
|
|
158
|
+
description: 'Lists reveal receipts saved in ~/.forewit. Returns metadata and file paths. include_salt adds each salt, and is refused while any listed round is still open for commits (chain time). Files that are not valid receipts are listed in warnings. Paginated, newest first.',
|
|
159
|
+
inputSchema: {
|
|
160
|
+
from: address.optional(),
|
|
161
|
+
round_id: roundId.optional(),
|
|
162
|
+
network: networkInput,
|
|
163
|
+
include_salt: z.boolean().optional().describe('Include each salt, for a private backup after the commit deadline. Default false.'),
|
|
164
|
+
...cursorInput,
|
|
165
|
+
},
|
|
166
|
+
outputSchema: {
|
|
167
|
+
folder: z.string(),
|
|
168
|
+
receipts: z.array(z.object({
|
|
169
|
+
file: z.string(), network: z.string(), chain_id: z.number().int(), ledger: z.string(), round_id: z.number().int(), forecaster: z.string(),
|
|
170
|
+
commit_hash: z.string(), probabilities_bps: z.array(z.number().int()), commit_deadline: z.string().nullable(), reveal_deadline: z.string().nullable(),
|
|
171
|
+
created_at: z.string().nullable(), salt: z.string().optional(),
|
|
172
|
+
})),
|
|
173
|
+
warnings: z.array(z.object({ file: z.string(), reason: z.string() })),
|
|
174
|
+
next_cursor: z.string().nullable(),
|
|
175
|
+
},
|
|
176
|
+
}, async ({ from, round_id, network: name, include_salt = false, cursor, limit }) => {
|
|
177
|
+
const filter = { forecaster: from, roundId: round_id };
|
|
178
|
+
if (name) filter.chainId = network(name).chainId;
|
|
179
|
+
const warnings = [];
|
|
180
|
+
const found = [];
|
|
181
|
+
for (const r of findReceipts(filter, home, warnings)) {
|
|
182
|
+
const parsed = receiptFile.safeParse(r);
|
|
183
|
+
if (parsed.success) found.push({ ...parsed.data, file: r.file });
|
|
184
|
+
else warnings.push({ file: r.file, reason: `not a valid receipt (fields: ${[...new Set(parsed.error.issues.map((i) => i.path.join('.')))].join(', ')})` });
|
|
185
|
+
}
|
|
186
|
+
for (const w of warnings) console.error(`forewit mcp: skipped ${w.file}: ${w.reason}`);
|
|
187
|
+
found.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
|
|
188
|
+
const { page, next_cursor } = paginate(found, { cursor, limit });
|
|
189
|
+
const withheld = include_salt ? await saltGate(page, warnings) : null;
|
|
190
|
+
return ok({
|
|
191
|
+
folder: receiptDir(home),
|
|
192
|
+
receipts: page.map((r) => ({
|
|
193
|
+
file: r.file, network: r.network, chain_id: r.chainId, ledger: r.ledger, round_id: r.roundId,
|
|
194
|
+
forecaster: r.forecaster, commit_hash: r.commitHash, probabilities_bps: r.probabilitiesBps ?? [],
|
|
195
|
+
commit_deadline: iso(r.commitDeadline), reveal_deadline: iso(r.revealDeadline), created_at: r.createdAt ?? null,
|
|
196
|
+
...(include_salt && !withheld.has(r) ? { salt: r.salt } : {}),
|
|
197
|
+
})),
|
|
198
|
+
warnings,
|
|
199
|
+
next_cursor,
|
|
200
|
+
});
|
|
201
|
+
}, { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false });
|
|
202
|
+
|
|
203
|
+
return server;
|
|
204
|
+
}
|