@rohan-protocol/mcp 0.8.1 → 0.8.3

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.
@@ -0,0 +1,140 @@
1
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
2
+ import { RohanClient, type AgentSigner, type NetworkId } from '@rohan-protocol/sdk';
3
+ import type { LoadedAgentIdentity } from './identity/keystore.js';
4
+ export declare const ROHAN_MCP_VERSION = "0.8.3";
5
+ export declare const ROHAN_MCP_INSTRUCTIONS: string;
6
+ export declare const ROHAN_EXECUTE_TOOL_WITH_ANNOTATIONS: {
7
+ annotations: {
8
+ title: string;
9
+ readOnlyHint: boolean;
10
+ destructiveHint: boolean;
11
+ idempotentHint: boolean;
12
+ openWorldHint: boolean;
13
+ };
14
+ name: "rohan_execute_handshake";
15
+ description: "Executes or locally previews a confidential handshake commitment on Midnight. Usage guidelines:\n- Use for a user-authorized settlement; set dryRun: true only when the user asks to preview, test, or inspect a commitment without on-chain settlement (default false).\n- Do not use for reads, history, status, or audit; use rohan_get_ledger_state, rohan_get_transaction_history, rohan_get_agent_status, or rohan_verify_commitment instead.\n- Keep sensitive values in confidentialPayload, actionSummary generic, and private keys out of tool arguments. Follow recoveryAction on errors; after replay check transaction history, and after signature errors check agent status. Payloads are canonicalized and hashed locally.";
16
+ inputSchema: {
17
+ readonly type: "object";
18
+ readonly properties: {
19
+ readonly actionSummary: {
20
+ readonly type: "string";
21
+ readonly minLength: 1;
22
+ readonly description: "Required public high-level action label.";
23
+ };
24
+ readonly agentId: {
25
+ readonly type: "string";
26
+ readonly description: "Optional Sovereign Agent DID. Defaults to the local signer's DID and must match it when provided.";
27
+ };
28
+ readonly confidentialPayload: {
29
+ readonly type: "object";
30
+ readonly description: "Optional confidential parameters, canonicalized and hashed locally.";
31
+ };
32
+ readonly counterpartyId: {
33
+ readonly type: "string";
34
+ readonly description: "Optional counterparty agent identifier.";
35
+ };
36
+ readonly dryRun: {
37
+ readonly type: "boolean";
38
+ readonly description: "Only set true when the user asks to preview, test, or inspect the commitment without settling on-chain. Defaults to false.";
39
+ };
40
+ readonly intent: {
41
+ readonly type: "string";
42
+ readonly deprecated: true;
43
+ readonly description: "Deprecated alias. actionSummary remains required.";
44
+ };
45
+ };
46
+ readonly required: readonly ["actionSummary"];
47
+ readonly additionalProperties: false;
48
+ };
49
+ };
50
+ export declare const ROHAN_VERIFY_TOOL_SCHEMA: {
51
+ name: string;
52
+ description: string;
53
+ inputSchema: {
54
+ type: string;
55
+ properties: {
56
+ payload: {
57
+ type: string;
58
+ description: string;
59
+ };
60
+ expectedDigest: {
61
+ type: string;
62
+ pattern: string;
63
+ description: string;
64
+ };
65
+ auditBundle: {
66
+ type: string;
67
+ description: string;
68
+ };
69
+ };
70
+ required: never[];
71
+ };
72
+ annotations: {
73
+ title: string;
74
+ readOnlyHint: boolean;
75
+ destructiveHint: boolean;
76
+ idempotentHint: boolean;
77
+ openWorldHint: boolean;
78
+ };
79
+ };
80
+ export declare const ROHAN_LEDGER_STATE_TOOL_SCHEMA: {
81
+ name: string;
82
+ description: string;
83
+ inputSchema: {
84
+ type: string;
85
+ properties: {};
86
+ };
87
+ annotations: {
88
+ title: string;
89
+ readOnlyHint: boolean;
90
+ destructiveHint: boolean;
91
+ idempotentHint: boolean;
92
+ openWorldHint: boolean;
93
+ };
94
+ };
95
+ export declare const ROHAN_HISTORY_TOOL_SCHEMA: {
96
+ name: string;
97
+ description: string;
98
+ inputSchema: {
99
+ type: string;
100
+ properties: {
101
+ limit: {
102
+ type: string;
103
+ description: string;
104
+ };
105
+ };
106
+ };
107
+ annotations: {
108
+ title: string;
109
+ readOnlyHint: boolean;
110
+ destructiveHint: boolean;
111
+ idempotentHint: boolean;
112
+ openWorldHint: boolean;
113
+ };
114
+ };
115
+ export declare const ROHAN_AGENT_STATUS_TOOL_SCHEMA: {
116
+ name: string;
117
+ description: string;
118
+ inputSchema: {
119
+ type: string;
120
+ properties: {};
121
+ };
122
+ annotations: {
123
+ title: string;
124
+ readOnlyHint: boolean;
125
+ destructiveHint: boolean;
126
+ idempotentHint: boolean;
127
+ openWorldHint: boolean;
128
+ };
129
+ };
130
+ export interface CreateRohanMcpServerOptions {
131
+ contractAddress: string;
132
+ relayerUrl: string;
133
+ network?: NetworkId;
134
+ rohanClient: RohanClient;
135
+ configuredSigner?: AgentSigner;
136
+ loadedIdentity?: Pick<LoadedAgentIdentity, 'did' | 'source' | 'filePath'>;
137
+ statusTimeoutMs?: number;
138
+ }
139
+ export declare function createRohanMcpServer(options: CreateRohanMcpServerOptions): Server;
140
+ //# sourceMappingURL=mcp-app.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-app.d.ts","sourceRoot":"","sources":["../src/mcp-app.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AAOnE,OAAO,EACL,WAAW,EAMX,KAAK,WAAW,EAChB,KAAK,SAAS,EAEf,MAAM,qBAAqB,CAAC;AAQ7B,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAElE,eAAO,MAAM,iBAAiB,UAAU,CAAC;AAEzC,eAAO,MAAM,sBAAsB,QAc3B,CAAC;AAIT,eAAO,MAAM,mCAAmC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAS/C,CAAC;AAEF,eAAO,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA8BpC,CAAC;AAEF,eAAO,MAAM,8BAA8B;;;;;;;;;;;;;;CAe1C,CAAC;AAEF,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;CAoBrC,CAAC;AAEF,eAAO,MAAM,8BAA8B;;;;;;;;;;;;;;CAe1C,CAAC;AAiGF,MAAM,WAAW,2BAA2B;IAC1C,eAAe,EAAE,MAAM,CAAC;IACxB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,SAAS,CAAC;IACpB,WAAW,EAAE,WAAW,CAAC;IACzB,gBAAgB,CAAC,EAAE,WAAW,CAAC;IAC/B,cAAc,CAAC,EAAE,IAAI,CAAC,mBAAmB,EAAE,KAAK,GAAG,QAAQ,GAAG,UAAU,CAAC,CAAC;IAC1E,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,wBAAgB,oBAAoB,CAAC,OAAO,EAAE,2BAA2B,GAAG,MAAM,CA4YjF"}
@@ -0,0 +1,431 @@
1
+ import crypto from 'node:crypto';
2
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
+ import { CallToolRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
4
+ import { sealActionIntent, computePayloadDigest, extractSealedIntentParts, canonicalizeJson, verifyAuditBundle, } from '@rohan-protocol/sdk';
5
+ import { SemanticFirewall } from './firewall.js';
6
+ import { resolveHandshakeAgentId, ROHAN_HANDSHAKE_TOOL_SCHEMA, validateHandshakeArguments, } from './identity/handshake.js';
7
+ export const ROHAN_MCP_VERSION = '0.8.3';
8
+ export const ROHAN_MCP_INSTRUCTIONS = `
9
+ Rohan Protocol provides gas-free confidential commitments and Ed25519 (W3C did:key) non-repudiation on Midnight Network (Ledger v9).
10
+
11
+ CORE RULES FOR AGENTS:
12
+ 1. PRIVACY BOUNDARY: Always place sensitive parameters (budgets, prices, counterparties, PII, contract terms) inside \`confidentialPayload\`. Keep \`actionSummary\` generic and non-sensitive (e.g., "Vendor Procurement Authorization").
13
+ 2. PRIVATE KEYS: Never ask the user for private keys or pass private keys in tool arguments. Local stdio identity is managed automatically (~/.rohan/agent-identity.json or ROHAN_AGENT_PRIVATE_KEY). Do not invent an \`agentId\` when a local signer is active.
14
+ 3. IDENTITY & STATUS: To check your active \`did:key\`, network, or relayer health, read \`rohan://identity\` or call \`rohan_get_agent_status\`.
15
+ 4. AUDIT VERIFICATION: \`rohan_verify_commitment\` checks plaintext against the **inner \`payloadDigest\`** (RFC 8785 JCS + SHA-256, referenced in \`actionSummary\` or \`auditBundle.payloadDigest\`), NOT the outer timestamp-salted \`intentHash\`. You can also pass an entire \`auditBundle\` to verify signature and binding offline.
16
+ 5. DRY RUN: Use \`dryRun: true\` only when the user explicitly asks to preview, test, or inspect a commitment without settling on-chain. The default is \`false\`; dry runs create no transaction and no \`txHash\`.
17
+ 6. ERROR RECOVERY:
18
+ - \`REPLAY_DETECTED\` (409): Do NOT retry the same payload/nonce. Call \`rohan_get_transaction_history\` to inspect existing settlements.
19
+ - \`STALE_TIMESTAMP\` (401): Retry with a fresh tool invocation.
20
+ - \`INVALID_SIGNATURE\` (401): Call \`rohan_get_agent_status\` to verify the active identity and relayer status before retrying.
21
+ - \`IDENTITY_MISMATCH\` (403): Omit \`agentId\` so the active signer's DID is used automatically.
22
+ `.trim();
23
+ // ── Tool Schemas with MCP Annotations ───────────────────────────────────────
24
+ export const ROHAN_EXECUTE_TOOL_WITH_ANNOTATIONS = {
25
+ ...ROHAN_HANDSHAKE_TOOL_SCHEMA,
26
+ annotations: {
27
+ title: 'Execute Confidential ZK Handshake',
28
+ readOnlyHint: false,
29
+ destructiveHint: false,
30
+ idempotentHint: false,
31
+ openWorldHint: true,
32
+ },
33
+ };
34
+ export const ROHAN_VERIFY_TOOL_SCHEMA = {
35
+ name: 'rohan_verify_commitment',
36
+ description: 'Cryptographically audits a plaintext payload and/or a portable RohanAuditBundle offline in local memory (0 gas). Usage guidelines:\n- Use to verify a payload digest or audit bundle; do not use to submit a handshake (use rohan_execute_handshake).\n- For expectedDigest mode provide the exact original JSON payload and the inner payloadDigest; never pass the outer timestamp-salted intentHash. For auditBundle mode, provide the complete bundle and optionally the original payload.\n- Verification is local and does not send plaintext to the relayer. Treat valid: false as a cryptographic mismatch, not a tool execution error; use recoveryAction to correct inputs.',
37
+ inputSchema: {
38
+ type: 'object',
39
+ properties: {
40
+ payload: {
41
+ type: 'object',
42
+ description: 'Plaintext contract, agreement, or confidential data object to verify.',
43
+ },
44
+ expectedDigest: {
45
+ type: 'string',
46
+ pattern: '^(?:sha256:|0x)?[0-9a-fA-F]{64}$',
47
+ description: 'Expected inner SHA-256 digest of the canonicalized payload (from actionSummary digest: sha256:<hash> or auditBundle.payloadDigest). Accepts raw hex, 0x, or sha256: prefixes.',
48
+ },
49
+ auditBundle: {
50
+ type: 'object',
51
+ description: 'Optional portable RohanAuditBundle (schema: rohan-audit-bundle/v1) returned by rohan_execute_handshake. Verifies Ed25519 signature, intentHash binding, and payloadDigest.',
52
+ },
53
+ },
54
+ required: [],
55
+ },
56
+ annotations: {
57
+ title: 'Verify Commitment & Audit Bundle',
58
+ readOnlyHint: true,
59
+ destructiveHint: false,
60
+ idempotentHint: true,
61
+ openWorldHint: false,
62
+ },
63
+ };
64
+ export const ROHAN_LEDGER_STATE_TOOL_SCHEMA = {
65
+ name: 'rohan_get_ledger_state',
66
+ description: 'Reads the current anchored Rohan Protocol contract state on Midnight. Usage guidelines:\n- Use for the latest state root, block height, or last transaction hash; do not use for transaction lists (use rohan_get_transaction_history) or identity/relayer health (use rohan_get_agent_status).\n- This is a read-only network lookup; do not include confidential payloads. If unavailable, check rohan_get_agent_status before retrying.',
67
+ inputSchema: {
68
+ type: 'object',
69
+ properties: {},
70
+ },
71
+ annotations: {
72
+ title: 'Get Midnight Ledger State',
73
+ readOnlyHint: true,
74
+ destructiveHint: false,
75
+ idempotentHint: true,
76
+ openWorldHint: true,
77
+ },
78
+ };
79
+ export const ROHAN_HISTORY_TOOL_SCHEMA = {
80
+ name: 'rohan_get_transaction_history',
81
+ description: 'Lists historical Rohan Protocol settlement transactions and receipts on Midnight. Usage guidelines:\n- Use to find or inspect prior settlements, especially after REPLAY_DETECTED; do not use for the latest state root (use rohan_get_ledger_state) or identity/health (use rohan_get_agent_status).\n- This read-only lookup accepts no confidential payload. If it fails, check rohan_get_agent_status and follow the returned error guidance.',
82
+ inputSchema: {
83
+ type: 'object',
84
+ properties: {
85
+ limit: {
86
+ type: 'integer',
87
+ description: 'Maximum number of historical transactions to return (default: 10, max: 50).',
88
+ },
89
+ },
90
+ },
91
+ annotations: {
92
+ title: 'Get Transaction History',
93
+ readOnlyHint: true,
94
+ destructiveHint: false,
95
+ idempotentHint: true,
96
+ openWorldHint: true,
97
+ },
98
+ };
99
+ export const ROHAN_AGENT_STATUS_TOOL_SCHEMA = {
100
+ name: 'rohan_get_agent_status',
101
+ description: 'Returns the active Sovereign Agent identity (W3C did:key), signing mode, configured network, and relayer reachability (gracefully degrades if offline). Usage guidelines:\n- Use to inspect local identity or diagnose connectivity and signature errors; do not use for transaction details (use rohan_get_transaction_history) or full ledger state (use rohan_get_ledger_state).\n- Never exposes private keys. Do not send secrets as arguments; if offline, inspect configuration and retry only after recovery.',
102
+ inputSchema: {
103
+ type: 'object',
104
+ properties: {},
105
+ },
106
+ annotations: {
107
+ title: 'Get Sovereign Agent Status',
108
+ readOnlyHint: true,
109
+ destructiveHint: false,
110
+ idempotentHint: true,
111
+ openWorldHint: true,
112
+ },
113
+ };
114
+ // ── Response Builders (Always provide both content[] and structuredContent) ──
115
+ function buildSuccessResult(payload) {
116
+ return {
117
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
118
+ structuredContent: payload,
119
+ };
120
+ }
121
+ function buildErrorResult(code, message, retryable, recoveryAction) {
122
+ const payload = {
123
+ success: false,
124
+ code,
125
+ retryable,
126
+ error: message,
127
+ recoveryAction,
128
+ };
129
+ return {
130
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
131
+ structuredContent: payload,
132
+ isError: true,
133
+ };
134
+ }
135
+ function classifyRelayerError(errMessage) {
136
+ const msg = errMessage || 'Unknown execution error';
137
+ if (/nonce.*already.*used|REPLAY_DETECTED|409/i.test(msg)) {
138
+ return buildErrorResult('REPLAY_DETECTED', msg, false, 'Nonce already consumed. Call rohan_get_transaction_history to retrieve the existing settlement receipt instead of retrying.');
139
+ }
140
+ if (/STALE_TIMESTAMP|timestamp.*skew|window/i.test(msg)) {
141
+ return buildErrorResult('STALE_TIMESTAMP', msg, true, 'Request timestamp fell outside the allowed ±5 minute clock window. Retry with a fresh tool invocation.');
142
+ }
143
+ if (/IDENTITY_MISMATCH|SIGNER_MISMATCH/i.test(msg)) {
144
+ return buildErrorResult('IDENTITY_MISMATCH', msg, false, 'Omit agentId so the active signer DID is injected automatically, or pass the exact DID from rohan://identity.');
145
+ }
146
+ if (/INVALID_SIGNATURE|UNAUTHORIZED|AUTHENTICATION_FAILED|401/i.test(msg)) {
147
+ return buildErrorResult('INVALID_SIGNATURE', msg, false, 'Ed25519 signature verification failed on the relayer. Call rohan_get_agent_status to verify active DID, network alignment, and local keystore integrity.');
148
+ }
149
+ if (/QUEUE_CAPACITY|503|RELAYER_OVERLOADED/i.test(msg)) {
150
+ return buildErrorResult('RELAYER_BUSY', msg, true, 'Relayer settlement queue is temporarily full. Wait 5 seconds and retry.');
151
+ }
152
+ return buildErrorResult('EXECUTION_FAILED', msg, false, 'Inspect the error details and verify network connectivity or arguments before retrying.');
153
+ }
154
+ async function withTimeout(promise, timeoutMs, message) {
155
+ let timeout;
156
+ try {
157
+ return await Promise.race([
158
+ promise,
159
+ new Promise((_, reject) => {
160
+ timeout = setTimeout(() => reject(new Error(message)), timeoutMs);
161
+ }),
162
+ ]);
163
+ }
164
+ finally {
165
+ if (timeout)
166
+ clearTimeout(timeout);
167
+ }
168
+ }
169
+ export function createRohanMcpServer(options) {
170
+ const { contractAddress, relayerUrl, network = 'preprod', rohanClient, configuredSigner, loadedIdentity, statusTimeoutMs = 8500, } = options;
171
+ const cleanRelayerOrigin = relayerUrl.replace(/\/api\/v1\/handshake(?:\/stream)?$/, '');
172
+ const getIdentitySnapshot = () => ({
173
+ agentDid: configuredSigner?.did ?? loadedIdentity?.did ?? null,
174
+ signingMode: configuredSigner ? 'ed25519' : 'unsigned',
175
+ identitySource: loadedIdentity?.source ?? (configuredSigner ? 'injected' : 'remote-gateway'),
176
+ keystorePath: loadedIdentity?.filePath ?? null,
177
+ network: `midnight-${network}`,
178
+ contractAddress,
179
+ relayerUrl: cleanRelayerOrigin,
180
+ });
181
+ const server = new Server({
182
+ name: 'rohan-shield',
183
+ version: ROHAN_MCP_VERSION,
184
+ }, {
185
+ capabilities: {
186
+ tools: {},
187
+ resources: {},
188
+ },
189
+ instructions: ROHAN_MCP_INSTRUCTIONS,
190
+ });
191
+ // ── Resources ─────────────────────────────────────────────────────────────
192
+ server.setRequestHandler(ListResourcesRequestSchema, async () => {
193
+ return {
194
+ resources: [
195
+ {
196
+ uri: 'rohan://identity',
197
+ name: 'Rohan Sovereign Agent Identity',
198
+ description: 'Read-only metadata describing the active Ed25519 W3C did:key identity, signing mode, keystore path, and Midnight contract context.',
199
+ mimeType: 'application/json',
200
+ },
201
+ ],
202
+ };
203
+ });
204
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
205
+ if (request.params.uri !== 'rohan://identity') {
206
+ throw new Error(`Resource not found: ${request.params.uri}`);
207
+ }
208
+ return {
209
+ contents: [
210
+ {
211
+ uri: 'rohan://identity',
212
+ mimeType: 'application/json',
213
+ text: JSON.stringify(getIdentitySnapshot(), null, 2),
214
+ },
215
+ ],
216
+ };
217
+ });
218
+ // ── Tools Discovery ───────────────────────────────────────────────────────
219
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
220
+ return {
221
+ tools: [
222
+ ROHAN_EXECUTE_TOOL_WITH_ANNOTATIONS,
223
+ ROHAN_LEDGER_STATE_TOOL_SCHEMA,
224
+ ROHAN_HISTORY_TOOL_SCHEMA,
225
+ ROHAN_VERIFY_TOOL_SCHEMA,
226
+ ROHAN_AGENT_STATUS_TOOL_SCHEMA,
227
+ ],
228
+ };
229
+ });
230
+ // ── Tool Execution ────────────────────────────────────────────────────────
231
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
232
+ const toolName = request.params.name;
233
+ const rawArgs = request.params?.arguments === undefined ? {} : request.params.arguments;
234
+ if (!rawArgs || typeof rawArgs !== 'object' || Array.isArray(rawArgs)) {
235
+ return buildErrorResult('INVALID_ARGUMENTS', 'Expected a valid arguments object.', true, 'Pass a JSON object as tool arguments (or omit arguments for parameterless read tools).');
236
+ }
237
+ const args = rawArgs;
238
+ // ── Tool 1: rohan_execute_handshake (legacy alias: rohan_zk_handshake) ──
239
+ if (toolName === 'rohan_execute_handshake' || toolName === 'rohan_zk_handshake') {
240
+ const argumentsError = validateHandshakeArguments(args);
241
+ if (argumentsError) {
242
+ return buildErrorResult('INVALID_ARGUMENTS', argumentsError, true, 'Provide a non-empty actionSummary string and an object for confidentialPayload (if included).');
243
+ }
244
+ const identity = resolveHandshakeAgentId(args.agentId, configuredSigner);
245
+ if ('error' in identity) {
246
+ return buildErrorResult('IDENTITY_MISMATCH', identity.error, false, 'Omit agentId so the active signer DID is used automatically, or supply the exact DID from rohan://identity.');
247
+ }
248
+ const effectiveAgentId = identity.agentId;
249
+ const actionLabel = args.actionSummary;
250
+ const isValid = SemanticFirewall.validate({
251
+ agentId: effectiveAgentId,
252
+ action: 'rohan_execute_handshake',
253
+ payload: args,
254
+ });
255
+ if (!isValid) {
256
+ return buildErrorResult('FIREWALL_REJECTED', 'Security Violation: Intent rejected by Semantic Firewall (V-01)', false, 'Ensure actionSummary and confidentialPayload contain valid, non-malicious content under 8 KB.');
257
+ }
258
+ try {
259
+ const finalIntent = sealActionIntent(actionLabel, args.confidentialPayload);
260
+ if (args.dryRun === true) {
261
+ const commitment = await rohanClient.generateHandshakeProof({
262
+ agentId: effectiveAgentId,
263
+ intent: finalIntent,
264
+ counterpartyId: args.counterpartyId,
265
+ });
266
+ const sealedParts = extractSealedIntentParts(finalIntent);
267
+ const payloadDigest = args.confidentialPayload && Object.keys(args.confidentialPayload).length > 0
268
+ ? await computePayloadDigest(args.confidentialPayload)
269
+ : sealedParts.payloadDigest;
270
+ return buildSuccessResult({
271
+ status: 'dry_run_only',
272
+ settledOnChain: false,
273
+ agentDid: effectiveAgentId,
274
+ actionSummary: actionLabel,
275
+ ...(payloadDigest ? { payloadDigest } : {}),
276
+ intentHash: commitment.publicInputs.intentHash,
277
+ commitment,
278
+ });
279
+ }
280
+ const receipt = await rohanClient.submitHandshake({
281
+ agentId: effectiveAgentId,
282
+ intent: finalIntent,
283
+ counterpartyId: args.counterpartyId,
284
+ });
285
+ // Deduplicate payloadDigest & auditBundle so we don't double-send them in the LLM context
286
+ const { auditBundle, payloadDigest, ...cleanReceipt } = receipt;
287
+ return buildSuccessResult({
288
+ status: 'success',
289
+ message: 'Zero-Knowledge Handshake successfully settled on Midnight Blockchain with Sovereign Identity (V-08).',
290
+ agentDid: effectiveAgentId,
291
+ ...(payloadDigest ? { payloadDigest } : {}),
292
+ ...(auditBundle ? { auditBundle } : {}),
293
+ receipt: cleanReceipt,
294
+ });
295
+ }
296
+ catch (err) {
297
+ return classifyRelayerError(err?.message || 'Handshake execution failed');
298
+ }
299
+ }
300
+ // ── Tool 2: rohan_get_ledger_state ──────────────────────────────────────
301
+ if (toolName === 'rohan_get_ledger_state') {
302
+ try {
303
+ const ledgerState = await rohanClient.getLedgerState();
304
+ const cacheAgeMs = Date.now() - (ledgerState.fetchedAt || Date.now());
305
+ return buildSuccessResult({
306
+ status: 'success',
307
+ contractAddress: ledgerState.contractAddress,
308
+ currentStateRoot: ledgerState.currentStateRoot,
309
+ blockHeight: ledgerState.blockHeight ?? null,
310
+ lastTxHash: ledgerState.lastTxHash ?? null,
311
+ network: ledgerState.network || `midnight-${network}`,
312
+ isMinedOnChain: ledgerState.isMinedOnChain ?? true,
313
+ cacheAgeMs: ledgerState.cacheAgeMs ?? cacheAgeMs,
314
+ cacheTtlMs: ledgerState.cacheTtlMs ?? 15000,
315
+ fetchedAt: ledgerState.fetchedAt,
316
+ });
317
+ }
318
+ catch (err) {
319
+ return buildErrorResult('RELAYER_UNREACHABLE', err?.message || 'Failed to fetch ledger state', true, 'Verify relayer connectivity or call rohan_get_agent_status to inspect relayer health.');
320
+ }
321
+ }
322
+ // ── Tool 3: rohan_get_transaction_history ───────────────────────────────
323
+ if (toolName === 'rohan_get_transaction_history') {
324
+ try {
325
+ const rawLimit = Number(args.limit) || 10;
326
+ const history = await rohanClient.getTransactionHistory(rawLimit);
327
+ return buildSuccessResult({ status: 'success', ...history });
328
+ }
329
+ catch (err) {
330
+ return buildErrorResult('HISTORY_FETCH_FAILED', err?.message || 'Failed to fetch transaction history', true, 'Retry shortly or check relayer connectivity via rohan_get_agent_status.');
331
+ }
332
+ }
333
+ // ── Tool 4: rohan_verify_commitment (Digest &/or AuditBundle) ───────────
334
+ if (toolName === 'rohan_verify_commitment') {
335
+ const hasBundle = args.auditBundle !== undefined;
336
+ const hasDigest = args.expectedDigest !== undefined;
337
+ if (!hasBundle && !hasDigest) {
338
+ return buildErrorResult('INVALID_ARGUMENTS', 'Missing verification target: provide either auditBundle, or expectedDigest together with payload.', true, 'Pass { payload, expectedDigest } using the inner payloadDigest, or pass { auditBundle, payload } from rohan_execute_handshake.');
339
+ }
340
+ if (args.payload !== undefined) {
341
+ if (!args.payload || typeof args.payload !== 'object' || Array.isArray(args.payload)) {
342
+ return buildErrorResult('INVALID_PAYLOAD', 'Invalid argument: payload must be a non-null JSON object.', true, 'Pass a valid JSON object as payload.');
343
+ }
344
+ const payloadString = JSON.stringify(args.payload);
345
+ if (payloadString.length > 256 * 1024) {
346
+ return buildErrorResult('PAYLOAD_TOO_LARGE', 'Plaintext exceeds maximum allowed size of 256 KB.', false, 'Reduce payload size below 256 KB before verifying.');
347
+ }
348
+ }
349
+ if (hasBundle) {
350
+ if (!args.auditBundle || typeof args.auditBundle !== 'object' || Array.isArray(args.auditBundle)) {
351
+ return buildErrorResult('INVALID_AUDIT_BUNDLE', 'Invalid argument: auditBundle must be a non-null JSON object.', true, 'Pass the complete auditBundle object returned by rohan_execute_handshake.');
352
+ }
353
+ try {
354
+ const result = await verifyAuditBundle(args.auditBundle, args.payload);
355
+ const recoveryAction = result.valid
356
+ ? undefined
357
+ : 'Provide the exact original JSON payload used for the handshake and the complete unmodified auditBundle. Check payloadDigest (the inner SHA-256 digest); intentHash is an outer timestamp-salted commitment, not a payload digest. Review the reported schema, signature, and intent-binding errors before trusting the bundle.';
358
+ return buildSuccessResult({
359
+ status: 'success',
360
+ mode: 'audit-bundle',
361
+ ...result,
362
+ ...(recoveryAction ? { recoveryAction } : {}),
363
+ });
364
+ }
365
+ catch (err) {
366
+ return buildErrorResult('VERIFICATION_ERROR', err?.message || 'Audit bundle verification failed', false, 'Ensure auditBundle conforms to rohan-audit-bundle/v1.');
367
+ }
368
+ }
369
+ if (!args.payload) {
370
+ return buildErrorResult('MISSING_PAYLOAD', 'Invalid argument: payload is required when verifying against expectedDigest.', true, 'Pass the confidential plaintext object as payload alongside expectedDigest.');
371
+ }
372
+ if (typeof args.expectedDigest !== 'string') {
373
+ return buildErrorResult('INVALID_DIGEST', 'Invalid argument: expectedDigest must be a string.', true, 'Pass the 64-character hex SHA-256 payloadDigest (with optional sha256: or 0x prefix).');
374
+ }
375
+ const normalizedExpected = args.expectedDigest.replace(/^(?:sha256:|0x)/i, '').toLowerCase();
376
+ if (!/^[0-9a-f]{64}$/.test(normalizedExpected)) {
377
+ return buildErrorResult('INVALID_DIGEST', 'Invalid expectedDigest: must resolve to a 64-character hexadecimal SHA-256 hash.', true, 'Pass the inner payloadDigest (NOT the outer salted intentHash if malformed).');
378
+ }
379
+ try {
380
+ const canonicalPayload = canonicalizeJson(args.payload);
381
+ const computedDigest = crypto.createHash('sha256').update(canonicalPayload, 'utf8').digest('hex').toLowerCase();
382
+ const match = crypto.timingSafeEqual(Buffer.from(computedDigest, 'hex'), Buffer.from(normalizedExpected, 'hex'));
383
+ return buildSuccessResult({
384
+ status: 'success',
385
+ mode: 'digest',
386
+ valid: match,
387
+ match,
388
+ expectedDigest: normalizedExpected,
389
+ computedDigest,
390
+ algorithm: 'SHA-256 (RFC 8785 JCS)',
391
+ verifiedAt: Date.now(),
392
+ ...(match
393
+ ? {}
394
+ : {
395
+ recoveryAction: 'Use the exact original JSON payload supplied to rohan_execute_handshake and compare its computedDigest with the inner payloadDigest. Do not pass the outer timestamp-salted intentHash as expectedDigest.',
396
+ }),
397
+ });
398
+ }
399
+ catch (err) {
400
+ return buildErrorResult('VERIFICATION_ERROR', err?.message || 'Verification execution failed', false, 'Ensure payload is valid JSON under 32 nesting levels.');
401
+ }
402
+ }
403
+ // ── Tool 5: rohan_get_agent_status (Graceful Offline Degradation) ───────
404
+ if (toolName === 'rohan_get_agent_status') {
405
+ const base = getIdentitySnapshot();
406
+ try {
407
+ const state = await withTimeout(rohanClient.getLedgerState(), statusTimeoutMs, `Relayer status check timed out after ${statusTimeoutMs}ms`);
408
+ return buildSuccessResult({
409
+ status: 'success',
410
+ ...base,
411
+ relayerHealthy: true,
412
+ currentBlockHeight: state.blockHeight ?? null,
413
+ currentStateRoot: state.currentStateRoot ?? null,
414
+ });
415
+ }
416
+ catch (err) {
417
+ return buildSuccessResult({
418
+ status: 'degraded',
419
+ ...base,
420
+ relayerHealthy: false,
421
+ currentBlockHeight: null,
422
+ currentStateRoot: null,
423
+ relayerError: err?.message || 'Relayer unreachable',
424
+ });
425
+ }
426
+ }
427
+ return buildErrorResult('UNKNOWN_TOOL', `Unknown tool: ${toolName}`, false, 'Call tools/list to inspect the 5 supported Rohan Protocol tools.');
428
+ });
429
+ return server;
430
+ }
431
+ //# sourceMappingURL=mcp-app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"mcp-app.js","sourceRoot":"","sources":["../src/mcp-app.ts"],"names":[],"mappings":"AAAA,OAAO,MAAM,MAAM,aAAa,CAAC;AACjC,OAAO,EAAE,MAAM,EAAE,MAAM,2CAA2C,CAAC;AACnE,OAAO,EACL,qBAAqB,EACrB,0BAA0B,EAC1B,sBAAsB,EACtB,yBAAyB,GAC1B,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAEL,gBAAgB,EAChB,oBAAoB,EACpB,wBAAwB,EACxB,gBAAgB,EAChB,iBAAiB,GAIlB,MAAM,qBAAqB,CAAC;AAE7B,OA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