@reclaimprotocol/agent 0.1.10 → 0.1.12

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.
Files changed (49) hide show
  1. package/lib/authoring/tools.js +67 -0
  2. package/lib/mcp/tools/agent/find.js +41 -16
  3. package/lib/mcp/tools/agent/propose.js +4 -4
  4. package/lib/old/client.d.ts +31 -5
  5. package/lib/old/client.js +33 -10
  6. package/lib/old/to-register.d.ts +2 -0
  7. package/lib/old/to-register.js +9 -5
  8. package/lib/old/tools/build.js +12 -2
  9. package/lib/old/tools/check-app-status.d.ts +8 -0
  10. package/lib/old/tools/check-app-status.js +27 -0
  11. package/lib/old/tools/get-provider-info.d.ts +10 -7
  12. package/lib/old/tools/get-provider-info.js +21 -15
  13. package/lib/old/tools/issue-app-credentials.d.ts +11 -0
  14. package/lib/old/tools/issue-app-credentials.js +35 -0
  15. package/lib/old/tools/js-sdk-integration-guide.d.ts +2 -0
  16. package/lib/old/tools/js-sdk-integration-guide.js +141 -0
  17. package/lib/old/tools/link-app.d.ts +10 -0
  18. package/lib/old/tools/link-app.js +72 -0
  19. package/lib/old/tools/publish.js +89 -126
  20. package/lib/old/tools/scaffold-demo-server.d.ts +2 -0
  21. package/lib/old/tools/scaffold-demo-server.js +242 -0
  22. package/lib/old/tools/verify-sdk-setup.d.ts +9 -0
  23. package/lib/old/tools/verify-sdk-setup.js +128 -0
  24. package/lib/provider/dom-xpath.js +178 -25
  25. package/lib/provider/draft.d.ts +6 -0
  26. package/lib/provider/draft.js +54 -5
  27. package/lib/provider/matcher.d.ts +4 -0
  28. package/lib/provider/matcher.js +6 -0
  29. package/lib/provider/to-version.d.ts +13 -0
  30. package/package.json +2 -1
  31. package/src/authoring/tools.ts +76 -0
  32. package/src/mcp/tools/agent/find.ts +44 -16
  33. package/src/mcp/tools/agent/propose.ts +4 -4
  34. package/src/old/client.ts +60 -18
  35. package/src/old/to-register.ts +11 -5
  36. package/src/old/tools/build.ts +12 -2
  37. package/src/old/tools/check-app-status.ts +33 -0
  38. package/src/old/tools/get-provider-info.ts +21 -15
  39. package/src/old/tools/issue-app-credentials.ts +42 -0
  40. package/src/old/tools/js-sdk-integration-guide.ts +147 -0
  41. package/src/old/tools/link-app.ts +88 -0
  42. package/src/old/tools/publish.ts +98 -158
  43. package/src/old/tools/scaffold-demo-server.ts +265 -0
  44. package/src/old/tools/verify-sdk-setup.ts +158 -0
  45. package/src/provider/dom-xpath.ts +227 -27
  46. package/src/provider/draft.ts +59 -5
  47. package/src/provider/matcher.ts +7 -0
  48. package/src/provider/to-version.ts +13 -0
  49. package/src/old/tools/get-version-config.ts +0 -56
@@ -0,0 +1,265 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs'
2
+ import { isAbsolute, join } from 'node:path'
3
+ import { defineTool, type RegisteredTool } from '../../mcp/server.ts'
4
+ import { findProjectRoot } from '../../paths.ts'
5
+
6
+ /** Corrected against `@reclaimprotocol/js-sdk` v5.8.1 (`Reclaim.ts`): awaits
7
+ * `getRequestUrl()`, uses `setContext` (not deprecated `addContext`), JSON-
8
+ * parses the raw webhook body before `verifyProof`, passes the required
9
+ * `{ providerId, providerVersion }` config, and reads `result.isVerified`
10
+ * (not `is_verified`). `providerVersion` is left unpinned (`undefined`) by
11
+ * default — the built-in "example" providerId isn't versioned, so pinning
12
+ * one is only meaningful once you swap in your own provider. */
13
+ function serverJs(providerId: string, providerVersion: string | undefined): string {
14
+ return `import express from "express";
15
+ import "dotenv/config";
16
+ import { ReclaimProofRequest, verifyProof } from "@reclaimprotocol/js-sdk";
17
+ import { randomUUID } from "node:crypto";
18
+
19
+ const app = express();
20
+ const port = process.env.PORT || 3000;
21
+ const providerId = ${JSON.stringify(providerId)};
22
+ // Left unpinned by default — set this if you need to pin a specific version.
23
+ const providerVersion = ${providerVersion ? JSON.stringify(providerVersion) : 'undefined'};
24
+
25
+ app.set("trust proxy", true);
26
+ app.use(express.json({ limit: "2mb" }));
27
+
28
+ app.get("/health", (_req, res) => {
29
+ res.json({ ok: true });
30
+ });
31
+
32
+ app.get("/verify", (_req, res) => {
33
+ res.type("html").send(\`<!doctype html>
34
+ <html lang="en">
35
+ <head>
36
+ <meta charset="utf-8" />
37
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
38
+ <title>Reclaim demo verification</title>
39
+ <style>
40
+ body { font-family: system-ui, sans-serif; max-width: 680px; margin: 64px auto; padding: 0 20px; line-height: 1.5; }
41
+ code { background: #f3f4f6; padding: 2px 6px; border-radius: 4px; }
42
+ button { background: #111827; border: 0; border-radius: 8px; color: white; cursor: pointer; font: inherit; padding: 12px 18px; }
43
+ button:disabled { cursor: wait; opacity: 0.7; }
44
+ pre { background: #f3f4f6; border-radius: 8px; overflow: auto; padding: 12px; }
45
+ </style>
46
+ </head>
47
+ <body>
48
+ <h1>Reclaim demo verification</h1>
49
+ <p>Uses provider <code>\${providerId}</code>.</p>
50
+ <button id="start">Start verification</button>
51
+ <pre id="status">Ready.</pre>
52
+ <p>Webhook endpoint: <code>/webhooks/reclaim</code></p>
53
+ <script>
54
+ const button = document.getElementById("start");
55
+ const status = document.getElementById("status");
56
+ button.addEventListener("click", async () => {
57
+ button.disabled = true;
58
+ status.textContent = "Creating verification request...";
59
+ try {
60
+ const response = await fetch("/api/reclaim/request", { method: "POST" });
61
+ if (!response.ok) throw new Error(await response.text());
62
+ const { requestUrl } = await response.json();
63
+ status.textContent = "Opening Reclaim verification...";
64
+ window.open(requestUrl, "_blank", "noopener,noreferrer");
65
+ status.textContent = "Verification opened. Complete it in the Reclaim window.";
66
+ } catch (error) {
67
+ status.textContent = error instanceof Error ? error.message : String(error);
68
+ button.disabled = false;
69
+ }
70
+ });
71
+ </script>
72
+ </body>
73
+ </html>\`);
74
+ });
75
+
76
+ app.post("/api/reclaim/request", async (req, res, next) => {
77
+ try {
78
+ const appId = process.env.RECLAIM_APP_ID;
79
+ const appSecret = process.env.RECLAIM_APP_SECRET;
80
+ if (!appId || !appSecret) {
81
+ return res.status(500).json({ error: "Missing RECLAIM_APP_ID or RECLAIM_APP_SECRET" });
82
+ }
83
+
84
+ const origin = process.env.PUBLIC_URL || \`\${req.protocol}://\${req.get("host")}\`;
85
+ const reclaimProofRequest = await ReclaimProofRequest.init(appId, appSecret, providerId, {
86
+ providerVersion,
87
+ });
88
+ reclaimProofRequest.setAppCallbackUrl(\`\${origin}/webhooks/reclaim\`, true);
89
+ reclaimProofRequest.setContext(
90
+ randomUUID(),
91
+ JSON.stringify({ createdAt: new Date().toISOString() }),
92
+ );
93
+
94
+ // getRequestUrl() is ASYNC in the current SDK — must be awaited.
95
+ const requestUrl = await reclaimProofRequest.getRequestUrl();
96
+
97
+ res.json({
98
+ request: reclaimProofRequest.toJsonString(),
99
+ requestUrl,
100
+ });
101
+ } catch (error) {
102
+ next(error);
103
+ }
104
+ });
105
+
106
+ app.post("/webhooks/reclaim", async (req, res, next) => {
107
+ try {
108
+ // With jsonProofResponse: true + express.json() above, req.body is
109
+ // already a parsed Proof/Proof[]. Without either of those, the raw body
110
+ // is text and must be JSON.parse()'d (and URL-decoded if form-encoded)
111
+ // before calling verifyProof.
112
+ const proof = req.body;
113
+
114
+ // The second argument is REQUIRED — must include providerId.
115
+ const result = await verifyProof(proof, { providerId, providerVersion });
116
+
117
+ console.log("Received Reclaim verification:");
118
+ console.log(JSON.stringify({ isVerified: result.isVerified, data: result.data, error: result.error }, null, 2));
119
+
120
+ res.status(200).json({ received: true, verified: result.isVerified });
121
+ } catch (error) {
122
+ next(error);
123
+ }
124
+ });
125
+
126
+ app.use((err, _req, res, _next) => {
127
+ console.error(err);
128
+ res.status(500).json({ error: err instanceof Error ? err.message : "Internal server error" });
129
+ });
130
+
131
+ app.listen(port, () => {
132
+ console.log(\`Reclaim demo server listening on http://localhost:\${port}\`);
133
+ console.log(\`Verify page: http://localhost:\${port}/verify\`);
134
+ console.log(\`Webhook endpoint: http://localhost:\${port}/webhooks/reclaim\`);
135
+ if (!process.env.PUBLIC_URL) {
136
+ console.log("Set PUBLIC_URL (e.g. an ngrok URL) so the webhook is reachable from Reclaim's servers.");
137
+ }
138
+ });
139
+ `
140
+ }
141
+
142
+ const PACKAGE_JSON = (name: string) => JSON.stringify(
143
+ {
144
+ name,
145
+ private: true,
146
+ type: 'module',
147
+ scripts: { start: 'node server.js' },
148
+ dependencies: {
149
+ '@reclaimprotocol/js-sdk': '^5.8.1',
150
+ dotenv: '^16.4.5',
151
+ express: '^4.21.2',
152
+ },
153
+ },
154
+ null,
155
+ 2,
156
+ ) + '\n'
157
+
158
+ const ENV_EXAMPLE = `RECLAIM_APP_ID=
159
+ RECLAIM_APP_SECRET=
160
+ PORT=3000
161
+ # REQUIRED for the webhook callback to land — Reclaim's servers can't reach
162
+ # localhost. Run: ngrok http 3000 (in a separate terminal) and paste the
163
+ # https://<id>.ngrok-free.app URL it prints here. Without this, only the
164
+ # frontend-side flow works (opening requestUrl) — the webhook never fires.
165
+ PUBLIC_URL=
166
+ `
167
+
168
+ const README = `# Reclaim demo server
169
+
170
+ 1. \`npm install\`
171
+ 2. Fill in \`.env\` (copy from \`.env.example\`) — get \`RECLAIM_APP_ID\`/
172
+ \`RECLAIM_APP_SECRET\` from the \`issue_app_credentials\` MCP tool, or your
173
+ existing app.
174
+ 3. In a separate terminal, run \`ngrok http 3000\` (install from
175
+ https://ngrok.com if needed) and copy the \`https://<id>.ngrok-free.app\`
176
+ URL it prints into \`PUBLIC_URL\` in \`.env\`. This is REQUIRED — Reclaim's
177
+ servers must reach your webhook over the public internet, and
178
+ \`localhost\` is not reachable from there.
179
+ 4. \`npm start\`, then open http://localhost:3000/verify and click "Start
180
+ verification".
181
+ 5. Watch the server logs for the \`/webhooks/reclaim\` payload once you
182
+ complete verification.
183
+
184
+ This demo defaults to providerId \`"example"\` — a built-in smoke-test
185
+ provider, so you can confirm the whole loop (request → open → callback)
186
+ works before wiring in a real provider.
187
+ `
188
+
189
+ /**
190
+ * Scaffold a small, runnable Express demo that exercises the full
191
+ * @reclaimprotocol/js-sdk flow end-to-end: request a proof (backend), open it
192
+ * (frontend), and verify the async webhook callback (backend). Corrected
193
+ * against the CURRENT SDK API (see js-sdk-integration-guide) rather than
194
+ * older examples that predate several signature changes.
195
+ */
196
+ const DEFAULT_PROVIDER_ID = 'example'
197
+
198
+ export function scaffoldDemoServerTool(): RegisteredTool {
199
+ return defineTool<{
200
+ targetDir: string
201
+ providerId?: string
202
+ providerVersion?: string
203
+ }>(
204
+ {
205
+ name: 'scaffold_reclaim_demo_server',
206
+ description:
207
+ 'Write a small runnable Express demo (server.js, package.json, ' +
208
+ '.env.example, README.md) that requests a Reclaim proof and ' +
209
+ 'verifies the async webhook callback, using the CURRENT ' +
210
+ '@reclaimprotocol/js-sdk API. Defaults `providerId` to the built-in ' +
211
+ '"example" smoke-test provider so you can confirm the whole loop ' +
212
+ 'without authoring one first, and requires ngrok (or similar) to ' +
213
+ 'expose the local server so the webhook callback can reach it — ' +
214
+ 'the generated README walks through that step. Use ' +
215
+ 'get_js_sdk_integration_guide for the annotated write-up of the ' +
216
+ 'same flow.',
217
+ inputSchema: {
218
+ type: 'object',
219
+ properties: {
220
+ targetDir: {
221
+ type: 'string',
222
+ description:
223
+ 'Directory to write the demo into (created if missing). ' +
224
+ 'Relative paths resolve against the project root.',
225
+ },
226
+ providerId: {
227
+ type: 'string',
228
+ description:
229
+ 'Provider id the demo requests a proof for (default ' +
230
+ '"example", a built-in smoke-test provider — good for ' +
231
+ 'confirming the flow works before wiring in a real one).',
232
+ },
233
+ providerVersion: {
234
+ type: 'string',
235
+ description:
236
+ 'Provider version to pin (default: unpinned — "example" ' +
237
+ 'isn\'t versioned, so only set this once you swap in your ' +
238
+ 'own provider).',
239
+ },
240
+ },
241
+ required: ['targetDir'],
242
+ },
243
+ },
244
+ async({ targetDir, providerId, providerVersion }) => {
245
+ const dir = isAbsolute(targetDir)
246
+ ? targetDir
247
+ : join(findProjectRoot(process.cwd()), targetDir)
248
+ mkdirSync(dir, { recursive: true })
249
+
250
+ const id = providerId ?? DEFAULT_PROVIDER_ID
251
+ writeFileSync(join(dir, 'server.js'), serverJs(id, providerVersion))
252
+ writeFileSync(join(dir, 'package.json'), PACKAGE_JSON('reclaim-demo-server'))
253
+ writeFileSync(join(dir, '.env.example'), ENV_EXAMPLE)
254
+ writeFileSync(join(dir, 'README.md'), README)
255
+
256
+ return {
257
+ dir,
258
+ providerId: id,
259
+ files: ['server.js', 'package.json', '.env.example', 'README.md'],
260
+ next: 'cd into the directory, npm install, copy .env.example to .env ' +
261
+ 'and fill it in (including PUBLIC_URL from ngrok), then npm start.',
262
+ }
263
+ },
264
+ )
265
+ }
@@ -0,0 +1,158 @@
1
+ import { existsSync, readFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { defineTool, type RegisteredTool } from '../../mcp/server.ts'
4
+ import { findProjectRoot } from '../../paths.ts'
5
+ import type { ReclaimOldClient } from '../client.ts'
6
+
7
+ interface Check {
8
+ name: string
9
+ ok: boolean
10
+ detail: string
11
+ }
12
+
13
+ function readEnvFile(dir: string): Record<string, string> {
14
+ const path = join(dir, '.env')
15
+ if(!existsSync(path)) {
16
+ return {}
17
+ }
18
+
19
+ const out: Record<string, string> = {}
20
+ for(const line of readFileSync(path, 'utf8').split('\n')) {
21
+ const m = line.match(/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*?)\s*$/)
22
+ if(m) {
23
+ out[m[1]] = m[2].replace(/^['"]|['"]$/g, '')
24
+ }
25
+ }
26
+
27
+ return out
28
+ }
29
+
30
+ /**
31
+ * Health-check a project's @reclaimprotocol/js-sdk setup: SDK installed,
32
+ * RECLAIM_APP_ID/RECLAIM_APP_SECRET present (env or .env), and (if an appId
33
+ * is found) whether that app is actually linked/has quota, via the real
34
+ * check_app_status endpoint — not just static file checks.
35
+ */
36
+ export function verifySdkSetupTool(client: ReclaimOldClient): RegisteredTool {
37
+ return defineTool<{ projectDir?: string }>(
38
+ {
39
+ name: 'verify_reclaim_sdk_setup',
40
+ description:
41
+ 'Health-check a project\'s @reclaimprotocol/js-sdk integration: SDK ' +
42
+ 'installed, RECLAIM_APP_ID/RECLAIM_APP_SECRET present, and (if an ' +
43
+ 'appId is found) whether that app is actually linked and has quota ' +
44
+ 'left, by calling the real status endpoint.',
45
+ inputSchema: {
46
+ type: 'object',
47
+ properties: {
48
+ projectDir: {
49
+ type: 'string',
50
+ description: 'Project directory (default: detected project root).',
51
+ },
52
+ },
53
+ },
54
+ },
55
+ async({ projectDir }) => {
56
+ const dir = projectDir ?? findProjectRoot(process.cwd())
57
+ const checks: Check[] = []
58
+
59
+ const pkgPath = join(dir, 'package.json')
60
+ let sdkInPkg = false
61
+ if(existsSync(pkgPath)) {
62
+ try {
63
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'))
64
+ sdkInPkg = Boolean(
65
+ pkg.dependencies?.['@reclaimprotocol/js-sdk'] ||
66
+ pkg.devDependencies?.['@reclaimprotocol/js-sdk'],
67
+ )
68
+ } catch{
69
+ // malformed package.json — fall through, reported below
70
+ }
71
+ }
72
+
73
+ const sdkInstalled = existsSync(
74
+ join(dir, 'node_modules', '@reclaimprotocol', 'js-sdk'),
75
+ )
76
+ checks.push({
77
+ name: 'sdk_dependency',
78
+ ok: sdkInPkg,
79
+ detail: sdkInPkg
80
+ ? '@reclaimprotocol/js-sdk is listed in package.json'
81
+ : '@reclaimprotocol/js-sdk is NOT in package.json — run ' +
82
+ '`npm install @reclaimprotocol/js-sdk`.',
83
+ })
84
+ checks.push({
85
+ name: 'sdk_installed',
86
+ ok: sdkInstalled,
87
+ detail: sdkInstalled
88
+ ? '@reclaimprotocol/js-sdk found in node_modules'
89
+ : 'Not found in node_modules — run your package manager\'s ' +
90
+ 'install command.',
91
+ })
92
+
93
+ const env = { ...readEnvFile(dir), ...process.env }
94
+ const appId = env.RECLAIM_APP_ID
95
+ const appSecret = env.RECLAIM_APP_SECRET
96
+ checks.push({
97
+ name: 'app_id',
98
+ ok: Boolean(appId),
99
+ detail: appId
100
+ ? `RECLAIM_APP_ID set (${appId})`
101
+ : 'RECLAIM_APP_ID missing (env or .env) — run ' +
102
+ 'issue_app_credentials or link_app_to_account.',
103
+ })
104
+ checks.push({
105
+ name: 'app_secret',
106
+ ok: Boolean(appSecret),
107
+ detail: appSecret
108
+ ? 'RECLAIM_APP_SECRET set'
109
+ : 'RECLAIM_APP_SECRET missing (env or .env).',
110
+ })
111
+
112
+ // Informational only — PUBLIC_URL is only needed for the async
113
+ // webhook callback, not the frontend-only flow, so a missing value
114
+ // doesn't fail the overall check.
115
+ const publicUrl = env.PUBLIC_URL
116
+ checks.push({
117
+ name: 'public_url',
118
+ ok: true,
119
+ detail: publicUrl
120
+ ? `PUBLIC_URL set (${publicUrl}) — used as the webhook callback ` +
121
+ 'base for setAppCallbackUrl.'
122
+ : 'PUBLIC_URL not set — fine if you only read the proof from the ' +
123
+ 'frontend flow, but the async webhook callback needs a ' +
124
+ 'publicly-reachable URL (e.g. from `ngrok http <port>`) or it ' +
125
+ 'will never fire.',
126
+ })
127
+
128
+ if(appId) {
129
+ try {
130
+ const status = await client.getApplicationStatus(appId) as {
131
+ isLinked?: boolean
132
+ sandboxMode?: boolean
133
+ available?: boolean
134
+ }
135
+ const linked = status?.isLinked === true
136
+ checks.push({
137
+ name: 'app_status',
138
+ ok: status?.available !== false,
139
+ detail:
140
+ `isLinked=${linked}, sandboxMode=${status?.sandboxMode}, ` +
141
+ `available=${status?.available}` +
142
+ (linked ? '' : ' — run link_app_to_account to lift the sandbox limit.'),
143
+ })
144
+ } catch(err) {
145
+ checks.push({
146
+ name: 'app_status',
147
+ ok: false,
148
+ detail: `Could not reach status endpoint: ${
149
+ err instanceof Error ? err.message : String(err)
150
+ }`,
151
+ })
152
+ }
153
+ }
154
+
155
+ return { projectDir: dir, checks, ok: checks.every((c) => c.ok) }
156
+ },
157
+ )
158
+ }