@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.
package/src/gateway.ts DELETED
@@ -1,59 +0,0 @@
1
- import { RohanRelayerClient } from '@rohan-protocol/sdk';
2
-
3
- export interface RohanMcpGatewayOptions {
4
- transport?: 'stdio' | 'streamable-http';
5
- relayerUrl?: string;
6
- contractAddress?: string;
7
- apiKey?: string;
8
- }
9
-
10
- /**
11
- * RohanMcpGateway
12
- * Connects AI Agent pipelines (Google ADK 2.0, Gemini, Claude, Cursor)
13
- * to the Rohan Protocol Gas Station via Streamable HTTP (NDJSON) or Stdio.
14
- */
15
- export class RohanMcpGateway {
16
- public readonly transport: string;
17
- public readonly relayerClient: RohanRelayerClient;
18
-
19
- constructor(options: RohanMcpGatewayOptions = {}) {
20
- this.transport = options.transport || 'streamable-http';
21
- this.relayerClient = new RohanRelayerClient({
22
- relayerUrl: options.relayerUrl || 'http://127.0.0.1:4005/api/v1/handshake',
23
- contractAddress: options.contractAddress || '585ac0c4448257507d8ffa2a89e2aa00abd86ec9e94bdb6f553bc83e05f4dd0e',
24
- apiKey: options.apiKey,
25
- });
26
- }
27
-
28
- /**
29
- * Generates a tool specification compliant with Google ADK 2.0 and Gemini tool calling.
30
- */
31
- asAdkTool() {
32
- return {
33
- name: 'rohan_execute_handshake',
34
- description: 'Executes a zero-knowledge verifiable handshake proof on Midnight Network with zero plaintext leaks.',
35
- parameters: {
36
- type: 'object',
37
- properties: {
38
- agentId: { type: 'string', description: 'Decentralized Identifier (DID) of calling agent' },
39
- intent: { type: 'string', description: 'Semantic action intent or agreement payload' },
40
- counterpartyId: { type: 'string', description: 'Optional recipient agent identifier' },
41
- },
42
- required: ['agentId', 'intent'],
43
- },
44
- execute: async (params: any) => {
45
- return await this.relayerClient.submitHandshake(params);
46
- },
47
- };
48
- }
49
-
50
- /**
51
- * Generates the legacy tool name for integrations that have not migrated yet.
52
- */
53
- asLegacyAdkTool() {
54
- return {
55
- ...this.asAdkTool(),
56
- name: 'rohan_zk_handshake',
57
- };
58
- }
59
- }
@@ -1,82 +0,0 @@
1
- import type { AgentSigner } from '@rohan-protocol/sdk';
2
-
3
- export const ROHAN_HANDSHAKE_TOOL_SCHEMA = {
4
- name: 'rohan_execute_handshake',
5
- description:
6
- '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.',
7
- inputSchema: {
8
- type: 'object',
9
- properties: {
10
- actionSummary: {
11
- type: 'string',
12
- minLength: 1,
13
- description: 'Required public high-level action label.',
14
- },
15
- agentId: {
16
- type: 'string',
17
- description: "Optional Sovereign Agent DID. Defaults to the local signer's DID and must match it when provided.",
18
- },
19
- confidentialPayload: {
20
- type: 'object',
21
- description: 'Optional confidential parameters, canonicalized and hashed locally.',
22
- },
23
- counterpartyId: {
24
- type: 'string',
25
- description: 'Optional counterparty agent identifier.',
26
- },
27
- intent: {
28
- type: 'string',
29
- deprecated: true,
30
- description: 'Deprecated alias. actionSummary remains required.',
31
- },
32
- },
33
- required: ['actionSummary'],
34
- additionalProperties: false,
35
- },
36
- } as const;
37
-
38
- export function validateActionSummary(value: unknown): string | undefined {
39
- if (typeof value !== 'string' || value.trim().length === 0) {
40
- return 'INVALID_ARGUMENTS: actionSummary is required and cannot be empty.';
41
- }
42
- return undefined;
43
- }
44
-
45
- export function validateHandshakeArguments(args: Record<string, unknown>): string | undefined {
46
- const allowedProperties = new Set([
47
- 'actionSummary',
48
- 'agentId',
49
- 'confidentialPayload',
50
- 'counterpartyId',
51
- 'intent',
52
- ]);
53
- if (Object.keys(args).some((key) => !allowedProperties.has(key))) {
54
- return 'INVALID_ARGUMENTS: Handshake arguments contain unsupported properties.';
55
- }
56
- if (args.intent !== undefined && typeof args.intent !== 'string') {
57
- return 'INVALID_ARGUMENTS: Deprecated intent must be a string when provided.';
58
- }
59
- return validateActionSummary(args.actionSummary);
60
- }
61
-
62
- export function resolveHandshakeAgentId(
63
- requestedAgentId: unknown,
64
- signer?: AgentSigner
65
- ): { agentId: string } | { error: string } {
66
- if (signer) {
67
- if (requestedAgentId === undefined) return { agentId: signer.did };
68
- if (typeof requestedAgentId !== 'string' || requestedAgentId !== signer.did) {
69
- return {
70
- error: 'IDENTITY_MISMATCH: Declared agentId does not match the armed Sovereign Signer DID.',
71
- };
72
- }
73
- return { agentId: signer.did };
74
- }
75
-
76
- if (typeof requestedAgentId !== 'string' || requestedAgentId.trim().length === 0) {
77
- return {
78
- error: 'MISSING_AGENT_ID: An explicit agentId is required when no Sovereign Signer is armed.',
79
- };
80
- }
81
- return { agentId: requestedAgentId };
82
- }
@@ -1,385 +0,0 @@
1
- import fs, { constants as fsConstants } from 'node:fs';
2
- import path from 'node:path';
3
- import os from 'node:os';
4
- import { createPrivateKey, createPublicKey, randomBytes } from 'node:crypto';
5
- import {
6
- createDidKey,
7
- generateEd25519KeyPair,
8
- InMemoryEd25519Signer,
9
- type AgentSigner,
10
- } from '@rohan-protocol/sdk';
11
-
12
- const ED25519_PKCS8_PREFIX = new Uint8Array([
13
- 0x30, 0x2e, 0x02, 0x01, 0x00, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x04, 0x22, 0x04, 0x20,
14
- ]);
15
- const ED25519_SPKI_PREFIX = new Uint8Array([
16
- 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0x00,
17
- ]);
18
- const MAX_KEYSTORE_SIZE = 4096;
19
-
20
- export interface AgentKeystoreData {
21
- did: string;
22
- privateKeyHex: string;
23
- createdAt: number;
24
- }
25
-
26
- export interface LoadedAgentIdentity {
27
- signer: AgentSigner;
28
- did: string;
29
- source: 'env' | 'filesystem' | 'auto-provisioned';
30
- filePath?: string;
31
- }
32
-
33
- export class KeystoreResolutionError extends Error {
34
- readonly code?: string;
35
-
36
- constructor(message: string, options?: { cause?: unknown; code?: string }) {
37
- super(message, { cause: options?.cause });
38
- this.name = 'KeystoreResolutionError';
39
- this.code = options?.code;
40
- }
41
- }
42
-
43
- function isErrno(error: unknown, code: string): boolean {
44
- return typeof error === 'object' && error !== null && 'code' in error &&
45
- (error as NodeJS.ErrnoException).code === code;
46
- }
47
-
48
- function currentUid(): number | undefined {
49
- return typeof process.getuid === 'function' ? process.getuid() : undefined;
50
- }
51
-
52
- function ensurePrivateDirectory(directoryPath: string): void {
53
- try {
54
- fs.mkdirSync(directoryPath, { recursive: true, mode: 0o700 });
55
- } catch (error) {
56
- throw new KeystoreResolutionError(
57
- `Could not create keystore directory "${directoryPath}".`,
58
- { cause: error }
59
- );
60
- }
61
-
62
- let directoryStat: fs.Stats;
63
- try {
64
- directoryStat = fs.lstatSync(directoryPath);
65
- } catch (error) {
66
- throw new KeystoreResolutionError(
67
- `Could not inspect keystore directory "${directoryPath}".`,
68
- { cause: error }
69
- );
70
- }
71
-
72
- if (directoryStat.isSymbolicLink() || !directoryStat.isDirectory()) {
73
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore parent must be a real directory, not a symlink.');
74
- }
75
-
76
- const uid = currentUid();
77
- if (uid !== undefined && directoryStat.uid !== uid) {
78
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore directory is not owned by the current user.');
79
- }
80
-
81
- if (process.platform !== 'win32') {
82
- try {
83
- fs.chmodSync(directoryPath, 0o700);
84
- directoryStat = fs.lstatSync(directoryPath);
85
- } catch (error) {
86
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Could not secure keystore directory permissions.', { cause: error });
87
- }
88
- if ((directoryStat.mode & 0o777) !== 0o700) {
89
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore directory must have mode 0700.');
90
- }
91
- }
92
- }
93
-
94
- async function derivePublicKey(privateKey: Uint8Array): Promise<Uint8Array> {
95
- if (privateKey.length !== 32) {
96
- throw new KeystoreResolutionError('Ed25519 private seed must be exactly 32 bytes.');
97
- }
98
-
99
- const pkcs8 = new Uint8Array(ED25519_PKCS8_PREFIX.length + privateKey.length);
100
- pkcs8.set(ED25519_PKCS8_PREFIX);
101
- pkcs8.set(privateKey, ED25519_PKCS8_PREFIX.length);
102
- try {
103
- const privateKeyObject = createPrivateKey({
104
- key: Buffer.from(pkcs8.buffer, pkcs8.byteOffset, pkcs8.byteLength),
105
- format: 'der',
106
- type: 'pkcs8',
107
- });
108
- const publicDer = createPublicKey(privateKeyObject).export({ format: 'der', type: 'spki' });
109
- const publicBytes = Buffer.isBuffer(publicDer) ? publicDer : Buffer.from(publicDer);
110
- if (
111
- publicBytes.length !== ED25519_SPKI_PREFIX.length + 32 ||
112
- !ED25519_SPKI_PREFIX.every((byte, index) => publicBytes[index] === byte)
113
- ) {
114
- throw new KeystoreResolutionError('Derived Ed25519 public key has an invalid encoding.');
115
- }
116
- return new Uint8Array(publicBytes.subarray(ED25519_SPKI_PREFIX.length));
117
- } finally {
118
- pkcs8.fill(0);
119
- }
120
- }
121
-
122
- function createSigner(publicKey: Uint8Array, privateKey: Uint8Array): InMemoryEd25519Signer {
123
- try {
124
- return new InMemoryEd25519Signer(publicKey, privateKey);
125
- } finally {
126
- publicKey.fill(0);
127
- privateKey.fill(0);
128
- }
129
- }
130
-
131
- function readKeystoreContents(filePath: string): string {
132
- let pathStat: fs.Stats;
133
- try {
134
- pathStat = fs.lstatSync(filePath);
135
- } catch (error) {
136
- if (isErrno(error, 'ENOENT')) {
137
- throw new KeystoreResolutionError(`Keystore file not found: ${filePath}`, { cause: error, code: 'ENOENT' });
138
- }
139
- throw new KeystoreResolutionError(`Could not inspect keystore file "${filePath}".`, { cause: error });
140
- }
141
- if (pathStat.isSymbolicLink()) {
142
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore file must not be a symbolic link.');
143
- }
144
-
145
- let fd: number;
146
- try {
147
- const noFollow = fsConstants.O_NOFOLLOW ?? 0;
148
- fd = fs.openSync(filePath, fsConstants.O_RDONLY | noFollow);
149
- } catch (error) {
150
- if (isErrno(error, 'ENOENT')) {
151
- throw new KeystoreResolutionError(`Keystore file not found: ${filePath}`, { cause: error, code: 'ENOENT' });
152
- }
153
- if (isErrno(error, 'ELOOP')) {
154
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore file must not be a symbolic link.', { cause: error });
155
- }
156
- throw new KeystoreResolutionError(`Could not open keystore file "${filePath}".`, { cause: error });
157
- }
158
-
159
- try {
160
- const stat = fs.fstatSync(fd);
161
- const currentPathStat = fs.lstatSync(filePath);
162
- if (
163
- currentPathStat.isSymbolicLink() ||
164
- currentPathStat.dev !== stat.dev ||
165
- currentPathStat.ino !== stat.ino ||
166
- !stat.isFile() ||
167
- stat.nlink !== 1
168
- ) {
169
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore must be a regular file with one link.');
170
- }
171
-
172
- const uid = currentUid();
173
- if (uid !== undefined && stat.uid !== uid) {
174
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore file is not owned by the current user.');
175
- }
176
-
177
- if (stat.size > MAX_KEYSTORE_SIZE) {
178
- throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Keystore file exceeds the maximum supported size.');
179
- }
180
-
181
- if (process.platform !== 'win32') {
182
- if ((stat.mode & 0o777) !== 0o600) {
183
- try {
184
- fs.fchmodSync(fd, 0o600);
185
- } catch (error) {
186
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Could not secure keystore permissions (expected 0600).', { cause: error });
187
- }
188
- }
189
- const securedStat = fs.fstatSync(fd);
190
- if ((securedStat.mode & 0o777) !== 0o600) {
191
- throw new KeystoreResolutionError('SECURITY_VIOLATION: Keystore file must have mode 0600.');
192
- }
193
- }
194
-
195
- return fs.readFileSync(fd, 'utf8');
196
- } finally {
197
- fs.closeSync(fd);
198
- }
199
- }
200
-
201
- export async function loadKeystoreFile(filePath: string): Promise<InMemoryEd25519Signer> {
202
- ensurePrivateDirectory(path.dirname(filePath));
203
- const contents = readKeystoreContents(filePath);
204
-
205
- let parsed: unknown;
206
- try {
207
- parsed = JSON.parse(contents);
208
- } catch (error) {
209
- throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Keystore JSON is invalid; refusing to replace the existing identity.', { cause: error });
210
- }
211
-
212
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
213
- throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Keystore must contain a JSON object.');
214
- }
215
- const data = parsed as Record<string, unknown>;
216
- const keys = Object.keys(data).sort();
217
- if (
218
- keys.length !== 3 ||
219
- keys[0] !== 'createdAt' ||
220
- keys[1] !== 'did' ||
221
- keys[2] !== 'privateKeyHex' ||
222
- typeof data.did !== 'string' ||
223
- typeof data.privateKeyHex !== 'string' ||
224
- !/^[0-9a-f]{64}$/.test(data.privateKeyHex) ||
225
- !Number.isSafeInteger(data.createdAt) ||
226
- (data.createdAt as number) <= 0
227
- ) {
228
- throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Keystore fields or values are invalid.');
229
- }
230
-
231
- const privateKey = new Uint8Array(Buffer.from(data.privateKeyHex, 'hex'));
232
- let publicKey: Uint8Array | undefined;
233
- try {
234
- publicKey = await derivePublicKey(privateKey);
235
- const derivedDid = createDidKey(publicKey);
236
- if (data.did !== derivedDid) {
237
- throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Stored DID does not match the DID derived from the private seed.');
238
- }
239
- return createSigner(publicKey, privateKey);
240
- } catch (error) {
241
- privateKey.fill(0);
242
- publicKey?.fill(0);
243
- if (error instanceof KeystoreResolutionError) throw error;
244
- throw new KeystoreResolutionError('CORRUPTED_KEYSTORE: Could not validate the stored identity.', { cause: error });
245
- }
246
- }
247
-
248
- export async function saveKeystoreFile(filePath: string, keystore: AgentKeystoreData): Promise<void> {
249
- const directoryPath = path.dirname(filePath);
250
- ensurePrivateDirectory(directoryPath);
251
-
252
- if (
253
- !keystore ||
254
- typeof keystore.did !== 'string' ||
255
- typeof keystore.privateKeyHex !== 'string' ||
256
- !/^[0-9a-f]{64}$/.test(keystore.privateKeyHex) ||
257
- !Number.isSafeInteger(keystore.createdAt) ||
258
- keystore.createdAt <= 0
259
- ) {
260
- throw new KeystoreResolutionError('Invalid keystore data.');
261
- }
262
-
263
- const privateKey = new Uint8Array(Buffer.from(keystore.privateKeyHex, 'hex'));
264
- let publicKey: Uint8Array | undefined;
265
- try {
266
- publicKey = await derivePublicKey(privateKey);
267
- if (createDidKey(publicKey) !== keystore.did) {
268
- throw new KeystoreResolutionError('Keystore DID does not match the DID derived from the private seed.');
269
- }
270
- } finally {
271
- privateKey.fill(0);
272
- publicKey?.fill(0);
273
- }
274
-
275
- const temporaryPath = `${filePath}.tmp-${process.pid}-${randomBytes(16).toString('hex')}`;
276
- const serialized = `${JSON.stringify(keystore, null, 2)}\n`;
277
- let fd: number | undefined;
278
- let tempCreated = false;
279
- try {
280
- fd = fs.openSync(temporaryPath, 'wx', 0o600);
281
- tempCreated = true;
282
- if (process.platform !== 'win32') {
283
- fs.fchmodSync(fd, 0o600);
284
- }
285
- fs.writeFileSync(fd, serialized, 'utf8');
286
- fs.fsyncSync(fd);
287
- fs.closeSync(fd);
288
- fd = undefined;
289
-
290
- fs.linkSync(temporaryPath, filePath);
291
- fs.unlinkSync(temporaryPath);
292
- tempCreated = false;
293
-
294
- if (process.platform !== 'win32') {
295
- const dirFd = fs.openSync(directoryPath, fsConstants.O_RDONLY);
296
- try {
297
- fs.fsyncSync(dirFd);
298
- } finally {
299
- fs.closeSync(dirFd);
300
- }
301
- }
302
- } catch (error) {
303
- if (fd !== undefined) fs.closeSync(fd);
304
- if (tempCreated) {
305
- try {
306
- fs.unlinkSync(temporaryPath);
307
- } catch (cleanupError) {
308
- if (!isErrno(cleanupError, 'ENOENT')) {
309
- throw new KeystoreResolutionError('Keystore write failed and temporary-file cleanup also failed.', { cause: cleanupError });
310
- }
311
- }
312
- }
313
- if (isErrno(error, 'EEXIST')) {
314
- throw new KeystoreResolutionError(`Keystore already exists: ${filePath}`, { cause: error, code: 'EEXIST' });
315
- }
316
- if (error instanceof KeystoreResolutionError) throw error;
317
- throw new KeystoreResolutionError(`Could not atomically save keystore "${filePath}".`, { cause: error });
318
- }
319
- }
320
-
321
- export async function createNewKeystoreFile(filePath: string): Promise<InMemoryEd25519Signer> {
322
- const keyPair = await generateEd25519KeyPair();
323
- try {
324
- const keystore: AgentKeystoreData = {
325
- did: createDidKey(keyPair.publicKey),
326
- privateKeyHex: Buffer.from(keyPair.privateKey).toString('hex'),
327
- createdAt: Date.now(),
328
- };
329
-
330
- try {
331
- await saveKeystoreFile(filePath, keystore);
332
- } catch (error) {
333
- if (error instanceof KeystoreResolutionError && error.code === 'EEXIST') {
334
- return await loadKeystoreFile(filePath);
335
- }
336
- throw error;
337
- }
338
-
339
- return new InMemoryEd25519Signer(keyPair.publicKey, keyPair.privateKey);
340
- } finally {
341
- keyPair.privateKey.fill(0);
342
- keyPair.publicKey.fill(0);
343
- }
344
- }
345
-
346
- export async function resolveAgentIdentity(options: {
347
- privateKeyHex?: string;
348
- filePath?: string;
349
- } = {}): Promise<LoadedAgentIdentity> {
350
- const envHex = options.privateKeyHex ?? process.env.ROHAN_AGENT_PRIVATE_KEY;
351
- if (envHex !== undefined && envHex.trim() !== '') {
352
- const normalized = envHex.trim().replace(/^0x/i, '');
353
- if (!/^[0-9a-f]{64}$/i.test(normalized)) {
354
- throw new KeystoreResolutionError('ROHAN_AGENT_PRIVATE_KEY is set but is not a valid 32-byte hexadecimal seed.');
355
- }
356
-
357
- const privateKey = new Uint8Array(Buffer.from(normalized, 'hex'));
358
- let publicKey: Uint8Array | undefined;
359
- try {
360
- publicKey = await derivePublicKey(privateKey);
361
- const signer = createSigner(publicKey, privateKey);
362
- return { signer, did: signer.did, source: 'env' };
363
- } catch (error) {
364
- privateKey.fill(0);
365
- publicKey?.fill(0);
366
- if (error instanceof KeystoreResolutionError) throw error;
367
- throw new KeystoreResolutionError('Could not initialize signer from ROHAN_AGENT_PRIVATE_KEY.', { cause: error });
368
- }
369
- }
370
-
371
- const filePath = options.filePath ?? path.join(os.homedir(), '.rohan', 'agent-identity.json');
372
- ensurePrivateDirectory(path.dirname(filePath));
373
-
374
- try {
375
- const signer = await loadKeystoreFile(filePath);
376
- return { signer, did: signer.did, source: 'filesystem', filePath };
377
- } catch (error) {
378
- if (!(error instanceof KeystoreResolutionError) || error.code !== 'ENOENT') {
379
- throw error;
380
- }
381
- }
382
-
383
- const signer = await createNewKeystoreFile(filePath);
384
- return { signer, did: signer.did, source: 'auto-provisioned', filePath };
385
- }
package/src/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './firewall.js';
2
- export * from './gateway.js';