@wowok/agent-mcp 2.3.13 → 2.3.14

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 (92) hide show
  1. package/dist/harness/checkpoint.d.ts +8 -0
  2. package/dist/harness/checkpoint.js +129 -0
  3. package/dist/harness/index.d.ts +33 -0
  4. package/dist/harness/index.js +75 -0
  5. package/dist/harness/plan.d.ts +18 -0
  6. package/dist/harness/plan.js +252 -0
  7. package/dist/harness/recover.d.ts +17 -0
  8. package/dist/harness/recover.js +139 -0
  9. package/dist/harness/types.d.ts +137 -0
  10. package/dist/harness/types.js +1 -0
  11. package/dist/harness/verify.d.ts +42 -0
  12. package/dist/harness/verify.js +237 -0
  13. package/dist/index.js +134 -52
  14. package/dist/loop-engineering/aggregate.d.ts +50 -0
  15. package/dist/loop-engineering/aggregate.js +132 -0
  16. package/dist/loop-engineering/diagnose.d.ts +21 -0
  17. package/dist/loop-engineering/diagnose.js +179 -0
  18. package/dist/loop-engineering/improve.d.ts +26 -0
  19. package/dist/loop-engineering/improve.js +178 -0
  20. package/dist/loop-engineering/index.d.ts +4 -0
  21. package/dist/loop-engineering/index.js +4 -0
  22. package/dist/loop-engineering/pipeline.d.ts +17 -0
  23. package/dist/loop-engineering/pipeline.js +56 -0
  24. package/dist/mode-market/index.d.ts +3 -0
  25. package/dist/mode-market/index.js +3 -0
  26. package/dist/mode-market/registry.d.ts +53 -0
  27. package/dist/mode-market/registry.js +124 -0
  28. package/dist/mode-market/review.d.ts +27 -0
  29. package/dist/mode-market/review.js +214 -0
  30. package/dist/mode-market/submission.d.ts +25 -0
  31. package/dist/mode-market/submission.js +85 -0
  32. package/dist/schema/call/allocation.d.ts +40 -40
  33. package/dist/schema/call/arbitration.d.ts +90 -90
  34. package/dist/schema/call/base.d.ts +1054 -0
  35. package/dist/schema/call/base.js +100 -22
  36. package/dist/schema/call/bridge-handler.js +36 -18
  37. package/dist/schema/call/bridge.d.ts +115 -115
  38. package/dist/schema/call/handler.d.ts +2 -1
  39. package/dist/schema/call/handler.js +94 -3
  40. package/dist/schema/call/index.d.ts +1 -0
  41. package/dist/schema/call/index.js +1 -0
  42. package/dist/schema/call/machine.d.ts +144 -144
  43. package/dist/schema/call/order.d.ts +12 -12
  44. package/dist/schema/call/progress.d.ts +6 -6
  45. package/dist/schema/call/reward.d.ts +6 -6
  46. package/dist/schema/call/semantic.d.ts +23 -0
  47. package/dist/schema/call/semantic.js +764 -0
  48. package/dist/schema/call/service.d.ts +142 -142
  49. package/dist/schema/call/treasury.d.ts +204 -204
  50. package/dist/schema/local/index.d.ts +113 -2
  51. package/dist/schema/local/index.js +11 -1
  52. package/dist/schema/messenger/index.d.ts +416 -92
  53. package/dist/schema/messenger/index.js +9 -0
  54. package/dist/schema/operations.d.ts +988 -495
  55. package/dist/schema/operations.js +14 -3
  56. package/dist/schema/query/index.d.ts +346 -342
  57. package/dist/schema/query/index.js +4 -1
  58. package/dist/schemas/account_operation.output.json +3 -0
  59. package/dist/schemas/account_operation.schema.json +1 -1
  60. package/dist/schemas/index.json +1 -1
  61. package/dist/schemas/local_info_operation.output.json +3 -0
  62. package/dist/schemas/local_mark_operation.output.json +3 -0
  63. package/dist/schemas/messenger_operation.output.json +21 -0
  64. package/dist/schemas/messenger_operation.schema.json +21 -0
  65. package/dist/schemas/onchain_events.output.json +3 -0
  66. package/dist/schemas/onchain_operations.output.json +464 -21
  67. package/dist/schemas/onchain_operations.schema.json +21 -17
  68. package/dist/schemas/onchain_operations_allocation.schema.json +11 -9
  69. package/dist/schemas/onchain_operations_arbitration.schema.json +11 -9
  70. package/dist/schemas/onchain_operations_contact.schema.json +11 -9
  71. package/dist/schemas/onchain_operations_demand.schema.json +11 -9
  72. package/dist/schemas/onchain_operations_gen_passport.schema.json +21 -17
  73. package/dist/schemas/onchain_operations_guard.schema.json +11 -9
  74. package/dist/schemas/onchain_operations_machine.schema.json +11 -9
  75. package/dist/schemas/onchain_operations_order.schema.json +11 -9
  76. package/dist/schemas/onchain_operations_payment.schema.json +11 -9
  77. package/dist/schemas/onchain_operations_permission.schema.json +11 -9
  78. package/dist/schemas/onchain_operations_personal.schema.json +11 -9
  79. package/dist/schemas/onchain_operations_progress.schema.json +11 -9
  80. package/dist/schemas/onchain_operations_repository.schema.json +11 -9
  81. package/dist/schemas/onchain_operations_reward.schema.json +11 -9
  82. package/dist/schemas/onchain_operations_service.schema.json +11 -9
  83. package/dist/schemas/onchain_operations_treasury.schema.json +11 -9
  84. package/dist/schemas/onchain_table_data.output.json +3 -0
  85. package/dist/schemas/query_toolkit.schema.json +5 -1
  86. package/dist/telemetry/index.d.ts +19 -0
  87. package/dist/telemetry/index.js +112 -0
  88. package/dist/telemetry/redact.d.ts +2 -0
  89. package/dist/telemetry/redact.js +23 -0
  90. package/dist/telemetry/storage.d.ts +8 -0
  91. package/dist/telemetry/storage.js +80 -0
  92. package/package.json +6 -3
@@ -75,24 +75,74 @@ export const ObjectsOpSchema = z.union([
75
75
  }).describe("Remove all objects."),
76
76
  ]).describe("Operate object list. Used to set, add, or remove objects.");
77
77
  export const ResponseDataSchema = ObjectBaseSchema.extend({
78
- change: z.union([z.literal("created"), z.literal("mutated"), z.string()]),
79
- }).describe("Call result data. Contains basic object information and change type.");
78
+ change: z.union([z.literal("created"), z.literal("mutated"), z.string()]).describe("What happened to this object in the operation. Constraint: 'created' | 'mutated' | custom string. Example: 'created'"),
79
+ }).describe("One object record in a query result. Contains the object's basic info plus how it changed in this operation.");
80
+ export const ObjectRoleSchema = z.object({
81
+ id: z.string().describe("Object ID (64-hex with 0x prefix). Identifies the on-chain object. Example: '0xa1d4...'"),
82
+ name: z.union([z.string(), z.null()]).optional().describe("Local mark name if assigned, else null. Relation: resolved via local_mark_operation. Example: 'my-shop' or null"),
83
+ role: z.enum([
84
+ "Permission", "Guard", "Machine", "Progress", "Service", "Order", "Allocation",
85
+ "Arbitration", "ArbCase", "Messenger", "Contact", "Demand", "Reward", "Personal",
86
+ "Repository", "Treasury", "Discount", "Other"
87
+ ]).describe("Business role of the object in the dependency graph. Constraint: enum of 18 values. Relation: derived from objectType last segment; drives Plan/Verify Loop positioning. Example: 'Service'"),
88
+ relation: z.object({
89
+ parent: z.union([z.string(), z.null()]).optional().describe("Parent object ID, if this object belongs to another (e.g. Machine belongs to Service). Example: '0x123...' or null"),
90
+ relation_type: z.enum(["machine_of", "guard_of", "allocator_of", "permission_of", "progress_of", "allocation_of", "arb_of", "other"]).optional().describe("How this object relates to its parent. Example: 'machine_of'"),
91
+ }).optional().describe("Relationship to another object in the dependency graph"),
92
+ immutable: z.boolean().optional().describe("Whether the object has entered an immutable state (e.g. Service published). Constraint: true after publish. Example: true"),
93
+ }).strict().describe("An object tagged with its business role and relationship within the object dependency graph");
94
+ export const FundRoleSchema = z.object({
95
+ amount: z.string().describe("Amount change as stringified integer (smallest unit). Negative=spend, positive=receive. Example: '-10000000000'"),
96
+ coinType: z.string().describe("Coin type tag (format: {address}::{module}::{struct}). Example: '0x2::wow::WOW'"),
97
+ role: z.enum(["payment", "refund", "change", "compensation", "reward", "gas", "deposit", "release", "other"]).describe("Business role of this fund movement. Constraint: enum of 9 values. Relation: derived from operation context. Example: 'payment'"),
98
+ from: z.string().nullable().optional().describe("Sender address if known. Example: '0xabc...' or null"),
99
+ to: z.string().nullable().optional().describe("Recipient address if known. Example: '0xdef...' or null"),
100
+ }).strict().describe("A fund movement tagged with its business role");
101
+ export const NextActionSchema = z.object({
102
+ action: z.string().describe("Recommended next action. Example: 'add sales products'"),
103
+ reason: z.string().describe("Why this action is recommended. Example: 'Service has no products; customers cannot order'"),
104
+ tool: z.string().optional().describe("MCP tool to use, if applicable. Example: 'onchain_operations'"),
105
+ prerequisite: z.string().optional().describe("Condition that must hold before this action. Example: 'Service must be created first'"),
106
+ priority: z.enum(["required", "recommended", "optional"]).describe("Priority. Constraint: enum. Example: 'required'"),
107
+ }).strict().describe("A recommended next action with priority and rationale");
108
+ export const EventSemanticSchema = z.object({
109
+ event_type: z.string().describe("Raw on-chain event type tag. Example: '0x2::service::ServicePublishedEvent'"),
110
+ business_meaning: z.string().describe("Human-readable business meaning. Example: 'Service has been published and is now immutable'"),
111
+ category: z.enum(["lifecycle", "state_change", "fund_flow", "permission", "guard", "other"]).describe("Business category. Constraint: enum of 6 values. Example: 'lifecycle'"),
112
+ related_object: z.string().optional().describe("Object ID the event relates to, if extractable. Example: '0x123...'"),
113
+ side_effect: z.string().optional().describe("Side effect description for AI. Example: 'Customers can now place orders against this Service'"),
114
+ }).strict().describe("An on-chain event annotated with business semantics");
115
+ export const SemanticSummarySchema = z.object({
116
+ intent: z.string().describe("Inferred user intent / operation goal. Constraint: snake_case string. Relation: derived from operation_type + data signals. Example: 'publish_service'"),
117
+ status: z.enum(["success", "partial", "failed", "pending_input"]).describe("Business-level status (not raw tx status). 'pending_input' = needs Guard submission. Example: 'success'"),
118
+ summary: z.string().describe("One-sentence human-readable summary of what happened. AI should read this first. Example: 'Successfully published Service my-shop with Machine bound'"),
119
+ created: z.array(ObjectRoleSchema).optional().describe("Objects newly created in this operation, tagged with roles"),
120
+ modified: z.array(ObjectRoleSchema).optional().describe("Objects mutated in this operation, tagged with roles"),
121
+ released: z.array(FundRoleSchema).optional().describe("Fund movements in this operation, tagged with roles"),
122
+ events: z.array(EventSemanticSchema).optional().describe("On-chain events annotated with business semantics (S-8)"),
123
+ next_actions: z.array(NextActionSchema).optional().describe("Recommended next actions to drive the workflow forward"),
124
+ warnings: z.array(z.string()).optional().describe("Business-level warnings. Example: 'order_allocators not configured; order funds cannot be distributed'"),
125
+ }).strict().describe("Business semantic summary: translates the raw transaction response into AI-directly-understandable business meaning");
80
126
  export const CallResponseErrorSchema = z.object({
81
- type: z.literal("error").describe("Type of call response: error"),
82
- error: z.string(),
83
- }).describe("Call error data. Contains error information.");
127
+ type: z.literal("error").describe("Discriminator for this result variant. Constraint: always 'error'. Example: 'error'"),
128
+ error: z.string().describe("Human-readable error message from the chain or SDK. Relation: enriched via enrichMoveError before classification. Example: 'Insufficient balance for gas'"),
129
+ error_code: z.enum(["invalid_parameter", "guard_rejected", "state_conflict", "insufficient_balance", "object_not_found", "permission_denied", "immutable_violation", "network_error", "unknown"]).optional().describe("Error classification for programmatic recovery. Constraint: enum of 9 values. Relation: drives Recover Loop strategy selection. Example: 'insufficient_balance'"),
130
+ retryable: z.boolean().optional().describe("Whether the same call can be retried as-is. Constraint: true only for network_error and insufficient_balance. Example: true"),
131
+ recovery_hint: z.string().optional().describe("Recovery suggestion for AI or user. Relation: paired with error_code to guide Recover Loop. Example: 'Claim faucet tokens then retry'"),
132
+ related_object: z.string().optional().describe("Object ID related to the error, if any. Example: '0x123...'"),
133
+ }).describe("Error result. Contains the raw error message plus structured classification (error_code/retryable/recovery_hint) so AI can choose a recovery strategy without parsing the error string.");
84
134
  export const GuardSubmissionToFillSchema = z.object({
85
- guard: NameOrAddressSchema.describe("Guard object name or ID."),
86
- submission: z.array(GuardTableItemSchema).describe("User-submitted data required for Guard verification."),
87
- }).strict().describe("Permission guard submission data.");
135
+ guard: NameOrAddressSchema.describe("Guard object name or ID that requires submission data. Example: 'my-delivery-guard'"),
136
+ submission: z.array(GuardTableItemSchema).describe("User-submitted data matching the Guard's required fields. Relation: structure must match the Guard table's column definitions. Example: [{field:'delivery_proof', value:'Qm...'}]"),
137
+ }).strict().describe("One Guard's submission data: the Guard to verify plus the user-provided data that satisfies its requirements.");
88
138
  export const SubmissionCallSchema = z.object({
89
- type: z.literal("submission").describe("Type of call response: submission"),
139
+ type: z.literal("submission").describe("Discriminator for this result variant. Constraint: always 'submission'. Example: 'submission'"),
90
140
  guard: z.array(z.object({
91
- object: NameOrAddressSchema.describe("Guard object name or ID."),
92
- impack: z.boolean().describe("Whether the verification result of this Guard participates in the final verification logic. If true, the verification result of this Guard will be included in the final verification result; if false, the verification result of this Guard will not be included."),
93
- }).strict()),
94
- submission: z.array(GuardSubmissionToFillSchema),
95
- }).strict().describe("Guard verification submission data required to complete an operation. Contains: (1) 'guard' - array of Guard objects to verify, each with an object ID and an 'impack' flag indicating if its result affects the final outcome; (2) 'submission' - array of user data submissions matching the Guard's requirements. The operation proceeds only after all Guards with impack=true are successfully verified.");
141
+ object: NameOrAddressSchema.describe("Guard object name or ID to verify against. Example: 'my-delivery-guard' or '0x123...'"),
142
+ impack: z.boolean().describe("Whether this Guard's verification result participates in the final logic. Constraint: if false, the Guard is checked but does not block the operation. Example: true"),
143
+ }).strict()).describe("Array of Guard objects to verify. Relation: each entry corresponds to a Guard bound to the operation."),
144
+ submission: z.array(GuardSubmissionToFillSchema).describe("User-submitted data for each Guard. Relation: one entry per Guard in the guard array; fill submission fields and resubmit via call_with_submission."),
145
+ }).strict().describe("Guard verification required. The operation was blocked because one or more Guards require user-submitted data. Fill the submission array and resubmit. Semantic status is 'pending_input'.");
96
146
  export const TypedPermissionObjectSchema = z.union([
97
147
  NameOrAddressSchema.describe("String format: Reference an EXISTING object by its name (local mark) or on-chain object ID. Use this when the object already exists and you want to reference it."),
98
148
  TypeNamedObjectWithPermissionSchema.describe("Object format: CREATE a NEW object with COMPLETE configuration including: optional name, tags, description, token type for payments (e.g., '0x2::wow::WOW'), AND Permission-based access control. Use this for creating sophisticated objects with both payment token specification and permission management."),
@@ -108,17 +158,17 @@ export const TypedDescriptionObjectSchema = z.union([
108
158
  export const CallResultSchema = z.discriminatedUnion("type", [
109
159
  SubmissionCallSchema,
110
160
  WowTransactionBlockResponseSchema.extend({
111
- type: z.literal("transaction"),
161
+ type: z.literal("transaction").describe("Discriminator for this result variant. Constraint: always 'transaction'. Example: 'transaction'"),
112
162
  }),
113
163
  CallResponseErrorSchema,
114
164
  z.object({
115
- type: z.literal("data"),
116
- data: z.array(ResponseDataSchema),
165
+ type: z.literal("data").describe("Discriminator for this result variant. Constraint: always 'data'. Example: 'data'"),
166
+ data: z.array(ResponseDataSchema).describe("Array of object records returned by a query operation. Example: [{id:'0x...', change:'created'}]"),
117
167
  }),
118
168
  z.object({
119
- type: z.literal("null"),
169
+ type: z.literal("null").describe("Discriminator for this result variant. Constraint: always 'null'. Example: 'null'"),
120
170
  }),
121
- ]).describe("Call result. Can be Guard verification information (type: 'submission') that needs to be submitted by the user, result response, error information (type: 'error'), or null.");
171
+ ]).describe("Discriminated union of 5 result types: 'transaction' (raw Sui response with digest/effects/objectChanges), 'submission' (Guard verification needed), 'error' (failed with error_code), 'data' (query result array), 'null' (no-op completed). AI should check result.type first to determine how to process the response.");
122
172
  export const ObjectsSchema = z.union([
123
173
  z.object({
124
174
  op: z.union([z.literal('add'), z.literal('set')]),
@@ -132,7 +182,35 @@ export const ObjectsSchema = z.union([
132
182
  op: z.literal('clear'),
133
183
  }).strict(),
134
184
  ]);
185
+ export const VerifyMismatchSchema = z.object({
186
+ dimension: z.enum(["created", "modified", "released", "state", "event"]).describe("Verify dimension that mismatched. Example: 'created'"),
187
+ expected: z.string().describe("What the Expect Loop declared. Example: 'Service object created'"),
188
+ actual: z.string().describe("What actually happened. Example: 'No object created'"),
189
+ severity: z.enum(["pass", "warn", "fail"]).describe("Severity: 'fail' blocks progress, 'warn' is advisory, 'pass' never appears here. Example: 'fail'"),
190
+ detail: z.string().describe("Human-readable explanation of the mismatch. Example: 'Expected Service creation but transaction succeeded without object change'"),
191
+ }).describe("One mismatch between expected and actual result. AI should read severity first to decide whether to halt.");
192
+ export const VerifyReportSchema = z.object({
193
+ status: z.enum(["pass", "warn", "fail"]).describe("Overall verify status. Constraint: 'fail' if any mismatch has severity 'fail'; 'warn' if only warns; 'pass' if no mismatches. Example: 'fail'"),
194
+ mismatches: z.array(VerifyMismatchSchema).describe("List of mismatches found. Empty array when status is 'pass'. Example: [{dimension:'created', expected:'...', actual:'...', severity:'fail', detail:'...'}]"),
195
+ summary: z.string().describe("Human-readable summary of the verify result. Example: '2 mismatches found: created dimension failed, event dimension warned'"),
196
+ timestamp: z.string().describe("ISO 8601 timestamp when verify ran. Example: '2026-07-14T10:30:00.000Z'"),
197
+ }).describe("Verify Loop report. Compares expected vs actual semantic fields across 5 dimensions. When status is 'fail', AI should consult the recovery_action in the parent harness_report.");
198
+ export const RecoveryActionSchema = z.object({
199
+ strategy: z.enum(["retry", "claim_faucet", "fill_submission", "recreate", "switch_account", "query_and_retry", "adjust_params", "escalate_human", "stop"]).describe("Recovery strategy chosen by the Recover Loop. Constraint: 9 strategies matching error_code table. Example: 'claim_faucet'"),
200
+ should_retry: z.boolean().describe("Whether AI should retry the original operation after applying the strategy. Constraint: false for 'stop' and 'escalate_human'. Example: true"),
201
+ adjusted_params: z.record(z.string(), z.unknown()).optional().describe("Suggested parameter adjustments for 'adjust_params' strategy. Example: {amount: '100000000'}"),
202
+ user_prompt: z.string().optional().describe("Prompt to show the user when recovery is semi-automatic or manual. Example: 'Please switch to an account with provider permission'"),
203
+ max_attempts: z.number().int().describe("Maximum attempts for this error_code type. Example: 3"),
204
+ current_attempt: z.number().int().describe("Current attempt count (1-indexed). Example: 1"),
205
+ detail: z.string().describe("Human-readable explanation of the recovery decision. Example: 'Insufficient balance detected; claim faucet tokens then retry'"),
206
+ }).describe("Recover Loop action. Generated when verify fails or an error occurs. AI should follow the strategy and respect max_attempts.");
207
+ export const HarnessReportSchema = z.object({
208
+ verify: VerifyReportSchema.describe("Verify Loop report comparing expected vs actual."),
209
+ recovery: RecoveryActionSchema.optional().describe("Recover Loop action. Present only when verify.status is 'fail' or 'warn', or when an error occurred."),
210
+ }).describe("L4 Harness report attached to CallOutput when the Harness is injected. Contains verify result and optional recovery action. AI should check verify.status first; if 'fail', consult recovery.strategy.");
135
211
  export const CallOutputSchema = z.object({
136
- result: CallResultSchema,
137
- message: z.string().optional().describe("Message or hint information"),
138
- }).strict().describe("On-chain Operation Result");
212
+ result: CallResultSchema.describe("Discriminated result. Check result.type first: 'transaction'|'submission'|'error'|'data'|'null'. Each variant has different fields."),
213
+ message: z.string().optional().describe("Human-readable summary or hint. Constraint: always present for error/transaction results; may be omitted for data/null. Example: 'Transaction completed successfully'"),
214
+ semantic: SemanticSummarySchema.optional().describe("Business semantic summary. AI should read semantic first; fall back to parsing result only when semantic is absent. Relation: populated by MCP server from operation context; undefined when intent cannot be confidently inferred or for non-transaction tools. Example: {intent:'publish_service', status:'success', summary:'...'}"),
215
+ harness_report: HarnessReportSchema.optional().describe("L4 Harness report (Verify + Recover). Present only when the Harness is injected and an Expected Result was declared for this operation. Relation: produced by handler.ts calling harness.verify() and harness.recover(). Example: {verify:{status:'fail', mismatches:[...]}, recovery:{strategy:'recreate'}}"),
216
+ }).strict().describe("Unified MCP tool output. result.type discriminates 5 outcomes: 'transaction' (raw Sui response), 'submission' (needs Guard data), 'error' (failed with error_code), 'data' (query result), 'null' (no-op). When semantic is present, prefer it over raw result parsing. When harness_report is present, check verify.status first and follow recovery.strategy if status is 'fail'.");
@@ -1,4 +1,5 @@
1
1
  import { BridgeClient, LocalMark, } from "@wowok/wowok";
2
+ import { classifyError, buildSemantic, buildDataSemantic } from "./semantic.js";
2
3
  let _bridgeClient = null;
3
4
  let _bridgeClientEnv = null;
4
5
  function getBridgeClient(env) {
@@ -56,9 +57,10 @@ function convertBigInts(obj) {
56
57
  }
57
58
  return obj;
58
59
  }
59
- function ok(message, result) {
60
+ function ok(message, result, context) {
60
61
  const safeResult = convertBigInts(result);
61
- const output = { message, result: { type: "data", data: safeResult } };
62
+ const semantic = buildSemantic(safeResult, context);
63
+ const output = { message, result: { type: "data", data: safeResult }, semantic };
62
64
  return {
63
65
  content: [
64
66
  { type: "text", text: message },
@@ -67,8 +69,20 @@ function ok(message, result) {
67
69
  structuredContent: output,
68
70
  };
69
71
  }
70
- function err(message) {
71
- const output = { message, result: { type: "error", error: message } };
72
+ function err(message, context) {
73
+ const classified = classifyError(message);
74
+ const semantic = buildDataSemantic(undefined, context, true, message);
75
+ const output = {
76
+ message,
77
+ result: {
78
+ type: "error",
79
+ error: message,
80
+ error_code: classified.error_code,
81
+ retryable: classified.retryable,
82
+ recovery_hint: classified.recovery_hint,
83
+ },
84
+ semantic,
85
+ };
72
86
  return {
73
87
  content: [{ type: "text", text: message }],
74
88
  structuredContent: output,
@@ -87,6 +101,10 @@ export async function handleBridgeOperations(args) {
87
101
  return err(`Parameter validation failed: ${e?.message ?? String(e)}`);
88
102
  }
89
103
  const env = validated.env;
104
+ const ctx = {
105
+ operation_type: "bridge_" + validated.operation_type,
106
+ data: validated.data,
107
+ };
90
108
  try {
91
109
  switch (validated.operation_type) {
92
110
  case "cross_chain_wow_to_evm": {
@@ -100,7 +118,7 @@ export async function handleBridgeOperations(args) {
100
118
  waitForFinalization: false,
101
119
  });
102
120
  return ok(`WOW→EVM cross-chain step 1 (deposit) submitted. transferId=${result.transferId}, activeEvmAccount=${result.activeEvmAccount}. ` +
103
- `Next: poll query_transfer_status until bridge signs (~1-5 min), then call claim_wow_to_evm to complete.`, result);
121
+ `Next: poll query_transfer_status until bridge signs (~1-5 min), then call claim_wow_to_evm to complete.`, result, ctx);
104
122
  }
105
123
  case "cross_chain_evm_to_wow": {
106
124
  validateMainnet(env);
@@ -114,14 +132,14 @@ export async function handleBridgeOperations(args) {
114
132
  waitForFinalization: false,
115
133
  });
116
134
  return ok(`EVM→WOW cross-chain submitted. transferId=${result.transferId}, activeEvmAccount=${result.activeEvmAccount}. ` +
117
- `Bridge will auto-claim on WOW (~10-20 min). Poll query_transfer_status to monitor progress.`, result);
135
+ `Bridge will auto-claim on WOW (~10-20 min). Poll query_transfer_status to monitor progress.`, result, ctx);
118
136
  }
119
137
  case "claim_wow_to_evm": {
120
138
  validateMainnet(env);
121
139
  const data = validated.data;
122
140
  const client = getBridgeClient(env);
123
141
  const result = await client.claimWowToEvm(data.transferId);
124
- return ok(`WOW→EVM claim (step 2) completed. transferId=${result.transferId}, claimTxHash=${result.claimTxHash}`, result);
142
+ return ok(`WOW→EVM claim (step 2) completed. transferId=${result.transferId}, claimTxHash=${result.claimTxHash}`, result, ctx);
125
143
  }
126
144
  case "withdraw": {
127
145
  const data = validated.data;
@@ -133,7 +151,7 @@ export async function handleBridgeOperations(args) {
133
151
  const tokenMeta = chain?.tokens?.find((t) => t.symbol === data.token);
134
152
  tokenAddress = tokenMeta?.evmAddress;
135
153
  if (!tokenAddress) {
136
- return err(`Cannot resolve ERC20 token address for symbol '${data.token}' on chain '${data.network ?? "mainnet"}'. Please pass tokenAddress explicitly.`);
154
+ return err(`Cannot resolve ERC20 token address for symbol '${data.token}' on chain '${data.network ?? "mainnet"}'. Please pass tokenAddress explicitly.`, ctx);
137
155
  }
138
156
  }
139
157
  const result = await client.withdrawFromActiveEvmAccount({
@@ -143,7 +161,7 @@ export async function handleBridgeOperations(args) {
143
161
  token: data.token ? data.token : undefined,
144
162
  network: data.network,
145
163
  });
146
- return ok(`Withdrawal submitted. transferId=${result.transferId}, txHash=${result.txHash}`, result);
164
+ return ok(`Withdrawal submitted. transferId=${result.transferId}, txHash=${result.txHash}`, result, ctx);
147
165
  }
148
166
  case "query_active_evm_account": {
149
167
  const data = validated.data ?? {};
@@ -152,12 +170,12 @@ export async function handleBridgeOperations(args) {
152
170
  network: data.network,
153
171
  tokens: data.tokens,
154
172
  });
155
- return ok(`activeEvmAccount: ${result.address} (${result.chains.length} chain(s))`, result);
173
+ return ok(`activeEvmAccount: ${result.address} (${result.chains.length} chain(s))`, result, ctx);
156
174
  }
157
175
  case "query_supported_evm_chains": {
158
176
  const client = getBridgeClientForQuery();
159
177
  const result = await client.querySupportedEvmChains();
160
- return ok(`${result.length} EVM chain(s) supported: ${result.map(c => `${c.name}(chainId=${c.chainId})`).join(", ")}`, result);
178
+ return ok(`${result.length} EVM chain(s) supported: ${result.map(c => `${c.name}(chainId=${c.chainId})`).join(", ")}`, result, ctx);
161
179
  }
162
180
  case "query_supported_tokens": {
163
181
  const data = validated.data ?? {};
@@ -166,7 +184,7 @@ export async function handleBridgeOperations(args) {
166
184
  network: data.network,
167
185
  });
168
186
  const totalTokens = result.reduce((sum, c) => sum + c.tokens.length, 0);
169
- return ok(`${result.length} chain(s), ${totalTokens} token entries: ${result.map((c) => `${c.chainName}(${c.tokens.length} tokens)`).join(", ")}`, result);
187
+ return ok(`${result.length} chain(s), ${totalTokens} token entries: ${result.map((c) => `${c.chainName}(${c.tokens.length} tokens)`).join(", ")}`, result, ctx);
170
188
  }
171
189
  case "query_transfer_list": {
172
190
  const data = validated.data ?? {};
@@ -187,7 +205,7 @@ export async function handleBridgeOperations(args) {
187
205
  result = result.slice(0, data.limit);
188
206
  }
189
207
  const active = result.filter(r => r.status !== "success" && r.status !== "failed").length;
190
- return ok(`${result.length} transfer record(s) (${active} in progress)${data.status || data.direction || data.token ? " (filtered)" : ""}`, result);
208
+ return ok(`${result.length} transfer record(s) (${active} in progress)${data.status || data.direction || data.token ? " (filtered)" : ""}`, result, ctx);
191
209
  }
192
210
  case "query_transfer_status": {
193
211
  const data = validated.data;
@@ -208,9 +226,9 @@ export async function handleBridgeOperations(args) {
208
226
  return err(`transferId '${data.transferId}' not found. ` +
209
227
  `Use query_transfer_list to see all valid transferIds. ` +
210
228
  `Note: transfer history is persisted in cache.db and restored on MCP restart, ` +
211
- `so this transferId may never have been created in this environment.`);
229
+ `so this transferId may never have been created in this environment.`, ctx);
212
230
  }
213
- return ok(`Transfer ${data.transferId}: ${result.direction} / ${result.step} / ${result.status}`, result);
231
+ return ok(`Transfer ${data.transferId}: ${result.direction} / ${result.step} / ${result.status}`, result, ctx);
214
232
  }
215
233
  case "manage_evm_rpc": {
216
234
  const data = validated.data;
@@ -220,15 +238,15 @@ export async function handleBridgeOperations(args) {
220
238
  network: data.network,
221
239
  rpcUrls: data.rpcUrls,
222
240
  });
223
- return ok(`RPC '${data.op}' operation ${result.success ? "succeeded" : "failed"}`, result);
241
+ return ok(`RPC '${data.op}' operation ${result.success ? "succeeded" : "failed"}`, result, ctx);
224
242
  }
225
243
  default: {
226
- return err(`Unsupported operation_type: ${validated.operation_type}`);
244
+ return err(`Unsupported operation_type: ${validated.operation_type}`, ctx);
227
245
  }
228
246
  }
229
247
  }
230
248
  catch (e) {
231
249
  const msg = e?.message ?? String(e);
232
- return err(`Bridge operation failed: ${msg}`);
250
+ return err(`Bridge operation failed: ${msg}`, ctx);
233
251
  }
234
252
  }