@reclaimprotocol/agent 0.1.0-dev.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.
Files changed (191) hide show
  1. package/README.md +287 -0
  2. package/lib/cdp/capture.d.ts +22 -0
  3. package/lib/cdp/capture.js +159 -0
  4. package/lib/cdp/client.d.ts +9 -0
  5. package/lib/cdp/client.js +11 -0
  6. package/lib/cdp/eviction.d.ts +16 -0
  7. package/lib/cdp/eviction.js +38 -0
  8. package/lib/cdp/launcher.d.ts +14 -0
  9. package/lib/cdp/launcher.js +102 -0
  10. package/lib/cdp/tabs.d.ts +6 -0
  11. package/lib/cdp/tabs.js +10 -0
  12. package/lib/cli/args.d.ts +14 -0
  13. package/lib/cli/args.js +19 -0
  14. package/lib/cli/commands.d.ts +1 -0
  15. package/lib/cli/commands.js +19 -0
  16. package/lib/cli.d.ts +1 -0
  17. package/lib/cli.js +7 -0
  18. package/lib/config/store.d.ts +45 -0
  19. package/lib/config/store.js +46 -0
  20. package/lib/index.d.ts +3 -0
  21. package/lib/index.js +7 -0
  22. package/lib/logger.d.ts +2 -0
  23. package/lib/logger.js +7 -0
  24. package/lib/mcp/api/operations.gen.d.ts +152 -0
  25. package/lib/mcp/api/operations.gen.js +2300 -0
  26. package/lib/mcp/api/tools.d.ts +3 -0
  27. package/lib/mcp/api/tools.js +36 -0
  28. package/lib/mcp/remap_errors.d.ts +2 -0
  29. package/lib/mcp/remap_errors.js +27 -0
  30. package/lib/mcp/server.d.ts +38 -0
  31. package/lib/mcp/server.js +76 -0
  32. package/lib/mcp/start.d.ts +1 -0
  33. package/lib/mcp/start.js +63 -0
  34. package/lib/mcp/tools/agent/analyze.d.ts +3 -0
  35. package/lib/mcp/tools/agent/analyze.js +26 -0
  36. package/lib/mcp/tools/agent/attach.d.ts +11 -0
  37. package/lib/mcp/tools/agent/attach.js +72 -0
  38. package/lib/mcp/tools/agent/build.d.ts +33 -0
  39. package/lib/mcp/tools/agent/build.js +74 -0
  40. package/lib/mcp/tools/agent/capture.d.ts +10 -0
  41. package/lib/mcp/tools/agent/capture.js +142 -0
  42. package/lib/mcp/tools/agent/eval.d.ts +5 -0
  43. package/lib/mcp/tools/agent/eval.js +127 -0
  44. package/lib/mcp/tools/agent/find.d.ts +3 -0
  45. package/lib/mcp/tools/agent/find.js +60 -0
  46. package/lib/mcp/tools/agent/proof.d.ts +3 -0
  47. package/lib/mcp/tools/agent/proof.js +214 -0
  48. package/lib/mcp/tools/agent/propose.d.ts +9 -0
  49. package/lib/mcp/tools/agent/propose.js +75 -0
  50. package/lib/mcp/tools/agent/publish.d.ts +3 -0
  51. package/lib/mcp/tools/agent/publish.js +122 -0
  52. package/lib/mcp/tools/agent/replay.d.ts +3 -0
  53. package/lib/mcp/tools/agent/replay.js +46 -0
  54. package/lib/mcp/tools/agent/session.d.ts +10 -0
  55. package/lib/mcp/tools/agent/session.js +29 -0
  56. package/lib/mcp/tools/credentials/authenticate.d.ts +3 -0
  57. package/lib/mcp/tools/credentials/authenticate.js +108 -0
  58. package/lib/mcp/tools/credentials/build.d.ts +16 -0
  59. package/lib/mcp/tools/credentials/build.js +33 -0
  60. package/lib/mcp/tools/credentials/cache.d.ts +70 -0
  61. package/lib/mcp/tools/credentials/cache.js +114 -0
  62. package/lib/mcp/tools/credentials/env-file.d.ts +25 -0
  63. package/lib/mcp/tools/credentials/env-file.js +71 -0
  64. package/lib/mcp/tools/credentials/import.d.ts +2 -0
  65. package/lib/mcp/tools/credentials/import.js +52 -0
  66. package/lib/mcp/tools/credentials/issue.d.ts +2 -0
  67. package/lib/mcp/tools/credentials/issue.js +84 -0
  68. package/lib/mcp/tools/credentials/list-cached.d.ts +2 -0
  69. package/lib/mcp/tools/credentials/list-cached.js +55 -0
  70. package/lib/mcp/tools/credentials/register.d.ts +18 -0
  71. package/lib/mcp/tools/credentials/register.js +30 -0
  72. package/lib/mcp/tools/credentials/resolve-owner-key.d.ts +12 -0
  73. package/lib/mcp/tools/credentials/resolve-owner-key.js +68 -0
  74. package/lib/mcp/tools/credentials/session-cache.d.ts +14 -0
  75. package/lib/mcp/tools/credentials/session-cache.js +19 -0
  76. package/lib/mcp/tools/credentials/status.d.ts +3 -0
  77. package/lib/mcp/tools/credentials/status.js +62 -0
  78. package/lib/mcp-bin.d.ts +1 -0
  79. package/lib/mcp-bin.js +7 -0
  80. package/lib/old/client.d.ts +67 -0
  81. package/lib/old/client.js +146 -0
  82. package/lib/old/flag.d.ts +11 -0
  83. package/lib/old/flag.js +13 -0
  84. package/lib/old/identity.d.ts +22 -0
  85. package/lib/old/identity.js +47 -0
  86. package/lib/old/instructions.d.ts +7 -0
  87. package/lib/old/instructions.js +29 -0
  88. package/lib/old/login-cdp.d.ts +23 -0
  89. package/lib/old/login-cdp.js +125 -0
  90. package/lib/old/to-register.d.ts +47 -0
  91. package/lib/old/to-register.js +133 -0
  92. package/lib/old/tools/authenticate.d.ts +18 -0
  93. package/lib/old/tools/authenticate.js +127 -0
  94. package/lib/old/tools/build.d.ts +9 -0
  95. package/lib/old/tools/build.js +16 -0
  96. package/lib/old/tools/me-providers.d.ts +10 -0
  97. package/lib/old/tools/me-providers.js +32 -0
  98. package/lib/old/tools/publish.d.ts +16 -0
  99. package/lib/old/tools/publish.js +97 -0
  100. package/lib/paths.d.ts +11 -0
  101. package/lib/paths.js +32 -0
  102. package/lib/pkg.d.ts +3 -0
  103. package/lib/pkg.js +13 -0
  104. package/lib/proof/attestor.d.ts +39 -0
  105. package/lib/proof/attestor.js +207 -0
  106. package/lib/proof/replay.d.ts +8 -0
  107. package/lib/proof/replay.js +73 -0
  108. package/lib/provider/constraints.d.ts +2 -0
  109. package/lib/provider/constraints.js +122 -0
  110. package/lib/provider/draft.d.ts +6 -0
  111. package/lib/provider/draft.js +68 -0
  112. package/lib/provider/graphql.d.ts +2 -0
  113. package/lib/provider/graphql.js +35 -0
  114. package/lib/provider/matcher.d.ts +36 -0
  115. package/lib/provider/matcher.js +436 -0
  116. package/lib/provider/normalize.d.ts +4 -0
  117. package/lib/provider/normalize.js +51 -0
  118. package/lib/provider/schema.d.ts +76 -0
  119. package/lib/provider/schema.js +1 -0
  120. package/lib/provider/secrets.d.ts +5 -0
  121. package/lib/provider/secrets.js +22 -0
  122. package/lib/provider/to-version.d.ts +22 -0
  123. package/lib/provider/to-version.js +68 -0
  124. package/lib/types/openapi.d.ts +4 -0
  125. package/lib/types/openapi.js +1 -0
  126. package/package.json +88 -0
  127. package/scripts/download-zk-files.ts +42 -0
  128. package/scripts/prepend-shebang.ts +17 -0
  129. package/skill/SKILL.md +248 -0
  130. package/src/cdp/capture.ts +215 -0
  131. package/src/cdp/client.ts +20 -0
  132. package/src/cdp/eviction.ts +52 -0
  133. package/src/cdp/launcher.ts +133 -0
  134. package/src/cdp/tabs.ts +22 -0
  135. package/src/cli/args.ts +20 -0
  136. package/src/cli/commands.ts +27 -0
  137. package/src/cli.ts +7 -0
  138. package/src/config/store.ts +86 -0
  139. package/src/index.ts +12 -0
  140. package/src/logger.ts +8 -0
  141. package/src/mcp/api/operations.gen.ts +2397 -0
  142. package/src/mcp/api/tools.ts +45 -0
  143. package/src/mcp/remap_errors.ts +35 -0
  144. package/src/mcp/server.ts +119 -0
  145. package/src/mcp/start.ts +78 -0
  146. package/src/mcp/tools/agent/analyze.ts +34 -0
  147. package/src/mcp/tools/agent/attach.ts +95 -0
  148. package/src/mcp/tools/agent/build.ts +99 -0
  149. package/src/mcp/tools/agent/capture.ts +202 -0
  150. package/src/mcp/tools/agent/eval.ts +161 -0
  151. package/src/mcp/tools/agent/find.ts +73 -0
  152. package/src/mcp/tools/agent/proof.ts +272 -0
  153. package/src/mcp/tools/agent/propose.ts +111 -0
  154. package/src/mcp/tools/agent/publish.ts +155 -0
  155. package/src/mcp/tools/agent/replay.ts +58 -0
  156. package/src/mcp/tools/agent/session.ts +46 -0
  157. package/src/mcp/tools/credentials/authenticate.ts +135 -0
  158. package/src/mcp/tools/credentials/build.ts +37 -0
  159. package/src/mcp/tools/credentials/cache.ts +161 -0
  160. package/src/mcp/tools/credentials/env-file.ts +101 -0
  161. package/src/mcp/tools/credentials/import.ts +72 -0
  162. package/src/mcp/tools/credentials/issue.ts +107 -0
  163. package/src/mcp/tools/credentials/list-cached.ts +66 -0
  164. package/src/mcp/tools/credentials/register.ts +49 -0
  165. package/src/mcp/tools/credentials/resolve-owner-key.ts +78 -0
  166. package/src/mcp/tools/credentials/session-cache.ts +31 -0
  167. package/src/mcp/tools/credentials/status.ts +82 -0
  168. package/src/mcp-bin.ts +7 -0
  169. package/src/old/client.ts +236 -0
  170. package/src/old/flag.ts +13 -0
  171. package/src/old/identity.ts +56 -0
  172. package/src/old/instructions.ts +30 -0
  173. package/src/old/login-cdp.ts +153 -0
  174. package/src/old/to-register.ts +234 -0
  175. package/src/old/tools/authenticate.ts +152 -0
  176. package/src/old/tools/build.ts +21 -0
  177. package/src/old/tools/me-providers.ts +42 -0
  178. package/src/old/tools/publish.ts +135 -0
  179. package/src/paths.ts +37 -0
  180. package/src/pkg.ts +24 -0
  181. package/src/proof/attestor.ts +286 -0
  182. package/src/proof/replay.ts +102 -0
  183. package/src/provider/constraints.ts +150 -0
  184. package/src/provider/draft.ts +105 -0
  185. package/src/provider/graphql.ts +42 -0
  186. package/src/provider/matcher.ts +616 -0
  187. package/src/provider/normalize.ts +65 -0
  188. package/src/provider/schema.ts +92 -0
  189. package/src/provider/secrets.ts +29 -0
  190. package/src/provider/to-version.ts +90 -0
  191. package/src/types/openapi.ts +7 -0
@@ -0,0 +1,202 @@
1
+ import { type CaptureSession, startCapture } from '../../../cdp/capture.ts'
2
+ import { defineTool, type RegisteredTool } from '../../server.ts'
3
+ import type { AttachState } from './attach.ts'
4
+
5
+ export interface CaptureStore {
6
+ sessions: Map<string, CaptureSession>
7
+ activeTab?: string
8
+ }
9
+
10
+ export function captureTools(
11
+ attachRef: { current?: AttachState },
12
+ captures: CaptureStore,
13
+ ): RegisteredTool[] {
14
+ const requireAttached = (): AttachState => {
15
+ if(!attachRef.current) {
16
+ throw new Error('Not attached. Call attach_chrome first.')
17
+ }
18
+
19
+ return attachRef.current
20
+ }
21
+
22
+ const startTool = defineTool<{ tabId: string }>(
23
+ {
24
+ name: 'start_capture',
25
+ description:
26
+ 'Begin recording network requests on the specified tab. ' +
27
+ 'Returns a captureId.',
28
+ inputSchema: {
29
+ type: 'object',
30
+ properties: { tabId: { type: 'string' } },
31
+ required: ['tabId'],
32
+ },
33
+ },
34
+ async({ tabId }) => {
35
+ const attached = requireAttached()
36
+ const tabClient = await attached.handles.attachToTab(tabId)
37
+ const session = await startCapture(tabClient)
38
+ captures.sessions.set(session.captureId, session)
39
+ captures.activeTab = tabId
40
+ return { captureId: session.captureId }
41
+ },
42
+ )
43
+
44
+ const stopTool = defineTool<{ captureId: string }>(
45
+ {
46
+ name: 'stop_capture',
47
+ description:
48
+ 'Stop recording on the given capture. ' +
49
+ 'Captured data remains queryable until reset_session.',
50
+ inputSchema: {
51
+ type: 'object',
52
+ properties: { captureId: { type: 'string' } },
53
+ required: ['captureId'],
54
+ },
55
+ },
56
+ async({ captureId }) => {
57
+ const session = captures.sessions.get(captureId)
58
+ if(!session) {
59
+ throw new Error(`no capture ${captureId}`)
60
+ }
61
+
62
+ await session.stop()
63
+ return { stopped: true, requestCount: session.requests.size }
64
+ },
65
+ )
66
+
67
+ const listTool = defineTool<{
68
+ captureId: string
69
+ filter?: {
70
+ method?: string
71
+ urlGlob?: string
72
+ statusMin?: number
73
+ statusMax?: number
74
+ contentType?: string
75
+ graphqlOp?: string
76
+ }
77
+ }>(
78
+ {
79
+ name: 'list_requests',
80
+ description:
81
+ 'List metadata for captured requests. ' +
82
+ 'Filter by method, URL glob, status, content-type, ' +
83
+ 'or graphqlOp. Returns only metadata, never bodies — ' +
84
+ 'use get_request for those.',
85
+ inputSchema: {
86
+ type: 'object',
87
+ properties: {
88
+ captureId: { type: 'string' },
89
+ filter: {
90
+ type: 'object',
91
+ properties: {
92
+ method: { type: 'string' },
93
+ urlGlob: { type: 'string' },
94
+ statusMin: { type: 'number' },
95
+ statusMax: { type: 'number' },
96
+ contentType: { type: 'string' },
97
+ graphqlOp: { type: 'string' },
98
+ },
99
+ },
100
+ },
101
+ required: ['captureId'],
102
+ },
103
+ },
104
+ async({ captureId, filter }) => {
105
+ const session = captures.sessions.get(captureId)
106
+ if(!session) {
107
+ throw new Error(`no capture ${captureId}`)
108
+ }
109
+
110
+ const out = []
111
+ for(const r of session.requests.values()) {
112
+ if(filter?.method && r.method !== filter.method.toUpperCase()) {
113
+ continue
114
+ }
115
+
116
+ if(filter?.urlGlob && !globMatch(filter.urlGlob, r.url)) {
117
+ continue
118
+ }
119
+
120
+ if(filter?.statusMin !== undefined && r.status < filter.statusMin) {
121
+ continue
122
+ }
123
+
124
+ if(filter?.statusMax !== undefined && r.status > filter.statusMax) {
125
+ continue
126
+ }
127
+
128
+ if(
129
+ filter?.contentType &&
130
+ !r.contentType.includes(filter.contentType)
131
+ ) {
132
+ continue
133
+ }
134
+
135
+ if(filter?.graphqlOp && r.graphqlOp !== filter.graphqlOp) {
136
+ continue
137
+ }
138
+
139
+ const item: Record<string, unknown> = {
140
+ requestId: r.requestId,
141
+ method: r.method,
142
+ url: r.url,
143
+ status: r.status,
144
+ contentType: r.contentType,
145
+ size: r.size,
146
+ }
147
+ if(r.graphqlOp !== undefined) {
148
+ item.graphqlOp = r.graphqlOp
149
+ }
150
+
151
+ out.push(item)
152
+ }
153
+
154
+ return { requests: out }
155
+ },
156
+ )
157
+
158
+ const getTool = defineTool<{ captureId: string, requestId: string }>(
159
+ {
160
+ name: 'get_request',
161
+ description:
162
+ 'Return full headers + bodies for a specific captured request.',
163
+ inputSchema: {
164
+ type: 'object',
165
+ properties: {
166
+ captureId: { type: 'string' },
167
+ requestId: { type: 'string' },
168
+ },
169
+ required: ['captureId', 'requestId'],
170
+ },
171
+ },
172
+ async({ captureId, requestId }) => {
173
+ const session = captures.sessions.get(captureId)
174
+ if(!session) {
175
+ throw new Error(`no capture ${captureId}`)
176
+ }
177
+
178
+ const r = session.requests.get(requestId)
179
+ if(!r) {
180
+ throw new Error(`no request ${requestId} in capture ${captureId}`)
181
+ }
182
+
183
+ const body = session.bodies.get(requestId)
184
+ if(!body.available) {
185
+ return { ...r, bodyAvailable: false, reason: body.reason }
186
+ }
187
+
188
+ return { ...r, responseBody: body.body, bodyAvailable: true }
189
+ },
190
+ )
191
+
192
+ return [startTool, stopTool, listTool, getTool]
193
+ }
194
+
195
+ function globMatch(pattern: string, str: string): boolean {
196
+ const re = new RegExp(
197
+ '^' +
198
+ pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*') +
199
+ '$',
200
+ )
201
+ return re.test(str)
202
+ }
@@ -0,0 +1,161 @@
1
+ import { listTabs } from '../../../cdp/tabs.ts'
2
+ import { defineTool, type RegisteredTool } from '../../server.ts'
3
+ import type { AttachState } from './attach.ts'
4
+
5
+ export function browserTools(attachRef: {
6
+ current?: AttachState
7
+ }): RegisteredTool[] {
8
+ const requireAttached = (): AttachState => {
9
+ if(!attachRef.current) {
10
+ throw new Error('Not attached. Call attach_chrome first.')
11
+ }
12
+
13
+ return attachRef.current
14
+ }
15
+
16
+ return [
17
+ defineTool<Record<string, never>>(
18
+ {
19
+ name: 'list_tabs',
20
+ description: 'List open Chrome tabs.',
21
+ inputSchema: { type: 'object', properties: {} },
22
+ },
23
+ async() => {
24
+ const attached = requireAttached()
25
+ return { tabs: await listTabs(attached.port) }
26
+ },
27
+ ),
28
+ defineTool<{ tabId: string, expression: string }>(
29
+ {
30
+ name: 'eval_in_page',
31
+ description:
32
+ 'Run a JS expression in a tab via Runtime.evaluate ' +
33
+ 'and return the result. ' +
34
+ 'Useful for reading visible values from the DOM.',
35
+ inputSchema: {
36
+ type: 'object',
37
+ properties: {
38
+ tabId: { type: 'string' },
39
+ expression: { type: 'string' },
40
+ },
41
+ required: ['tabId', 'expression'],
42
+ },
43
+ },
44
+ async({ tabId, expression }) => {
45
+ const attached = requireAttached()
46
+ const { Runtime } = await attached.handles.attachToTab(tabId)
47
+ const result = await Runtime.evaluate({
48
+ expression,
49
+ returnByValue: true,
50
+ })
51
+ if(result.exceptionDetails) {
52
+ return { error: result.exceptionDetails.text }
53
+ }
54
+
55
+ return { value: result.result.value }
56
+ },
57
+ ),
58
+ defineTool<{ tabId: string, url: string, timeoutMs?: number }>(
59
+ {
60
+ name: 'navigate',
61
+ description:
62
+ 'Navigate a tab to a URL via Page.navigate, ' +
63
+ 'waiting for the load event. ' +
64
+ 'Use this to drive the browser yourself ' +
65
+ 'instead of asking the developer to navigate. ' +
66
+ 'Returns the final URL after navigation ' +
67
+ '(which may differ from the requested URL due to redirects).',
68
+ inputSchema: {
69
+ type: 'object',
70
+ properties: {
71
+ tabId: { type: 'string' },
72
+ url: { type: 'string' },
73
+ timeoutMs: { type: 'number' },
74
+ },
75
+ required: ['tabId', 'url'],
76
+ },
77
+ },
78
+ async({ tabId, url, timeoutMs }) => {
79
+ const attached = requireAttached()
80
+ const { Page, Runtime } = await attached.handles.attachToTab(tabId)
81
+
82
+ await Page.enable()
83
+ const loadPromise = new Promise<void>((resolve) => {
84
+ Page.loadEventFired(() => resolve())
85
+ })
86
+ const nav = await Page.navigate({ url })
87
+ if(nav.errorText) {
88
+ return { ok: false, error: nav.errorText }
89
+ }
90
+
91
+ const t = timeoutMs ?? 30_000
92
+ const raced = await Promise.race([
93
+ loadPromise.then(() => 'loaded' as const),
94
+ new Promise<'timeout'>(
95
+ (resolve) => setTimeout(() => resolve('timeout'), t),
96
+ ),
97
+ ])
98
+ const final = await Runtime.evaluate({
99
+ expression: 'location.href',
100
+ returnByValue: true,
101
+ })
102
+ return {
103
+ ok: true,
104
+ loadStatus: raced,
105
+ finalUrl: final.result.value,
106
+ }
107
+ },
108
+ ),
109
+ defineTool<{
110
+ tabId: string
111
+ expression: string
112
+ timeoutMs?: number
113
+ pollMs?: number
114
+ }>(
115
+ {
116
+ name: 'wait_for_page',
117
+ description:
118
+ 'Poll a JS expression in a tab until it ' +
119
+ 'returns truthy (or timeout). ' +
120
+ 'Use this for steps that require the ' +
121
+ 'developer to do something in the browser — ' +
122
+ 'most commonly waiting for them to finish logging in. ' +
123
+ 'Pass an expression that ' +
124
+ 'evaluates true once the desired state is reached, e.g. ' +
125
+ '`!!document.querySelector' +
126
+ '(\'summary[aria-label*="View profile"]\')`' +
127
+ ' for GitHub post-login.',
128
+ inputSchema: {
129
+ type: 'object',
130
+ properties: {
131
+ tabId: { type: 'string' },
132
+ expression: { type: 'string' },
133
+ timeoutMs: { type: 'number' },
134
+ pollMs: { type: 'number' },
135
+ },
136
+ required: ['tabId', 'expression'],
137
+ },
138
+ },
139
+ async({ tabId, expression, timeoutMs, pollMs }) => {
140
+ const attached = requireAttached()
141
+ const { Runtime } = await attached.handles.attachToTab(tabId)
142
+ const deadline = Date.now() + (timeoutMs ?? 120_000)
143
+ const interval = pollMs ?? 1000
144
+ while(Date.now() < deadline) {
145
+ const r = await Runtime.evaluate({ expression, returnByValue: true })
146
+ if(r.exceptionDetails) {
147
+ return { matched: false, error: r.exceptionDetails.text }
148
+ }
149
+
150
+ if(r.result.value) {
151
+ return { matched: true, value: r.result.value }
152
+ }
153
+
154
+ await new Promise((resolve) => setTimeout(resolve, interval))
155
+ }
156
+
157
+ return { matched: false, reason: 'timeout' }
158
+ },
159
+ ),
160
+ ]
161
+ }
@@ -0,0 +1,73 @@
1
+ import { normalizeCandidates } from '../../../provider/normalize.ts'
2
+ import { defineTool, type RegisteredTool } from '../../server.ts'
3
+ import type { CaptureStore } from './capture.ts'
4
+
5
+ export function findTool(captures: CaptureStore): RegisteredTool {
6
+ return defineTool<{ captureId: string, value: string, limit?: number }>(
7
+ {
8
+ name: 'find_requests_containing',
9
+ description:
10
+ 'Search captured responses for any encoding of `value`.' +
11
+ 'Returns a ranked candidate list ' +
12
+ 'with the JSON path (when applicable), score, and a short snippet.' +
13
+ 'Server-side; bodies stay here.',
14
+ inputSchema: {
15
+ type: 'object',
16
+ properties: {
17
+ captureId: { type: 'string' },
18
+ value: { type: 'string' },
19
+ limit: { type: 'number' },
20
+ },
21
+ required: ['captureId', 'value'],
22
+ },
23
+ },
24
+ async({ captureId, value, limit }) => {
25
+ const session = captures.sessions.get(captureId)
26
+ if(!session) {
27
+ throw new Error(`no capture ${captureId}`)
28
+ }
29
+
30
+ const variants = normalizeCandidates(value)
31
+
32
+ const ranked = []
33
+ for(const r of session.requests.values()) {
34
+ if(!r.responseBody) {
35
+ continue
36
+ }
37
+
38
+ let hit: { snippet: string, variant: string } | undefined
39
+ for(const v of variants) {
40
+ const idx = r.responseBody.indexOf(v)
41
+ if(idx >= 0) {
42
+ const start = Math.max(0, idx - 40)
43
+ const end = Math.min(r.responseBody.length, idx + v.length + 40)
44
+ hit = { snippet: r.responseBody.slice(start, end), variant: v }
45
+ break
46
+ }
47
+ }
48
+
49
+ if(!hit) {
50
+ continue
51
+ }
52
+
53
+ // Score: prefer JSON responses + smaller bodies (likely API endpoints).
54
+ const score =
55
+ (r.contentType.includes('json') ? 10 : 0) +
56
+ Math.max(0, 5 - Math.log10(Math.max(r.size, 1)))
57
+ ranked.push({
58
+ requestId: r.requestId,
59
+ url: r.url,
60
+ method: r.method,
61
+ status: r.status,
62
+ contentType: r.contentType,
63
+ matchedVariant: hit.variant,
64
+ snippet: hit.snippet,
65
+ score,
66
+ })
67
+ }
68
+
69
+ ranked.sort((a, b) => b.score - a.score)
70
+ return { candidates: ranked.slice(0, limit ?? 10) }
71
+ },
72
+ )
73
+ }
@@ -0,0 +1,272 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+ import { reclaimHomeDirPath } from '../../../paths.ts'
4
+ import {
5
+ runAttestorProof,
6
+ tailLogs,
7
+ warnsAndErrors,
8
+ } from '../../../proof/attestor.ts'
9
+ import type { ReclaimProvider } from '../../../provider/schema.ts'
10
+ import { defineTool, type RegisteredTool } from '../../server.ts'
11
+ import type { SecretStore } from './propose.ts'
12
+
13
+ function claimsDir(): string {
14
+ return join(reclaimHomeDirPath(), 'claims')
15
+ }
16
+
17
+ function proofRunsDir(): string {
18
+ return join(reclaimHomeDirPath(), 'proof-runs')
19
+ }
20
+
21
+ /** Persist everything we know about this proof attempt — input provider,
22
+ * sentParams the SDK saw, full captured logs, and the final result — to
23
+ * a file the dev can `cat` directly. This is the source of truth when
24
+ * the LLM's summary disagrees with reality. */
25
+ function writeProofRunDump(payload: {
26
+ provider: unknown
27
+ hasSecretParamsRef: boolean
28
+ attestorUrl?: string
29
+ result: Record<string, unknown>
30
+ }): string | undefined {
31
+ try {
32
+ mkdirSync(proofRunsDir(), { recursive: true })
33
+ const path = join(proofRunsDir(), `${Date.now()}.json`)
34
+ writeFileSync(path, JSON.stringify(payload, null, 2), 'utf8')
35
+ return path
36
+ } catch{
37
+ // Persistence is best-effort; never fail the proof for it.
38
+ return undefined
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Walk a claim object for display:
44
+ * - drop any `request` field at any depth (it's huge and only useful
45
+ * for low-level debugging — the on-disk claim still has it)
46
+ * - convert byte-like values (Uint8Array, or arrays where every entry
47
+ * is a number in [0,255]) to base64 strings so they render as
48
+ * readable text instead of `{"0":12,"1":34,...}`
49
+ *
50
+ * The on-disk file at claimPath is the raw, unprettified claim — this
51
+ * function only affects what we return in the MCP tool response.
52
+ */
53
+ function prettifyClaim(value: unknown): unknown {
54
+ if(value === null || value === undefined) {
55
+ return value
56
+ }
57
+
58
+ if(value instanceof Uint8Array) {
59
+ return Buffer.from(value).toString('base64')
60
+ }
61
+
62
+ if(Array.isArray(value)) {
63
+ if(isLikelyByteArray(value)) {
64
+ return Buffer.from(value as number[]).toString('base64')
65
+ }
66
+
67
+ return value.map(prettifyClaim)
68
+ }
69
+
70
+ if(typeof value === 'object') {
71
+ const out: Record<string, unknown> = {}
72
+ for(const [k, v] of Object.entries(value as Record<string, unknown>)) {
73
+ if(k === 'request') {
74
+ continue
75
+ }
76
+
77
+ out[k] = prettifyClaim(v)
78
+ }
79
+
80
+ return out
81
+ }
82
+
83
+ return value
84
+ }
85
+
86
+ function isLikelyByteArray(v: unknown[]): boolean {
87
+ if(v.length === 0) {
88
+ return false
89
+ }
90
+
91
+ for(const x of v) {
92
+ if(typeof x !== 'number' || !Number.isInteger(x) || x < 0 || x > 255) {
93
+ return false
94
+ }
95
+ }
96
+
97
+ return true
98
+ }
99
+
100
+ export function proofTool(secrets: SecretStore): RegisteredTool {
101
+ return defineTool<{
102
+ provider: unknown
103
+ secretParamsRef?: string
104
+ attestorUrl?: string
105
+ ownerAddress?: string
106
+ }>(
107
+ {
108
+ name: 'run_proof',
109
+ description:
110
+ 'Run a full zkTLS proof through the Reclaim attestor SDK. ' +
111
+ 'Use only after replay_request ' +
112
+ 'returns matchesOriginal=true — attestor calls are expensive. ' +
113
+ 'Writes the full claim to ' +
114
+ '~/.reclaim/claims/<timestamp>.json and ' +
115
+ 'returns identifier + extractedParameters + ' +
116
+ 'claimPath + a prettified `claim` field ' +
117
+ '(request dropped, byte arrays as base64) suitable ' +
118
+ 'for displaying directly to the dev. ' +
119
+ 'When the MCP server is started with ' +
120
+ '`RECLAIM_AGENT_TRACE=1`, ALSO writes ' +
121
+ 'a per-call diagnostic dump (input provider, ' +
122
+ 'sentParams the SDK saw post-substitution, ' +
123
+ 'FULL attestor log stream, result) to ' +
124
+ '~/.reclaim/proof-runs/<timestamp>.json and ' +
125
+ 'returns the path as `runLogPath`. ' +
126
+ '`attestorUrl` overrides the default attestor URL only when the dev ' +
127
+ 'supplies a specific ' +
128
+ 'alternative — do NOT invent backup URLs ' +
129
+ '(there is one live public attestor right now; ' +
130
+ 'surface real errors to the dev instead of guessing). ' +
131
+ '`ownerAddress` (the credential to sign with) is REQUIRED — ' +
132
+ 'call resolve_owner_key first to obtain it, then pass it here. ' +
133
+ 'errorKind="missing-owner-key" means that address has no known ' +
134
+ 'private key; re-run resolve_owner_key or issue/import a credential.',
135
+ inputSchema: {
136
+ type: 'object',
137
+ properties: {
138
+ // `type: 'object'` is required so MCP clients (the LLM)
139
+ // serialize the value as an object, not a JSON-stringified
140
+ // string. `properties: {}` is required so zod-from-json-schema
141
+ // compiles to a passthrough instead of strict-strip — leaving
142
+ // it off makes the server receive `{}`.
143
+ provider: { type: 'object', properties: {} },
144
+ secretParamsRef: { type: 'string' },
145
+ attestorUrl: { type: 'string' },
146
+ ownerAddress: {
147
+ type: 'string',
148
+ pattern: '^0x[0-9a-fA-F]{40}$',
149
+ description:
150
+ 'ETH address of the credential to sign the claim with. ' +
151
+ 'Get it from resolve_owner_key first. The private key is ' +
152
+ 'resolved locally (cache / env / .env) — never passed here.',
153
+ },
154
+ },
155
+ required: ['provider', 'ownerAddress'],
156
+ },
157
+ },
158
+ async({ provider, secretParamsRef, attestorUrl, ownerAddress }) => {
159
+ let resolved: Record<string, string> = {}
160
+ if(secretParamsRef !== undefined) {
161
+ const r = secrets.resolve(secretParamsRef)
162
+ if(!r) {
163
+ throw new Error(
164
+ `unknown secretParamsRef "${secretParamsRef}" — ` +
165
+ 'the MCP server has restarted or reset_session was called. ' +
166
+ 'Re-run propose_provider to mint a fresh ref.',
167
+ )
168
+ }
169
+
170
+ resolved = r
171
+ }
172
+
173
+ const result = await runAttestorProof(
174
+ provider as ReclaimProvider,
175
+ resolved,
176
+ attestorUrl,
177
+ ownerAddress,
178
+ )
179
+
180
+ // Persist the full claim to disk for the dev to inspect/share.
181
+ let claimPath: string | undefined
182
+ if(result.proof !== undefined && result.proof !== null) {
183
+ try {
184
+ mkdirSync(claimsDir(), { recursive: true })
185
+ claimPath = join(claimsDir(), `${Date.now()}.json`)
186
+ writeFileSync(
187
+ claimPath,
188
+ JSON.stringify(result.proof, null, 2),
189
+ 'utf8',
190
+ )
191
+ } catch{
192
+ // Persistence is best-effort; don't fail the proof for it.
193
+ claimPath = undefined
194
+ }
195
+ }
196
+
197
+ const out: Record<string, unknown> = {
198
+ verified: result.verified,
199
+ extractedValue: result.extractedValue,
200
+ extractedParameters: result.extractedParameters,
201
+ }
202
+ if(result.identifier !== undefined) {
203
+ out.identifier = result.identifier
204
+ }
205
+
206
+ if(result.owner !== undefined) {
207
+ out.owner = result.owner
208
+ }
209
+
210
+ if(claimPath !== undefined) {
211
+ out.claimPath = claimPath
212
+ }
213
+
214
+ if(result.proof !== undefined && result.proof !== null) {
215
+ out.claim = prettifyClaim(result.proof)
216
+ }
217
+
218
+ if(result.error !== undefined) {
219
+ out.error = result.error
220
+ }
221
+
222
+ if(result.errorKind !== undefined) {
223
+ out.errorKind = result.errorKind
224
+ }
225
+
226
+ // Trim the LLM-visible logs — full stream goes to runLogPath.
227
+ if(result.attestorLogs !== undefined && result.attestorLogs.length > 0) {
228
+ out.attestorLogs = result.verified
229
+ ? warnsAndErrors(result.attestorLogs)
230
+ : tailLogs(result.attestorLogs)
231
+ if((out.attestorLogs as unknown[]).length === 0) {
232
+ delete out.attestorLogs
233
+ }
234
+ }
235
+
236
+ if(result.sentParams !== undefined) {
237
+ out.sentParams = result.sentParams
238
+ }
239
+
240
+ // Persist a diagnostic dump for forensics — gated behind
241
+ // RECLAIM_AGENT_TRACE=1 (matches the attestor logger capture).
242
+ // Off by default since happy-path runs don't need it; turn on
243
+ // when investigating proof failures and the file at runLogPath
244
+ // will carry the input provider, sentParams, full attestor log
245
+ // stream, and result.
246
+ if(process.env['RECLAIM_AGENT_TRACE'] === '1') {
247
+ const runLogPath = writeProofRunDump({
248
+ provider,
249
+ hasSecretParamsRef: secretParamsRef !== undefined,
250
+ attestorUrl,
251
+ result: {
252
+ verified: result.verified,
253
+ error: result.error,
254
+ errorKind: result.errorKind,
255
+ extractedValue: result.extractedValue,
256
+ extractedParameters: result.extractedParameters,
257
+ identifier: result.identifier,
258
+ owner: result.owner,
259
+ sentParams: result.sentParams,
260
+ attestorLogs: result.attestorLogs,
261
+ claimPath,
262
+ },
263
+ })
264
+ if(runLogPath !== undefined) {
265
+ out.runLogPath = runLogPath
266
+ }
267
+ }
268
+
269
+ return out
270
+ },
271
+ )
272
+ }