@rohan-protocol/mcp 0.8.0 β†’ 0.8.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.
package/src/server.ts CHANGED
@@ -10,15 +10,23 @@ import {
10
10
  } from '@modelcontextprotocol/sdk/types.js';
11
11
 
12
12
  import { SemanticFirewall } from './firewall.js';
13
- import { RohanClient, sealActionIntent, canonicalizeJson } from '@rohan-protocol/sdk';
14
- import { resolveSignerFromEnv } from './identity.js';
13
+ import { RohanClient, sealActionIntent, canonicalizeJson, type AgentSigner } from '@rohan-protocol/sdk';
14
+ import { resolveAgentIdentity } from './identity/keystore.js';
15
+ import {
16
+ resolveHandshakeAgentId,
17
+ ROHAN_HANDSHAKE_TOOL_SCHEMA,
18
+ validateHandshakeArguments,
19
+ } from './identity/handshake.js';
20
+ export { ROHAN_HANDSHAKE_TOOL_SCHEMA };
15
21
 
16
22
  const CONTRACT_ADDRESS = process.env.ROHAN_CONTRACT_ADDRESS || '585ac0c4448257507d8ffa2a89e2aa00abd86ec9e94bdb6f553bc83e05f4dd0e';
17
23
  const RELAYER_URL = process.env.ROHAN_RELAYER_URL || 'https://api.rohanprotocol.network/api/v1/handshake';
18
24
  const API_KEY = process.env.ROHAN_API_KEY || '';
19
- const configuredSigner = await resolveSignerFromEnv();
20
- if (configuredSigner) {
21
- console.error(`πŸ›‘οΈ [MCP V-08] Sovereign Agent Signer armed: ${configuredSigner.did}`);
25
+ const loadedIdentity = await resolveAgentIdentity();
26
+ const configuredSigner: AgentSigner = loadedIdentity.signer;
27
+ console.error(`πŸ›‘οΈ [MCP V-08] Agent identity active (${loadedIdentity.source}): ${loadedIdentity.did}`);
28
+ if (loadedIdentity.filePath) {
29
+ console.error(`πŸ›‘οΈ [MCP V-08] Keystore path: ${loadedIdentity.filePath}`);
22
30
  }
23
31
 
24
32
  const rohanClient = new RohanClient({
@@ -31,7 +39,7 @@ const rohanClient = new RohanClient({
31
39
  const server = new Server(
32
40
  {
33
41
  name: 'rohan-protocol-mcp',
34
- version: '0.8.0',
42
+ version: '0.8.1',
35
43
  },
36
44
  {
37
45
  capabilities: {
@@ -40,39 +48,6 @@ const server = new Server(
40
48
  }
41
49
  );
42
50
 
43
- // ── Tool 1 Schema: Write / Settlement ───────────────────────────────────────
44
- export const ROHAN_HANDSHAKE_TOOL_SCHEMA = {
45
- name: 'rohan_execute_handshake',
46
- description:
47
- 'Executes a confidential zero-knowledge state transition on Midnight Blockchain. Confidential parameters are automatically canonicalized (RFC 8785) and hashed in client RAMβ€”never exposed on-chain or in model logs.',
48
- inputSchema: {
49
- type: 'object',
50
- properties: {
51
- agentId: {
52
- type: 'string',
53
- description: 'Decentralized Identifier (DID) of the initiating agent',
54
- },
55
- actionSummary: {
56
- type: 'string',
57
- description: "Public high-level action label (e.g. 'Vendor Agreement Execution', 'Database Audit Anchor')",
58
- },
59
- confidentialPayload: {
60
- type: 'object',
61
- description: 'OPTIONAL confidential parameters (budgets, deals, PII). Automatically canonicalized via RFC 8785 and hashed in local memory.',
62
- },
63
- counterpartyId: {
64
- type: 'string',
65
- description: 'Optional counterparty agent identifier',
66
- },
67
- intent: {
68
- type: 'string',
69
- description: 'Legacy fallback for actionSummary',
70
- },
71
- },
72
- required: ['agentId'],
73
- },
74
- };
75
-
76
51
  // ── Tool 2 Schema: Audit / In-Memory Verification ───────────────────────────
77
52
  export const ROHAN_VERIFY_TOOL_SCHEMA = {
78
53
  name: 'rohan_verify_commitment',
@@ -146,13 +121,26 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
146
121
 
147
122
  // ── Tool 1: rohan_zk_handshake ────────────────────────────────────────────
148
123
  if (toolName === 'rohan_execute_handshake' || toolName === 'rohan_zk_handshake') {
149
- const actionLabel = args.actionSummary || args.intent;
150
- if (!actionLabel) {
151
- throw new Error('Invalid arguments: Either actionSummary or intent is required.');
124
+ const argumentsError = validateHandshakeArguments(args);
125
+ if (argumentsError) {
126
+ return {
127
+ content: [{ type: 'text', text: JSON.stringify({ success: false, error: argumentsError }) }],
128
+ isError: true,
129
+ };
130
+ }
131
+
132
+ const identity = resolveHandshakeAgentId(args.agentId, configuredSigner);
133
+ if ('error' in identity) {
134
+ return {
135
+ content: [{ type: 'text', text: JSON.stringify({ success: false, error: identity.error }) }],
136
+ isError: true,
137
+ };
152
138
  }
139
+ const effectiveAgentId = identity.agentId;
140
+ const actionLabel = args.actionSummary;
153
141
 
154
142
  const isValid = SemanticFirewall.validate({
155
- agentId: args.agentId,
143
+ agentId: effectiveAgentId,
156
144
  action: 'rohan_execute_handshake',
157
145
  payload: args,
158
146
  });
@@ -168,7 +156,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
168
156
  const finalIntent = sealActionIntent(actionLabel, args.confidentialPayload);
169
157
 
170
158
  const receipt = await rohanClient.submitHandshake({
171
- agentId: args.agentId,
159
+ agentId: effectiveAgentId,
172
160
  intent: finalIntent,
173
161
  counterpartyId: args.counterpartyId,
174
162
  });
@@ -178,7 +166,8 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
178
166
  type: 'text',
179
167
  text: JSON.stringify({
180
168
  status: 'success',
181
- message: 'Zero-Knowledge Handshake successfully settled on Midnight Blockchain.',
169
+ message: 'Zero-Knowledge Handshake successfully settled on Midnight Blockchain with Sovereign Identity (V-08).',
170
+ agentDid: effectiveAgentId,
182
171
  receipt,
183
172
  }, null, 2),
184
173
  }],
@@ -312,7 +301,7 @@ server.setRequestHandler(CallToolRequestSchema, async (request) => {
312
301
  async function run() {
313
302
  const transport = new StdioServerTransport();
314
303
  await server.connect(transport);
315
- console.error('πŸ›‘οΈ Rohan Protocol MCP Server running via stdio (v0.8.0)...');
304
+ console.error('πŸ›‘οΈ Rohan Protocol MCP Server running via stdio (v0.8.1)...');
316
305
  }
317
306
 
318
307
  run().catch((error) => {
@@ -1,32 +1,170 @@
1
1
  import assert from 'node:assert/strict';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
2
5
  import test from 'node:test';
3
6
  import {
4
7
  publicKeyFromDidKey,
5
8
  verifyEd25519Signature,
6
9
  } from '@rohan-protocol/sdk';
7
- import { resolveSignerFromEnv } from '../dist/identity.js';
10
+ import {
11
+ loadKeystoreFile,
12
+ resolveAgentIdentity,
13
+ saveKeystoreFile,
14
+ } from '../dist/identity/keystore.js';
15
+ import {
16
+ resolveHandshakeAgentId,
17
+ ROHAN_HANDSHAKE_TOOL_SCHEMA,
18
+ validateActionSummary,
19
+ validateHandshakeArguments,
20
+ } from '../dist/identity/handshake.js';
8
21
 
9
22
  const TEST_SEED_HEX = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
10
23
 
11
- test('derives a matching Ed25519 signer from a 32-byte hex seed', async () => {
12
- const signer = await resolveSignerFromEnv(TEST_SEED_HEX);
13
- assert.ok(signer);
24
+ function createTempKeystorePath() {
25
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'rohan-identity-'));
26
+ return {
27
+ directory,
28
+ filePath: path.join(directory, 'agent-identity.json'),
29
+ cleanup: () => fs.rmSync(directory, { recursive: true, force: true }),
30
+ };
31
+ }
14
32
 
15
- const message = new TextEncoder().encode('Rohan Protocol V-08 Verification');
16
- const signature = await signer.sign(message);
17
- const publicKey = publicKeyFromDidKey(signer.did);
33
+ test('auto-provisions a persistent identity and reloads the same signer', async (t) => {
34
+ const temp = createTempKeystorePath();
35
+ t.after(temp.cleanup);
36
+
37
+ const created = await resolveAgentIdentity({ privateKeyHex: '', filePath: temp.filePath });
38
+ const loaded = await resolveAgentIdentity({ privateKeyHex: '', filePath: temp.filePath });
39
+
40
+ assert.equal(created.source, 'auto-provisioned');
41
+ assert.equal(loaded.source, 'filesystem');
42
+ assert.equal(loaded.did, created.did);
43
+ assert.equal(fs.statSync(temp.directory).mode & 0o777, 0o700);
44
+ assert.equal(fs.statSync(temp.filePath).mode & 0o777, 0o600);
45
+ assert.equal(fs.statSync(temp.filePath).nlink, 1);
46
+ });
47
+
48
+ test('concurrent first-run provisioning never overwrites the winning identity', async (t) => {
49
+ const temp = createTempKeystorePath();
50
+ t.after(temp.cleanup);
18
51
 
52
+ const [first, second] = await Promise.all([
53
+ resolveAgentIdentity({ privateKeyHex: '', filePath: temp.filePath }),
54
+ resolveAgentIdentity({ privateKeyHex: '', filePath: temp.filePath }),
55
+ ]);
56
+ const restored = await resolveAgentIdentity({ privateKeyHex: '', filePath: temp.filePath });
57
+
58
+ assert.equal(first.did, second.did);
59
+ assert.equal(restored.did, first.did);
60
+ assert.equal(fs.statSync(temp.filePath).mode & 0o777, 0o600);
61
+ });
62
+
63
+ test('provisioned keystore permissions stay strict under a restrictive umask', async (t) => {
64
+ const temp = createTempKeystorePath();
65
+ t.after(temp.cleanup);
66
+ const previousUmask = process.umask(0o777);
67
+ try {
68
+ await resolveAgentIdentity({ privateKeyHex: '', filePath: temp.filePath });
69
+ } finally {
70
+ process.umask(previousUmask);
71
+ }
72
+ assert.equal(fs.statSync(temp.directory).mode & 0o777, 0o700);
73
+ assert.equal(fs.statSync(temp.filePath).mode & 0o777, 0o600);
74
+ });
75
+
76
+ test('environment seed takes precedence and malformed explicit seed fails closed', async (t) => {
77
+ const temp = createTempKeystorePath();
78
+ t.after(temp.cleanup);
79
+ fs.writeFileSync(temp.filePath, '{ broken', { mode: 0o600 });
80
+
81
+ const fromEnv = await resolveAgentIdentity({ privateKeyHex: TEST_SEED_HEX, filePath: temp.filePath });
82
+ const message = new TextEncoder().encode('Rohan Protocol V-08 Verification');
83
+ const signature = await fromEnv.signer.sign(message);
84
+ const publicKey = publicKeyFromDidKey(fromEnv.did);
85
+ assert.equal(fromEnv.source, 'env');
19
86
  assert.equal(await verifyEd25519Signature(publicKey, signature, message), true);
87
+
88
+ await assert.rejects(
89
+ resolveAgentIdentity({ privateKeyHex: 'malformed', filePath: temp.filePath }),
90
+ /ROHAN_AGENT_PRIVATE_KEY is set/
91
+ );
92
+ assert.equal(fs.readFileSync(temp.filePath, 'utf8'), '{ broken');
93
+ });
94
+
95
+ test('refuses to replace a corrupted or mismatched keystore', async (t) => {
96
+ const temp = createTempKeystorePath();
97
+ t.after(temp.cleanup);
98
+ fs.writeFileSync(temp.filePath, '{ broken', { mode: 0o600 });
99
+
100
+ await assert.rejects(
101
+ resolveAgentIdentity({ privateKeyHex: '', filePath: temp.filePath }),
102
+ /CORRUPTED_KEYSTORE/
103
+ );
104
+ assert.equal(fs.readFileSync(temp.filePath, 'utf8'), '{ broken');
105
+
106
+ fs.unlinkSync(temp.filePath);
107
+ const validIdentity = await resolveAgentIdentity({ privateKeyHex: TEST_SEED_HEX, filePath: temp.filePath });
108
+ fs.writeFileSync(temp.filePath, JSON.stringify({
109
+ did: `${validIdentity.did}tampered`,
110
+ privateKeyHex: TEST_SEED_HEX,
111
+ createdAt: Date.now(),
112
+ }), { mode: 0o600 });
113
+ await assert.rejects(loadKeystoreFile(temp.filePath), /Stored DID does not match/);
20
114
  });
21
115
 
22
- test('does not configure a signer when no private key is provided', async () => {
23
- assert.equal(await resolveSignerFromEnv(undefined), undefined);
24
- assert.equal(await resolveSignerFromEnv(' '), undefined);
116
+ test('rejects symlinked keystore paths', async (t) => {
117
+ if (process.platform === 'win32') t.skip('Symlink behavior is platform-dependent on Windows.');
118
+ const temp = createTempKeystorePath();
119
+ t.after(temp.cleanup);
120
+ const target = path.join(temp.directory, 'target.json');
121
+ const link = path.join(temp.directory, 'agent-identity.json');
122
+ fs.writeFileSync(target, '{}', { mode: 0o600 });
123
+ fs.symlinkSync(target, link);
124
+
125
+ await assert.rejects(loadKeystoreFile(link), /symbolic link|ELOOP/);
25
126
  });
26
127
 
27
- test('fails explicitly when a configured private key is malformed', async () => {
128
+ test('requires actionSummary and resolves optional agentId to the signer DID', async () => {
129
+ const temp = createTempKeystorePath();
130
+ try {
131
+ const { signer } = await resolveAgentIdentity({ privateKeyHex: TEST_SEED_HEX, filePath: temp.filePath });
132
+ assert.deepEqual(ROHAN_HANDSHAKE_TOOL_SCHEMA.inputSchema.required, ['actionSummary']);
133
+ assert.equal(ROHAN_HANDSHAKE_TOOL_SCHEMA.inputSchema.required.includes('agentId'), false);
134
+ assert.equal(ROHAN_HANDSHAKE_TOOL_SCHEMA.inputSchema.properties.intent.deprecated, true);
135
+ assert.equal(validateActionSummary(' '), 'INVALID_ARGUMENTS: actionSummary is required and cannot be empty.');
136
+ assert.equal(validateActionSummary(undefined), 'INVALID_ARGUMENTS: actionSummary is required and cannot be empty.');
137
+ assert.equal(validateActionSummary('Review settlement'), undefined);
138
+ assert.match(
139
+ validateHandshakeArguments({ actionSummary: 'review', privateKey: TEST_SEED_HEX }),
140
+ /unsupported properties/
141
+ );
142
+ assert.match(
143
+ validateHandshakeArguments({ intent: 'legacy-only' }),
144
+ /actionSummary is required/
145
+ );
146
+ assert.match(
147
+ validateHandshakeArguments({ actionSummary: 'review', intent: {} }),
148
+ /Deprecated intent must be a string/
149
+ );
150
+ assert.deepEqual(resolveHandshakeAgentId(undefined, signer), { agentId: signer.did });
151
+ assert.deepEqual(resolveHandshakeAgentId(signer.did, signer), { agentId: signer.did });
152
+ assert.match(resolveHandshakeAgentId('did:key:other', signer).error, /^IDENTITY_MISMATCH:/);
153
+ assert.match(resolveHandshakeAgentId(undefined).error, /^MISSING_AGENT_ID:/);
154
+ } finally {
155
+ temp.cleanup();
156
+ }
157
+ });
158
+
159
+ test('refuses to overwrite an existing keystore when saving', async (t) => {
160
+ const temp = createTempKeystorePath();
161
+ t.after(temp.cleanup);
162
+
163
+ await resolveAgentIdentity({ privateKeyHex: '', filePath: temp.filePath });
164
+ const data = JSON.parse(fs.readFileSync(temp.filePath, 'utf8'));
165
+
28
166
  await assert.rejects(
29
- resolveSignerFromEnv('not-a-private-key'),
30
- /ROHAN_AGENT_PRIVATE_KEY must be exactly 32 bytes/
167
+ saveKeystoreFile(temp.filePath, data),
168
+ /already exists/
31
169
  );
32
170
  });
package/src/identity.ts DELETED
@@ -1,56 +0,0 @@
1
- import { webcrypto } from 'node:crypto';
2
- import {
3
- InMemoryEd25519Signer,
4
- type AgentSigner,
5
- } from '@rohan-protocol/sdk';
6
-
7
- const ED25519_PKCS8_PREFIX = new Uint8Array([
8
- 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
9
- ]);
10
-
11
- export async function resolveSignerFromEnv(
12
- rawPrivateKeyHex = process.env.ROHAN_AGENT_PRIVATE_KEY
13
- ): Promise<AgentSigner | undefined> {
14
- if (rawPrivateKeyHex === undefined || rawPrivateKeyHex.trim() === '') {
15
- return undefined;
16
- }
17
-
18
- const normalizedHex = rawPrivateKeyHex.trim().replace(/^0x/i, '');
19
- if (!/^[0-9a-f]{64}$/i.test(normalizedHex)) {
20
- throw new Error('ROHAN_AGENT_PRIVATE_KEY must be exactly 32 bytes encoded as 64 hex characters.');
21
- }
22
-
23
- const privateKey = new Uint8Array(Buffer.from(normalizedHex, 'hex'));
24
- const pkcs8Key = new Uint8Array(ED25519_PKCS8_PREFIX.length + privateKey.length);
25
- pkcs8Key.set(ED25519_PKCS8_PREFIX);
26
- pkcs8Key.set(privateKey, ED25519_PKCS8_PREFIX.length);
27
-
28
- try {
29
- const cryptoKey = await webcrypto.subtle.importKey(
30
- 'pkcs8',
31
- pkcs8Key,
32
- { name: 'Ed25519' },
33
- true,
34
- ['sign']
35
- );
36
- const jwk = await webcrypto.subtle.exportKey('jwk', cryptoKey);
37
- if (!jwk.x) {
38
- throw new Error('Could not derive the Ed25519 public key from ROHAN_AGENT_PRIVATE_KEY.');
39
- }
40
-
41
- const publicKey = new Uint8Array(Buffer.from(jwk.x, 'base64url'));
42
- if (publicKey.length !== 32) {
43
- throw new Error('Derived Ed25519 public key has an invalid length.');
44
- }
45
-
46
- return new InMemoryEd25519Signer(publicKey, privateKey);
47
- } catch (error) {
48
- throw new Error(
49
- 'Failed to initialize the Ed25519 signer from ROHAN_AGENT_PRIVATE_KEY.',
50
- { cause: error }
51
- );
52
- } finally {
53
- privateKey.fill(0);
54
- pkcs8Key.fill(0);
55
- }
56
- }