agent-envelope-mcp 1.2.0 → 1.2.2

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.
@@ -1,174 +1,245 @@
1
- import assert from 'node:assert/strict';
2
- import { execFileSync } from 'node:child_process';
3
- import test from 'node:test';
4
- import { fileURLToPath } from 'node:url';
5
- import { Client } from '@modelcontextprotocol/sdk/client/index.js';
6
- import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
7
- import { createServer, decisionFromReport } from '../src/server.js';
8
-
9
- const projectRoot = fileURLToPath(new URL('..', import.meta.url));
10
-
11
- function spawnedToolNames(env) {
12
- return execFileSync(
13
- process.execPath,
14
- [
15
- '-e',
16
- "import('./src/server.js').then(({createServer})=>console.log(Object.keys(createServer()._registeredTools||{}).sort().join(',')))",
17
- ],
18
- {
19
- cwd: projectRoot,
20
- env,
21
- encoding: 'utf8',
22
- },
23
- ).trim().split(',').filter(Boolean);
24
- }
25
-
26
- test('registers mint tool by default', () => {
27
- const { AE_TOOLS: _aeTools, ...env } = process.env;
28
- const names = spawnedToolNames(env);
29
- assert.ok(names.includes('ae_mint'));
30
- assert.ok(names.includes('ae_register_delegated_action'));
31
- });
32
-
33
- test('AE_TOOLS=readonly omits mint tool', () => {
34
- const names = spawnedToolNames({ ...process.env, AE_TOOLS: 'readonly' });
35
- assert.equal(names.includes('ae_mint'), false);
36
- assert.equal(names.includes('ae_register_delegated_action'), false);
37
- });
38
-
39
- test('delegated action registration uses the hosted registration route', async () => {
40
- const previousKey = process.env.AE_API_KEY;
41
- const previousFetch = globalThis.fetch;
42
- let request;
43
- process.env.AE_API_KEY = 'test-api-key';
44
- globalThis.fetch = async (url, init) => {
45
- request = { url, init };
46
- return new Response(JSON.stringify({
47
- statusCode: 201,
48
- headers: { 'content-type': 'application/json' },
49
- body: JSON.stringify({ recordId: 'ae-action-test' }),
50
- }), {
51
- status: 200,
52
- headers: { 'content-type': 'application/json' },
53
- });
54
- };
55
-
56
- try {
57
- const server = createServer();
58
- const result = await server._registeredTools.ae_register_delegated_action.handler({
59
- record: { recordId: 'ae-action-test' },
60
- request: { requestId: 'request-test' },
61
- delegateId: 'ae-delegate-test0001',
62
- });
63
-
64
- assert.equal(result.isError, undefined);
65
- assert.equal(result.structuredContent.recordId, 'ae-action-test');
66
- assert.ok(request.url.endsWith('/sovereign/agents/register-delegated'));
67
- assert.equal(request.init.headers['X-Api-Key'], 'test-api-key');
68
- assert.deepEqual(JSON.parse(request.init.body), {
69
- record: { recordId: 'ae-action-test' },
70
- request: { requestId: 'request-test' },
71
- delegateId: 'ae-delegate-test0001',
72
- });
73
- } finally {
74
- globalThis.fetch = previousFetch;
75
- if (previousKey === undefined) delete process.env.AE_API_KEY;
76
- else process.env.AE_API_KEY = previousKey;
77
- }
78
- });
79
-
80
- test('delegated action registration accepts the canonical domain projection over MCP', async () => {
81
- const previousKey = process.env.AE_API_KEY;
82
- const previousFetch = globalThis.fetch;
83
- let called = false;
84
- process.env.AE_API_KEY = 'test-api-key';
85
- globalThis.fetch = async () => {
86
- called = true;
87
- return new Response(JSON.stringify({ recordId: 'ae-action-test' }), {
88
- status: 200,
89
- headers: { 'content-type': 'application/json' },
90
- });
91
- };
92
- const server = createServer();
93
- const client = new Client({ name: 'domain-projection-test', version: '1.0.0' });
94
- const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
95
-
96
- try {
97
- await server.connect(serverTransport);
98
- await client.connect(clientTransport);
99
- const domainHash = `0x${'1'.repeat(64)}`;
100
- const domainAddress = `0x${'2'.repeat(40)}`;
101
- const actionEnvelopeHash = `0x${'3'.repeat(64)}`;
102
- const result = await client.callTool({
103
- name: 'ae_register_delegated_action',
104
- arguments: {
105
- record: {
106
- type: 'agentenvelope.publicActionRecord',
107
- version: 1,
108
- recordId: 'ae-action-test',
109
- agentId: 'mobile:device-01:0',
110
- agentAddress: `0x${'4'.repeat(40)}`,
111
- status: 'active',
112
- domain: {
113
- domainInfo: {
114
- type: 'agentenvelope.domainInfo',
115
- version: 1,
116
- namespace: 'mobile-testing',
117
- domainId: 'hmgcc-mobile-mimic',
118
- kind: 'device',
119
- },
120
- canonicalDomainInfo: '{}',
121
- domainHash,
122
- domainAddress,
123
- domainFingerprint: 'ae-domain-test',
124
- createdAt: '2026-09-26T15:51:06.679Z',
125
- },
126
- actionEnvelope: { actionIndex: 0 },
127
- actionEnvelopeHash,
128
- expiry: null,
129
- },
130
- request: { requestId: 'request-test' },
131
- delegateId: 'ae-delegate-test0001',
132
- },
133
- });
134
-
135
- assert.equal(result.isError, undefined);
136
- assert.equal(called, true);
137
- } finally {
138
- await client.close();
139
- await server.close();
140
- globalThis.fetch = previousFetch;
141
- if (previousKey === undefined) delete process.env.AE_API_KEY;
142
- else process.env.AE_API_KEY = previousKey;
143
- }
144
- });
145
-
146
- test('decisionFromReport fails closed when operation is requested but absent from report envelope', () => {
147
- const decision = decisionFromReport(
148
- { valid: true, envelope: { resources: ['refund:123'] } },
149
- { agentId: 'agent-1', actionIndex: 0, operation: 'refund', resource: 'refund:123' },
150
- );
151
-
152
- assert.equal(decision.allowed, false);
153
- assert.equal(decision.reason, 'operation_missing');
154
- });
155
-
156
- test('decisionFromReport fails closed when resource is requested but absent from report envelope', () => {
157
- const decision = decisionFromReport(
158
- { valid: true, envelope: { operation: 'refund' } },
159
- { agentId: 'agent-1', actionIndex: 0, operation: 'refund', resource: 'refund:123' },
160
- );
161
-
162
- assert.equal(decision.allowed, false);
163
- assert.equal(decision.reason, 'resources_missing');
164
- });
165
-
166
- test('decisionFromReport allows matching operation and resource', () => {
167
- const decision = decisionFromReport(
168
- { valid: true, envelope: { operation: 'refund', resources: ['refund:*'] } },
169
- { agentId: 'agent-1', actionIndex: 0, operation: 'refund', resource: 'refund:123' },
170
- );
171
-
172
- assert.equal(decision.allowed, true);
173
- assert.equal(decision.reason, 'verified');
174
- });
1
+ import assert from 'node:assert/strict';
2
+ import { execFileSync, spawnSync } from 'node:child_process';
3
+ import test from 'node:test';
4
+ import { buildMintDelegate, buildMintRequest, canonicalJSON, contentHash, hexToBytes, mintActionCapability, seedAddress, signAction } from 'agent-envelope-sdk';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
7
+ import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
8
+ import { createServer, decisionFromReport } from '../src/server.js';
9
+
10
+ const projectRoot = fileURLToPath(new URL('..', import.meta.url));
11
+
12
+ function spawnedToolNames(env) {
13
+ return execFileSync(
14
+ process.execPath,
15
+ [
16
+ '-e',
17
+ "import('./src/server.js').then(({createServer})=>console.log(Object.keys(createServer()._registeredTools||{}).sort().join(',')))",
18
+ ],
19
+ {
20
+ cwd: projectRoot,
21
+ env,
22
+ encoding: 'utf8',
23
+ },
24
+ ).trim().split(',').filter(Boolean);
25
+ }
26
+
27
+ test('registers mint tool by default', () => {
28
+ const { AE_TOOLS: _aeTools, ...env } = process.env;
29
+ const names = spawnedToolNames(env);
30
+ assert.ok(names.includes('ae_mint'));
31
+ assert.ok(names.includes('ae_register_delegated_action'));
32
+ });
33
+
34
+ test('AE_TOOLS=readonly omits mint tool', () => {
35
+ const names = spawnedToolNames({ ...process.env, AE_TOOLS: 'readonly' });
36
+ assert.equal(names.includes('ae_mint'), false);
37
+ assert.equal(names.includes('ae_register_delegated_action'), false);
38
+ assert.ok(names.includes('ae_verify_action'));
39
+ assert.ok(names.includes('ae_check_legitimacy'));
40
+ });
41
+
42
+ test('AE_TOOLS=sovereign exposes only offline sovereign verification', () => {
43
+ const names = spawnedToolNames({ ...process.env, AE_TOOLS: 'sovereign' });
44
+ assert.deepEqual(names, [
45
+ 'ae_verify_sovereign',
46
+ 'ae_verify_sovereign_record',
47
+ ]);
48
+ });
49
+
50
+ test('an explicit unknown or blank mode stops the CLI before it exposes tools', () => {
51
+ for (const mode of ['soverign', '', ' ']) {
52
+ const result = spawnSync(process.execPath, ['bin/agent-envelope-mcp.js'], {
53
+ cwd: projectRoot, env: { ...process.env, AE_TOOLS: mode }, encoding: 'utf8', timeout: 5000,
54
+ });
55
+ assert.equal(result.status, 1);
56
+ assert.match(result.stderr, /Invalid AE_TOOLS setting/);
57
+ assert.equal(result.stdout, '');
58
+ }
59
+ assert.deepEqual(spawnedToolNames({ ...process.env, AE_TOOLS: ' Read-Only ' }),
60
+ spawnedToolNames({ ...process.env, AE_TOOLS: 'readonly' }));
61
+ });
62
+
63
+ async function connectClient(t) {
64
+ const server = createServer();
65
+ const client = new Client({ name: 'mcp-integration-test', version: '1.0.0' });
66
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
67
+ await server.connect(serverTransport);
68
+ await client.connect(clientTransport);
69
+ t.after(async () => { await client.close(); await server.close(); });
70
+ return client;
71
+ }
72
+
73
+ function hostedFetch(t, handler) {
74
+ const previousKey = process.env.AE_API_KEY;
75
+ process.env.AE_API_KEY = 'test-api-key';
76
+ t.after(() => {
77
+ if (previousKey === undefined) delete process.env.AE_API_KEY;
78
+ else process.env.AE_API_KEY = previousKey;
79
+ });
80
+ return t.mock.method(globalThis, 'fetch', handler);
81
+ }
82
+
83
+ function signedMint(legitimacyRef) {
84
+ const now = new Date().toISOString();
85
+ const seed = n => new Uint8Array(32).fill(n);
86
+ const domainInfo = { type: 'agentenvelope.domainInfo', version: 1, namespace: 'test', domainId: 'cold-room', kind: 'device' };
87
+ const domain = {
88
+ domainInfo, canonicalDomainInfo: canonicalJSON(domainInfo), domainHash: contentHash(domainInfo),
89
+ domainAddress: seedAddress(seed(1)), domainFingerprint: 'ae-domain-test', createdAt: now,
90
+ };
91
+ const delegate = buildMintDelegate(seed(1), {
92
+ domainHash: domain.domainHash, legitimacyRef, allowedOperations: ['read'], allowedResources: ['sensor:1'],
93
+ botPolicy: 'any-signed-bot', actionIndexPolicy: { min: 0, max: 5 }, maxMints: 5, maxUsesPerAction: 1,
94
+ timeWindow: { notBefore: null, notAfter: null }, nonce: '0x' + 'ab'.repeat(32), issuedAt: now,
95
+ });
96
+ const request = buildMintRequest(seed(2), delegate, {
97
+ agentId: 'fridge.reader', operation: 'read', resources: ['sensor:1'], actionIndex: 0, maxUses: 1,
98
+ legitimacyId: legitimacyRef?.legitimacyId,
99
+ timeWindow: delegate.timeWindow, nonce: 'test-mint-1', requestedAt: now,
100
+ });
101
+ const capability = mintActionCapability(seed(3), delegate, request);
102
+ const actionEnvelope = {
103
+ type: 'agentenvelope.actionEnvelope', version: 1, agentId: request.agentId,
104
+ domain: { domainId: domainInfo.domainId, domainHash: domain.domainHash },
105
+ actionIndex: 0, operation: request.operation, resources: request.resources, timeWindow: request.timeWindow,
106
+ decayPolicy: { mode: 'ACTION' }, limits: { maxUses: 1, enforcement: 'external' },
107
+ };
108
+ const record = {
109
+ type: 'agentenvelope.publicActionRecord', version: 1, recordId: 'ae-action-test', ownerUserId: 'test',
110
+ custodyMode: 'remote-mint-delegate', verifierProfile: 'domain-action-envelope', createdAt: now,
111
+ agentId: request.agentId, agentAddress: capability.agentAddress, status: 'active', domain,
112
+ actionEnvelope, canonicalActionEnvelope: canonicalJSON(actionEnvelope), actionEnvelopeHash: contentHash(actionEnvelope), expiry: null,
113
+ };
114
+ const payload = { sensor: 1 };
115
+ const signature = signAction(hexToBytes(capability.actionSeedHex), payload);
116
+ return { delegate, request, record, payload, signature };
117
+ }
118
+
119
+ test('offline MCP verifies SDK-signed records in both supported domain projections', async t => {
120
+ const fetch = t.mock.method(globalThis, 'fetch', () => { throw new Error('offline tool used the network'); });
121
+ const client = await connectClient(t);
122
+ const { record, payload, signature } = signedMint();
123
+ const verify = candidate => client.callTool({ name: 'ae_verify_sovereign_record', arguments: {
124
+ record: candidate, payload, signature, actionIndex: 0, expectedActionEnvelopeHash: record.actionEnvelopeHash,
125
+ } });
126
+ for (const domain of [record.domain, record.actionEnvelope.domain]) {
127
+ assert.equal((await verify({ ...record, domain })).structuredContent.valid, true);
128
+ }
129
+ const rejected = await verify({ ...record, canonicalActionEnvelope: '{}' });
130
+ assert.equal(rejected.structuredContent.valid, false);
131
+ assert.equal(fetch.mock.callCount(), 0);
132
+ });
133
+
134
+ test('hosted mint and registration preserve signed inputs and require matching references', async t => {
135
+ const { delegate, request, record } = signedMint();
136
+ const calls = [];
137
+ hostedFetch(t, async (url, init) => {
138
+ calls.push({ path: new URL(url).pathname, body: JSON.parse(init.body), key: init.headers['X-Api-Key'] });
139
+ return new Response(JSON.stringify({ statusCode: 200, body: JSON.stringify({ valid: true }) }));
140
+ });
141
+ const client = await connectClient(t);
142
+ const mint = (permit, req) => client.callTool({ name: 'ae_mint', arguments: { delegate: permit, request: req } });
143
+ const invalidScope = buildMintRequest(new Uint8Array(32).fill(2), delegate, { ...request, maxUses: null });
144
+ assert.equal((await mint(delegate, invalidScope)).isError, true);
145
+ assert.equal((await mint({ ...delegate, delegateId: 'ae-delegate-wrong-id' }, request)).isError, true);
146
+ assert.equal(calls.length, 0);
147
+ assert.equal((await mint(delegate, request)).structuredContent.valid, true);
148
+ const register = delegateId => client.callTool({
149
+ name: 'ae_register_delegated_action', arguments: { delegateId, request, record },
150
+ });
151
+ assert.equal((await register('ae-delegate-wrong-id')).isError, true);
152
+ assert.equal((await register(delegate.delegateId)).isError, undefined);
153
+ assert.equal(calls.length, 2);
154
+ assert.ok(calls[0].path.endsWith('/sovereign/mint'));
155
+ assert.ok(calls[1].path.endsWith('/sovereign/agents/register-delegated'));
156
+ assert.ok(calls.every(call => call.key === 'test-api-key'));
157
+ assert.deepEqual(calls[0].body, { delegate, request });
158
+ assert.deepEqual(calls[1].body, { delegateId: delegate.delegateId, request, record });
159
+ });
160
+
161
+ test('a valid signed mint still needs hosted admission', async t => {
162
+ const { delegate, request } = signedMint();
163
+ hostedFetch(t, async () => new Response(JSON.stringify({
164
+ code: 'MINT_LIMIT_REACHED', error: 'delegate mint limit reached',
165
+ }), { status: 409 }));
166
+ const client = await connectClient(t);
167
+ const result = await client.callTool({ name: 'ae_mint', arguments: { delegate, request } });
168
+ assert.equal(result.isError, true);
169
+ assert.equal(result.structuredContent.code, 'MINT_LIMIT_REACHED');
170
+ });
171
+
172
+ test('mint precheck returns hosted legitimacy codes and details before contacting the portal', async t => {
173
+ const requiredLegitimacyId = 'ae-legit-test0001';
174
+ const { delegate, request } = signedMint({ required: true, legitimacyId: requiredLegitimacyId });
175
+ const fetch = hostedFetch(t, () => { throw new Error('unexpected hosted request'); });
176
+ const client = await connectClient(t);
177
+ for (const [legitimacyId, code] of [
178
+ [undefined, 'LEGITIMACY_REF_REQUIRED'], [' ', 'LEGITIMACY_REF_REQUIRED'],
179
+ ['ae-legit-test0002', 'LEGITIMACY_SCOPE_MISMATCH'],
180
+ ]) {
181
+ const signed = buildMintRequest(new Uint8Array(32).fill(2), delegate, { ...request, legitimacyId });
182
+ const result = await client.callTool({ name: 'ae_mint', arguments: { delegate, request: signed } });
183
+ assert.equal(result.isError, true);
184
+ assert.equal(result.structuredContent.code, code);
185
+ assert.equal(result.structuredContent.message, result.structuredContent.error);
186
+ assert.deepEqual(result.structuredContent.legitimacy, {
187
+ requiredLegitimacyId, ...(code === 'LEGITIMACY_SCOPE_MISMATCH' ? { suppliedLegitimacyId: legitimacyId } : {}),
188
+ });
189
+ }
190
+ assert.equal(fetch.mock.callCount(), 0);
191
+ });
192
+
193
+ test('legitimacy uses the SDK expiry rules and binds the hosted state to the requested ID', async t => {
194
+ const legitimacyId = 'ae-legit-test0001';
195
+ let state = { type: 'agentenvelope.legitimacyState', version: 1, legitimacyId, status: 'legitimate' };
196
+ hostedFetch(t, async () => new Response(JSON.stringify({ state })));
197
+ const client = await connectClient(t);
198
+ const check = async () => (await client.callTool({ name: 'ae_check_legitimacy', arguments: { legitimacyId } })).structuredContent;
199
+ assert.equal((await check()).allowed, true);
200
+ for (const [expiresAt, allowed] of [[null, true], ['', false], ['invalid-date', false], ['2000-01-01T00:00:00Z', false]]) {
201
+ state = { ...state, expiresAt };
202
+ assert.equal((await check()).allowed, allowed);
203
+ }
204
+ state = { ...state, expiresAt: null, legitimacyId: 'ae-legit-another1' };
205
+ assert.equal((await check()).allowed, false);
206
+ });
207
+
208
+ test('decisionFromReport fails closed when operation is requested but absent from report envelope', () => {
209
+ const decision = decisionFromReport(
210
+ { valid: true, agentId: 'agent-1', actionIndex: 0, envelope: { resources: ['refund:123'] } },
211
+ { agentId: 'agent-1', actionIndex: 0, operation: 'refund', resource: 'refund:123' },
212
+ );
213
+
214
+ assert.equal(decision.allowed, false);
215
+ assert.equal(decision.reason, 'operation_missing');
216
+ });
217
+
218
+ test('decisionFromReport fails closed when resource is requested but absent from report envelope', () => {
219
+ const decision = decisionFromReport(
220
+ { valid: true, agentId: 'agent-1', actionIndex: 0, envelope: { operation: 'refund' } },
221
+ { agentId: 'agent-1', actionIndex: 0, operation: 'refund', resource: 'refund:123' },
222
+ );
223
+
224
+ assert.equal(decision.allowed, false);
225
+ assert.equal(decision.reason, 'resources_missing');
226
+ });
227
+
228
+ test('decisionFromReport allows matching operation and resource', () => {
229
+ const decision = decisionFromReport(
230
+ { valid: true, agentId: 'agent-1', actionIndex: 0, envelope: { operation: 'refund', resources: ['refund:*'] } },
231
+ { agentId: 'agent-1', actionIndex: 0, operation: 'refund', resource: 'refund:123' },
232
+ );
233
+
234
+ assert.equal(decision.allowed, true);
235
+ assert.equal(decision.reason, 'verified');
236
+ });
237
+
238
+ test('authorization requires a boolean verdict for the requested agent, index and envelope', () => {
239
+ const input = { agentId: 'agent-1', actionIndex: 0, expectedActionEnvelopeHash: '0x' + '12'.repeat(32) };
240
+ const report = { valid: true, agentId: input.agentId, actionIndex: 0, actionEnvelopeHash: input.expectedActionEnvelopeHash };
241
+ assert.equal(decisionFromReport(report, input).allowed, true);
242
+ for (const fields of [{ valid: 'false' }, { valid: 1 }, { agentId: 'other' }, { actionIndex: 1 }, { actionEnvelopeHash: undefined }]) {
243
+ assert.equal(decisionFromReport({ ...report, ...fields }, input).allowed, false);
244
+ }
245
+ });