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.
package/src/server.js CHANGED
@@ -1,615 +1,667 @@
1
- /**
2
- * AgentEnvelope MCP server: the MCP adapter for AgentEnvelope.
3
- *
4
- * Any MCP client can call these tools to verify delegated action authority
5
- * before the runtime executes a real action. Sovereign verification is local
6
- * and free. Hosted governance uses API-key protected AgentEnvelope routes for
7
- * records, legitimacy, delegates, verification reports, and mint receipts.
8
- */
9
-
10
- import { randomUUID } from 'node:crypto';
11
- import { createServer as createHttpServer } from 'node:http';
12
- import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
13
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
14
- import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
15
- import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
16
- import { z } from 'zod';
17
- import { AgentEnvelopeClient } from 'agent-envelope-sdk/client';
18
- import { verifyAction as verifyActionSovereign, verifyRecord as verifyRecordSovereign } from 'agent-envelope-sdk';
19
-
20
- const HOSTED_BASE_URL = process.env.AE_API_BASE_URL?.trim() || 'https://jemdjwteae.execute-api.us-east-1.amazonaws.com/v1';
21
- const SERVER_VERSION = '1.2.0';
22
- const NEEDS_KEY =
23
- 'AE_API_KEY is not set. This is a hosted-governance tool; set the portal-issued API key to use it. Sovereign signature and record verification need no key.';
24
- const TOOLS_MODE = process.env.AE_TOOLS?.trim().toLowerCase() || 'all';
25
- const MINT_ENABLED = TOOLS_MODE !== 'readonly' && TOOLS_MODE !== 'read-only';
26
- const MAX_HOSTED_CLIENTS = 100;
27
- const HTTP_SESSION_IDLE_MS = Number.parseInt(process.env.AE_MCP_SESSION_IDLE_MS || '', 10) || 30 * 60 * 1000;
28
- const HTTP_SESSION_SWEEP_MS = Math.min(60 * 1000, Math.max(5 * 1000, Math.floor(HTTP_SESSION_IDLE_MS / 2)));
29
-
30
- const encoder = new TextEncoder();
31
- const MAX_SIGNED_MESSAGE_BYTES = 64 * 1024;
32
- const MAX_RECORD_BYTES = 256 * 1024;
33
- const MAX_MINT_OBJECT_BYTES = 256 * 1024;
34
- const AGENT_ID = /^[a-zA-Z0-9_:-]{1,128}$/;
35
- const ADDRESS = /^0x[a-fA-F0-9]{40}$/;
36
- const HASH = /^0x[a-fA-F0-9]{64}$/;
37
- const SIGNATURE = /^0x[a-fA-F0-9]{130}$/;
38
- const DELEGATE_ID = /^ae-delegate-[a-zA-Z0-9_-]{8,128}$/;
39
- const LEGITIMACY_ID = /^ae-legit-[a-zA-Z0-9_-]{8,128}$/;
40
- const SAFE_TEXT_ID = /^[a-zA-Z0-9_:.*/-]{1,256}$/;
41
-
42
- const hostedClients = new Map();
43
-
44
- function getApiKey(extra) {
45
- const bearer = extra?.authInfo?.token?.trim();
46
- return bearer || process.env.AE_API_KEY?.trim() || null;
47
- }
48
-
49
- function governanceClient(extra) {
50
- const apiKey = getApiKey(extra);
51
- if (!apiKey) return null;
52
- if (hostedClients.has(apiKey)) {
53
- const client = hostedClients.get(apiKey);
54
- hostedClients.delete(apiKey);
55
- hostedClients.set(apiKey, client);
56
- return client;
57
- }
58
- hostedClients.set(apiKey, new AgentEnvelopeClient({ apiKey }));
59
- if (hostedClients.size > MAX_HOSTED_CLIENTS) {
60
- const oldestKey = hostedClients.keys().next().value;
61
- if (oldestKey) hostedClients.delete(oldestKey);
62
- }
63
- return hostedClients.get(apiKey);
64
- }
65
-
66
- function isPlainObject(value) {
67
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
68
- }
69
-
70
- function unwrapProxyResponse(value) {
71
- if (!isPlainObject(value) || !Number.isInteger(value.statusCode) || !('body' in value)) return value;
72
- let body = value.body;
73
- if (typeof body === 'string') {
74
- try {
75
- body = JSON.parse(body);
76
- } catch {
77
- body = { message: body };
78
- }
79
- }
80
- if (value.statusCode >= 400) {
81
- const error = new Error(body?.message || body?.error || `AgentEnvelope API error ${value.statusCode}`);
82
- error.status = value.statusCode;
83
- error.body = body;
84
- throw error;
85
- }
86
- return body;
87
- }
88
-
89
- function jsonByteLength(value) {
90
- try {
91
- return encoder.encode(JSON.stringify(value)).length;
92
- } catch {
93
- return Infinity;
94
- }
95
- }
96
-
97
- function jsonWithin(maxBytes, label) {
98
- return z.unknown().refine((value) => jsonByteLength(value) <= maxBytes, {
99
- message: `${label} exceeds ${maxBytes} JSON bytes`,
100
- });
101
- }
102
-
103
- function summaryText(value) {
104
- if (isPlainObject(value)) {
105
- if ('allowed' in value) return value.allowed ? 'AgentEnvelope allowed the action.' : 'AgentEnvelope denied the action.';
106
- if ('valid' in value) return value.valid ? 'AgentEnvelope verification passed.' : 'AgentEnvelope verification failed.';
107
- if ('delegateId' in value) return `AgentEnvelope delegate result: ${value.delegateId}`;
108
- if ('legitimacyId' in value) return `AgentEnvelope legitimacy result: ${value.legitimacyId}`;
109
- }
110
- return JSON.stringify(value, null, 2);
111
- }
112
-
113
- function ok(value, text = summaryText(value)) {
114
- return {
115
- content: [{ type: 'text', text }],
116
- ...(isPlainObject(value) ? { structuredContent: value } : {}),
117
- };
118
- }
119
-
120
- function fail(message, details) {
121
- return {
122
- content: [{ type: 'text', text: message }],
123
- ...(details && isPlainObject(details) ? { structuredContent: details } : {}),
124
- isError: true,
125
- };
126
- }
127
-
128
- function hostedResult(value, fallback) {
129
- const normalized = unwrapProxyResponse(value);
130
- if (normalized && typeof normalized === 'object' && !Array.isArray(normalized) && 'error' in normalized) {
131
- return fail(`${fallback}: ${String(normalized.error)}`, normalized);
132
- }
133
- return ok(normalized);
134
- }
135
-
136
- function errorBody(err) {
137
- if (err && typeof err === 'object' && 'body' in err && err.body && typeof err.body === 'object') return err.body;
138
- return null;
139
- }
140
-
141
- async function hostedJson(path, init, extra) {
142
- const apiKey = getApiKey(extra);
143
- if (!apiKey) throw new Error(NEEDS_KEY);
144
- const res = await fetch(HOSTED_BASE_URL + path, {
145
- ...init,
146
- headers: {
147
- 'Content-Type': 'application/json',
148
- 'X-Api-Key': apiKey,
149
- ...(init?.headers ?? {}),
150
- },
151
- });
152
- const body = await res.json().catch(() => null);
153
- if (!res.ok) {
154
- const err = new Error(body?.message || body?.error || `AgentEnvelope API error ${res.status}`);
155
- err.status = res.status;
156
- err.body = body;
157
- throw err;
158
- }
159
- return body;
160
- }
161
-
162
- function extractBearer(req) {
163
- const header = req.headers.authorization;
164
- if (typeof header !== 'string') return null;
165
- const [scheme, token] = header.split(/\s+/, 2);
166
- if (scheme?.toLowerCase() !== 'bearer' || !token?.trim()) return null;
167
- return token.trim();
168
- }
169
-
170
- function jsonResponse(res, statusCode, body) {
171
- res.writeHead(statusCode, { 'content-type': 'application/json' });
172
- res.end(JSON.stringify(body));
173
- }
174
-
175
- async function readJsonBody(req) {
176
- const chunks = [];
177
- for await (const chunk of req) chunks.push(chunk);
178
- if (chunks.length === 0) return undefined;
179
- const text = Buffer.concat(chunks).toString('utf8');
180
- if (!text.trim()) return undefined;
181
- return JSON.parse(text);
182
- }
183
-
184
- export function decisionFromReport(report, input) {
185
- const reportValid = Boolean(report?.valid);
186
- const hasOperation = typeof report?.envelope?.operation === 'string';
187
- const hasResources = Array.isArray(report?.envelope?.resources);
188
- const operationMatches = !input.operation || (hasOperation && report.envelope.operation === input.operation);
189
- const resourceMatches = !input.resource || (hasResources && resourceAllowed(report.envelope.resources, input.resource));
190
- const valid = reportValid && operationMatches && resourceMatches;
191
- const reason = valid
192
- ? 'verified'
193
- : !reportValid
194
- ? (report?.reason || report?.legitimacyReason || 'verification_failed')
195
- : !operationMatches
196
- ? (hasOperation ? 'operation_mismatch' : 'operation_missing')
197
- : (hasResources ? 'resource_mismatch' : 'resources_missing');
198
- return {
199
- type: 'agentenvelope.authorizationDecision',
200
- version: 1,
201
- allowed: valid,
202
- decision: valid ? 'allowed' : 'denied',
203
- reason,
204
- message: valid ? 'AgentEnvelope verified authority for this action.' : `AgentEnvelope denied this action: ${reason}`,
205
- agentId: input.agentId,
206
- ...(input.operation ? { operation: input.operation } : {}),
207
- ...(input.resource ? { resource: input.resource } : {}),
208
- ...(input.actionIndex !== undefined ? { actionIndex: input.actionIndex } : {}),
209
- checkedAt: report?.checkedAt ?? new Date().toISOString(),
210
- ...(report?.recordId ? { recordId: report.recordId } : {}),
211
- ...(report?.actionEnvelopeHash ? { actionEnvelopeHash: report.actionEnvelopeHash } : {}),
212
- ...(report?.expectedActionEnvelopeHash ? { expectedActionEnvelopeHash: report.expectedActionEnvelopeHash } : {}),
213
- ...(report?.legitimacyRef ? { legitimacyRef: report.legitimacyRef } : {}),
214
- report,
215
- };
216
- }
217
-
218
- function resourceAllowed(allowedResources, resource) {
219
- const prefix = resource.split(':')[0];
220
- return allowedResources.some((allowed) => allowed === resource || allowed === `${prefix}:*` || allowed === '*');
221
- }
222
-
223
- const signedMessageSchema = jsonWithin(MAX_SIGNED_MESSAGE_BYTES, 'signed message');
224
- const mintObjectSchema = jsonWithin(MAX_MINT_OBJECT_BYTES, 'mint object');
225
- const agentIdSchema = z.string().regex(AGENT_ID, 'agentId must be 1-128 characters: letters, numbers, underscore, colon, or hyphen');
226
- const addressSchema = z.string().regex(ADDRESS, 'address must be a 0x-prefixed 20-byte hex address');
227
- const hashSchema = z.string().regex(HASH, 'hash must be a 0x-prefixed 32-byte hex value');
228
- const signatureSchema = z.string().regex(SIGNATURE, 'signature must be a 0x-prefixed 65-byte recoverable signature');
229
- const delegateIdSchema = z.string().regex(DELEGATE_ID, 'delegateId must be an ae-delegate id');
230
- const legitimacyIdSchema = z.string().regex(LEGITIMACY_ID, 'legitimacyId must be an ae-legit id');
231
- const operationSchema = z.string().regex(SAFE_TEXT_ID, 'operation contains unsupported characters');
232
- const resourceSchema = z.string().regex(SAFE_TEXT_ID, 'resource contains unsupported characters');
233
-
234
- const publicActionRecordSchema = z.object({
235
- type: z.literal('agentenvelope.publicActionRecord'),
236
- version: z.literal(1),
237
- recordId: z.string().min(1).max(256),
238
- agentId: agentIdSchema,
239
- agentAddress: addressSchema,
240
- status: z.string().min(1).max(32),
241
- domain: z.object({
242
- domainInfo: z.object({
243
- type: z.literal('agentenvelope.domainInfo'),
244
- version: z.literal(1),
245
- namespace: z.string().min(1).max(128),
246
- domainId: z.string().min(1).max(128),
247
- kind: z.string().min(1).max(128),
248
- }).passthrough(),
249
- canonicalDomainInfo: z.string().min(1).max(4096),
250
- domainHash: hashSchema,
251
- domainAddress: addressSchema,
252
- domainFingerprint: z.string().min(1).max(128),
253
- createdAt: z.string().min(1).max(64),
254
- }).passthrough(),
255
- actionEnvelope: z.object({
256
- actionIndex: z.number().int().nonnegative(),
257
- }).passthrough(),
258
- actionEnvelopeHash: hashSchema,
259
- expiry: z.string().nullable().optional(),
260
- }).passthrough().refine((value) => jsonByteLength(value) <= MAX_RECORD_BYTES, {
261
- message: `public action record exceeds ${MAX_RECORD_BYTES} JSON bytes`,
262
- });
263
-
264
- const readOnlyLocal = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
265
- const readOnlyHosted = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
266
- const governedHosted = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
267
-
268
- export function createServer() {
269
- const server = new McpServer({ name: 'agent-envelope', version: SERVER_VERSION });
270
-
271
- server.registerTool(
272
- 'ae_verify_sovereign',
273
- {
274
- title: 'Verify signature (sovereign, offline)',
275
- description:
276
- 'Signature-only check: verify a signed message against a known agent address. Pure crypto, no vault, no API key, no network. This does not check scope, expiry, usage limits, or hosted record status.',
277
- annotations: readOnlyLocal,
278
- inputSchema: {
279
- message: signedMessageSchema.describe('The exact signed message value'),
280
- signature: signatureSchema.describe('0x-prefixed 65-byte signature'),
281
- expectedAddress: addressSchema.describe("The agent's 0x address to check against"),
282
- },
283
- },
284
- async ({ message, signature, expectedAddress }) => {
285
- try {
286
- return ok(verifyActionSovereign({ message, signature, expectedAddress }));
287
- } catch (err) {
288
- return fail(err instanceof Error ? err.message : 'verification failed');
289
- }
290
- },
291
- );
292
-
293
- server.registerTool(
294
- 'ae_verify_sovereign_record',
295
- {
296
- title: 'Verify public action record (sovereign, offline)',
297
- description:
298
- 'Verify a signed action against a public action record. Checks record status, action index, signature/address match, optional expected envelope hash, and time decay. No API key or network call.',
299
- annotations: readOnlyLocal,
300
- inputSchema: {
301
- record: publicActionRecordSchema.describe('The public action record received from AgentEnvelope or another trusted store'),
302
- actionIndex: z.number().int().nonnegative().describe('The action index being invoked'),
303
- payload: signedMessageSchema.describe('The exact signed action payload'),
304
- signature: signatureSchema.describe('0x-prefixed 65-byte signature'),
305
- expectedActionEnvelopeHash: hashSchema.optional().describe('Optional expected action-envelope hash'),
306
- },
307
- },
308
- async ({ record, actionIndex, payload, signature, expectedActionEnvelopeHash }) => {
309
- try {
310
- return ok(verifyRecordSovereign(record, { payload, signature, actionIndex, expectedActionEnvelopeHash }));
311
- } catch (err) {
312
- return fail(err instanceof Error ? err.message : 'record verification failed');
313
- }
314
- },
315
- );
316
-
317
- server.registerTool(
318
- 'ae_get_agent',
319
- {
320
- title: 'Look up registered agent',
321
- description: 'Fetch the hosted public record for an agent id. Requires a portal-issued API key.',
322
- annotations: readOnlyHosted,
323
- inputSchema: {
324
- agentId: agentIdSchema.describe('The registered agent id'),
325
- },
326
- },
327
- async ({ agentId }, extra) => {
328
- const client = governanceClient(extra);
329
- if (!client) return fail(NEEDS_KEY);
330
- try {
331
- return hostedResult(await client.getAgent(agentId), 'lookup failed');
332
- } catch (err) {
333
- return fail(err instanceof Error ? err.message : 'lookup failed', errorBody(err));
334
- }
335
- },
336
- );
337
-
338
- server.registerTool(
339
- 'ae_verify_action',
340
- {
341
- title: 'Verify action (hosted record)',
342
- description: 'Verify a signed action against the hosted public record for an agent. Requires a portal-issued API key.',
343
- annotations: readOnlyHosted,
344
- inputSchema: {
345
- agentId: agentIdSchema.describe('The registered agent id'),
346
- actionIndex: z.number().int().nonnegative().describe('The action index'),
347
- payload: signedMessageSchema.describe('The signed action payload'),
348
- signature: signatureSchema.describe('0x-prefixed 65-byte signature'),
349
- expectedActionEnvelopeHash: hashSchema.optional().describe('Optional expected action-envelope hash'),
350
- },
351
- },
352
- async ({ agentId, actionIndex, payload, signature, expectedActionEnvelopeHash }, extra) => {
353
- const client = governanceClient(extra);
354
- if (!client) return fail(NEEDS_KEY);
355
- try {
356
- return hostedResult(await client.verifyAction({ agentId, actionIndex, payload, signature, expectedActionEnvelopeHash }), 'verification failed');
357
- } catch (err) {
358
- return fail(err instanceof Error ? err.message : 'verification failed', errorBody(err));
359
- }
360
- },
361
- );
362
-
363
- server.registerTool(
364
- 'ae_authorize_action',
365
- {
366
- title: 'Authorize action (hosted decision)',
367
- description:
368
- 'One-call AgentEnvelope decision for a proposed agent action. It normalizes hosted verification into allowed/denied and checks optional operation/resource labels against the verified record envelope when present.',
369
- annotations: readOnlyHosted,
370
- inputSchema: {
371
- agentId: agentIdSchema.describe('The registered agent id'),
372
- operation: operationSchema.optional().describe('The proposed operation, for decision context and audit readability'),
373
- resource: resourceSchema.optional().describe('The proposed resource, for decision context and audit readability'),
374
- actionIndex: z.number().int().nonnegative().describe('The action index'),
375
- payload: signedMessageSchema.describe('The exact signed action payload'),
376
- signature: signatureSchema.describe('0x-prefixed 65-byte signature'),
377
- expectedActionEnvelopeHash: hashSchema.optional().describe('Optional expected action-envelope hash'),
378
- },
379
- },
380
- async (input, extra) => {
381
- const client = governanceClient(extra);
382
- if (!client) return fail(NEEDS_KEY);
383
- try {
384
- const report = unwrapProxyResponse(await client.verifyAction(input));
385
- return ok(decisionFromReport(report, input));
386
- } catch (err) {
387
- const body = errorBody(err);
388
- return ok({
389
- type: 'agentenvelope.authorizationDecision',
390
- version: 1,
391
- allowed: false,
392
- decision: 'denied',
393
- reason: body?.code || body?.error || (err instanceof Error ? err.message : 'verification_failed'),
394
- message: body?.message || (err instanceof Error ? err.message : 'AgentEnvelope denied this action.'),
395
- agentId: input.agentId,
396
- ...(input.operation ? { operation: input.operation } : {}),
397
- ...(input.resource ? { resource: input.resource } : {}),
398
- actionIndex: input.actionIndex,
399
- checkedAt: new Date().toISOString(),
400
- ...(body ? { report: body } : {}),
401
- });
402
- }
403
- },
404
- );
405
-
406
- server.registerTool(
407
- 'ae_get_delegate',
408
- {
409
- title: 'Get mint delegate',
410
- description: 'Fetch one active hosted mint delegate by delegate id. Returns an error if the delegate is revoked. Requires a portal-issued API key.',
411
- annotations: readOnlyHosted,
412
- inputSchema: {
413
- delegateId: delegateIdSchema.describe('The hosted delegate id'),
414
- },
415
- },
416
- async ({ delegateId }, extra) => {
417
- try {
418
- return hostedResult(await hostedJson('/sovereign/delegates/' + encodeURIComponent(delegateId), { method: 'GET' }, extra), 'delegate lookup failed');
419
- } catch (err) {
420
- return fail(err instanceof Error ? err.message : 'delegate lookup failed', errorBody(err));
421
- }
422
- },
423
- );
424
-
425
- server.registerTool(
426
- 'ae_check_legitimacy',
427
- {
428
- title: 'Check legitimacy state',
429
- description: 'Fetch and normalize a hosted legitimacy state. Returns allowed when the state is legitimate and not expired. Requires a portal-issued API key.',
430
- annotations: readOnlyHosted,
431
- inputSchema: {
432
- legitimacyId: legitimacyIdSchema.describe('The hosted legitimacy id'),
433
- },
434
- },
435
- async ({ legitimacyId }, extra) => {
436
- const client = governanceClient(extra);
437
- if (!client) return fail(NEEDS_KEY);
438
- try {
439
- const result = await client.getLegitimacyState(legitimacyId);
440
- const state = result?.legitimacy ?? result?.state ?? result;
441
- const expiresAt = state?.expiresAt;
442
- const expired = Boolean(expiresAt && Date.parse(expiresAt) <= Date.now());
443
- const allowed = state?.status === 'legitimate' && !expired;
444
- return ok({
445
- type: 'agentenvelope.legitimacyDecision',
446
- version: 1,
447
- legitimacyId,
448
- allowed,
449
- decision: allowed ? 'allowed' : 'denied',
450
- status: state?.status ?? 'unknown',
451
- ...(expired ? { reason: 'legitimacy policy expired' } : {}),
452
- checkedAt: new Date().toISOString(),
453
- state,
454
- });
455
- } catch (err) {
456
- return fail(err instanceof Error ? err.message : 'legitimacy check failed', errorBody(err));
457
- }
458
- },
459
- );
460
-
461
- if (MINT_ENABLED) {
462
- server.registerTool(
463
- 'ae_mint',
464
- {
465
- title: 'Verify mint request (hosted receipt)',
466
- description:
467
- 'Verify a MintDelegate and signed MintRequest through hosted governance. Returns a mint receipt; it does not return private capability material. Requires a portal-issued API key. This is a governed action.',
468
- annotations: governedHosted,
469
- inputSchema: {
470
- delegate: mintObjectSchema.describe('The signed MintDelegate'),
471
- request: mintObjectSchema.describe('The bot-signed MintRequest'),
472
- },
473
- },
474
- async ({ delegate, request }, extra) => {
475
- const client = governanceClient(extra);
476
- if (!client) return fail(NEEDS_KEY);
477
- try {
478
- return hostedResult(await client.mint({ delegate, request }), 'mint failed');
479
- } catch (err) {
480
- return fail(err instanceof Error ? err.message : 'mint failed', errorBody(err));
481
- }
482
- },
483
- );
484
-
485
- server.registerTool(
486
- 'ae_register_delegated_action',
487
- {
488
- title: 'Register delegated action record',
489
- description:
490
- 'Publish a verifier-safe public action record after a successful hosted mint. The hosted service confirms the delegate, signed request, mint nonce, record metadata, plan limits, and legitimacy before registration.',
491
- annotations: governedHosted,
492
- inputSchema: {
493
- record: publicActionRecordSchema.describe('The public action record derived from the minted capability'),
494
- request: mintObjectSchema.describe('The same signed MintRequest accepted by ae_mint'),
495
- delegateId: delegateIdSchema.describe('The hosted delegate used for the mint'),
496
- },
497
- },
498
- async ({ record, request, delegateId }, extra) => {
499
- try {
500
- return hostedResult(await hostedJson('/sovereign/agents/register-delegated', {
501
- method: 'POST',
502
- body: JSON.stringify({ record, request, delegateId }),
503
- }, extra), 'delegated record registration failed');
504
- } catch (err) {
505
- return fail(err instanceof Error ? err.message : 'delegated record registration failed', errorBody(err));
506
- }
507
- },
508
- );
509
- }
510
-
511
- return server;
512
- }
513
-
514
- /** Build the server and connect it over stdio. */
515
- export async function start() {
516
- const server = createServer();
517
- await server.connect(new StdioServerTransport());
518
- console.error('AgentEnvelope MCP server ready on stdio.');
519
- }
520
-
521
- /** Build the server and expose it over Streamable HTTP. */
522
- export async function startHttp({ port = 8787, host = '127.0.0.1', path = '/mcp' } = {}) {
523
- const transports = new Map();
524
- const closeSession = (id, entry) => {
525
- transports.delete(id);
526
- try {
527
- const closeResult = entry?.transport?.close?.();
528
- if (closeResult && typeof closeResult.catch === 'function') closeResult.catch(() => {});
529
- } catch {
530
- // Session eviction should never crash the HTTP listener.
531
- }
532
- };
533
- const sweepIdleSessions = () => {
534
- const cutoff = Date.now() - HTTP_SESSION_IDLE_MS;
535
- for (const [id, entry] of transports) {
536
- if (entry.lastSeen <= cutoff) closeSession(id, entry);
537
- }
538
- };
539
- const sweepTimer = setInterval(sweepIdleSessions, HTTP_SESSION_SWEEP_MS);
540
- sweepTimer.unref?.();
541
-
542
- const httpServer = createHttpServer(async (req, res) => {
543
- try {
544
- sweepIdleSessions();
545
- const url = new URL(req.url || '/', `http://${req.headers.host || `${host}:${port}`}`);
546
-
547
- if (url.pathname === '/health') {
548
- jsonResponse(res, 200, { ok: true, name: 'agent-envelope', transport: 'streamable-http' });
549
- return;
550
- }
551
-
552
- if (url.pathname !== path) {
553
- jsonResponse(res, 404, { error: 'not found' });
554
- return;
555
- }
556
-
557
- const token = extractBearer(req);
558
- if (token) req.auth = { token, clientId: 'bearer', scopes: ['agent-envelope'] };
559
-
560
- const rawSessionId = req.headers['mcp-session-id'];
561
- const sessionId = Array.isArray(rawSessionId) ? rawSessionId[0] : rawSessionId;
562
- const body = req.method === 'POST' ? await readJsonBody(req) : undefined;
563
- const entry = sessionId ? transports.get(sessionId) : undefined;
564
- let transport = entry?.transport;
565
- if (entry) entry.lastSeen = Date.now();
566
-
567
- if (!transport) {
568
- if (req.method !== 'POST' || !isInitializeRequest(body)) {
569
- jsonResponse(res, 400, {
570
- jsonrpc: '2.0',
571
- error: { code: -32000, message: 'Bad Request: initialize before using this MCP session' },
572
- id: null,
573
- });
574
- return;
575
- }
576
-
577
- transport = new StreamableHTTPServerTransport({
578
- sessionIdGenerator: () => randomUUID(),
579
- enableJsonResponse: true,
580
- onsessioninitialized: (id) => transports.set(id, { transport, lastSeen: Date.now() }),
581
- });
582
-
583
- transport.onclose = () => {
584
- if (transport?.sessionId) transports.delete(transport.sessionId);
585
- };
586
-
587
- const mcpServer = createServer();
588
- await mcpServer.connect(transport);
589
- }
590
-
591
- await transport.handleRequest(req, res, body);
592
- } catch (err) {
593
- if (!res.headersSent) {
594
- jsonResponse(res, 500, {
595
- jsonrpc: '2.0',
596
- error: { code: -32603, message: err instanceof Error ? err.message : 'Internal server error' },
597
- id: null,
598
- });
599
- }
600
- }
601
- });
602
-
603
- httpServer.on('close', () => {
604
- clearInterval(sweepTimer);
605
- for (const [id, entry] of transports) closeSession(id, entry);
606
- });
607
-
608
- await new Promise((resolve, reject) => {
609
- httpServer.once('error', reject);
610
- httpServer.listen(port, host, resolve);
611
- });
612
-
613
- console.error(`AgentEnvelope MCP server ready on http://${host}:${port}${path}`);
614
- return httpServer;
615
- }
1
+ /**
2
+ * AgentEnvelope MCP server: the MCP adapter for AgentEnvelope.
3
+ *
4
+ * Any MCP client can call these tools to verify delegated action authority
5
+ * before the runtime executes a real action. Sovereign verification is local
6
+ * and free. Hosted governance uses API-key protected AgentEnvelope routes for
7
+ * records, legitimacy, delegates, verification reports, and mint receipts.
8
+ */
9
+
10
+ import { randomUUID } from 'node:crypto';
11
+ import { createServer as createHttpServer } from 'node:http';
12
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
13
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
14
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
15
+ import { isInitializeRequest } from '@modelcontextprotocol/sdk/types.js';
16
+ import { z } from 'zod';
17
+ import { AgentEnvelopeClient } from 'agent-envelope-sdk/client';
18
+ import {
19
+ isAuthorityLegitimate,
20
+ verifyAction as verifyActionSovereign,
21
+ verifyMintDelegate,
22
+ verifyMintRequest,
23
+ verifyRecord as verifyRecordSovereign,
24
+ } from 'agent-envelope-sdk';
25
+
26
+ const HOSTED_BASE_URL = process.env.AE_API_BASE_URL?.trim() || 'https://jemdjwteae.execute-api.us-east-1.amazonaws.com/v1';
27
+ const SERVER_VERSION = '1.2.2';
28
+ const NEEDS_KEY =
29
+ 'AE_API_KEY is not set. This is a hosted-governance tool; set the portal-issued API key to use it. Sovereign signature and record verification need no key.';
30
+ const TOOLS_MODE = process.env.AE_TOOLS?.trim().toLowerCase() ?? 'all';
31
+ if (!['sovereign', 'readonly', 'read-only', 'all'].includes(TOOLS_MODE)) {
32
+ throw new Error('Invalid AE_TOOLS setting. Use sovereign, readonly, or all.');
33
+ }
34
+ const SOVEREIGN_ONLY = TOOLS_MODE === 'sovereign';
35
+ const MINT_ENABLED = TOOLS_MODE === 'all';
36
+ const MAX_HOSTED_CLIENTS = 100;
37
+ const HTTP_SESSION_IDLE_MS = Number.parseInt(process.env.AE_MCP_SESSION_IDLE_MS || '', 10) || 30 * 60 * 1000;
38
+ const HTTP_SESSION_SWEEP_MS = Math.min(60 * 1000, Math.max(5 * 1000, Math.floor(HTTP_SESSION_IDLE_MS / 2)));
39
+
40
+ const encoder = new TextEncoder();
41
+ const MAX_SIGNED_MESSAGE_BYTES = 64 * 1024;
42
+ const MAX_RECORD_BYTES = 256 * 1024;
43
+ const MAX_MINT_OBJECT_BYTES = 256 * 1024;
44
+ const AGENT_ID = /^[a-zA-Z0-9_:-][a-zA-Z0-9._:-]{0,127}$/;
45
+ const ADDRESS = /^0x[a-fA-F0-9]{40}$/;
46
+ const HASH = /^0x[a-f0-9]{64}$/;
47
+ const SIGNATURE = /^0x[a-fA-F0-9]{130}$/;
48
+ const DELEGATE_ID = /^ae-delegate-[a-zA-Z0-9_-]{8,128}$/;
49
+ const LEGITIMACY_ID = /^ae-legit-[a-zA-Z0-9_-]{8,128}$/;
50
+ const SAFE_TEXT_ID = /^[a-zA-Z0-9_:.*/-]{1,256}$/;
51
+
52
+ const hostedClients = new Map();
53
+
54
+ function getApiKey(extra) {
55
+ const bearer = extra?.authInfo?.token?.trim();
56
+ return bearer || process.env.AE_API_KEY?.trim() || null;
57
+ }
58
+
59
+ function governanceClient(extra) {
60
+ const apiKey = getApiKey(extra);
61
+ if (!apiKey) return null;
62
+ if (hostedClients.has(apiKey)) {
63
+ const client = hostedClients.get(apiKey);
64
+ hostedClients.delete(apiKey);
65
+ hostedClients.set(apiKey, client);
66
+ return client;
67
+ }
68
+ hostedClients.set(apiKey, new AgentEnvelopeClient({ apiKey }));
69
+ if (hostedClients.size > MAX_HOSTED_CLIENTS) {
70
+ const oldestKey = hostedClients.keys().next().value;
71
+ if (oldestKey) hostedClients.delete(oldestKey);
72
+ }
73
+ return hostedClients.get(apiKey);
74
+ }
75
+
76
+ function isPlainObject(value) {
77
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
78
+ }
79
+
80
+ function unwrapProxyResponse(value) {
81
+ if (!isPlainObject(value) || !Number.isInteger(value.statusCode) || !('body' in value)) return value;
82
+ let body = value.body;
83
+ if (typeof body === 'string') {
84
+ try {
85
+ body = JSON.parse(body);
86
+ } catch {
87
+ body = { message: body };
88
+ }
89
+ }
90
+ if (value.statusCode >= 400) {
91
+ const error = new Error(body?.message || body?.error || `AgentEnvelope API error ${value.statusCode}`);
92
+ error.status = value.statusCode;
93
+ error.body = body;
94
+ throw error;
95
+ }
96
+ return body;
97
+ }
98
+
99
+ function jsonByteLength(value) {
100
+ try {
101
+ return encoder.encode(JSON.stringify(value)).length;
102
+ } catch {
103
+ return Infinity;
104
+ }
105
+ }
106
+
107
+ function jsonWithin(maxBytes, label) {
108
+ return z.unknown().refine((value) => jsonByteLength(value) <= maxBytes, {
109
+ message: `${label} exceeds ${maxBytes} JSON bytes`,
110
+ });
111
+ }
112
+
113
+ function summaryText(value) {
114
+ if (isPlainObject(value)) {
115
+ if ('allowed' in value) return value.allowed === true ? 'AgentEnvelope allowed the action.' : 'AgentEnvelope denied the action.';
116
+ if ('valid' in value) return value.valid === true ? 'AgentEnvelope verification passed.' : 'AgentEnvelope verification failed.';
117
+ if ('delegateId' in value) return `AgentEnvelope delegate result: ${value.delegateId}`;
118
+ if ('legitimacyId' in value) return `AgentEnvelope legitimacy result: ${value.legitimacyId}`;
119
+ }
120
+ return JSON.stringify(value, null, 2);
121
+ }
122
+
123
+ function ok(value, text = summaryText(value)) {
124
+ return {
125
+ content: [{ type: 'text', text }],
126
+ ...(isPlainObject(value) ? { structuredContent: value } : {}),
127
+ };
128
+ }
129
+
130
+ function fail(message, details) {
131
+ return {
132
+ content: [{ type: 'text', text: message }],
133
+ ...(details && isPlainObject(details) ? { structuredContent: details } : {}),
134
+ isError: true,
135
+ };
136
+ }
137
+
138
+ function mintRequestFailure(reason, delegate, request) {
139
+ const requiredRef = delegate.legitimacyRef;
140
+ if (requiredRef?.required === true && (reason === 'legitimacyId is invalid' || reason === 'legitimacyId mismatch')) {
141
+ const supplied = request.legitimacyId;
142
+ const missing = typeof supplied !== 'string' || !supplied.trim();
143
+ const message = missing ? 'legitimacyId required by delegate policy' : 'legitimacy scope mismatch';
144
+ return fail(message, {
145
+ error: message,
146
+ code: missing ? 'LEGITIMACY_REF_REQUIRED' : 'LEGITIMACY_SCOPE_MISMATCH',
147
+ message,
148
+ legitimacy: {
149
+ requiredLegitimacyId: requiredRef.legitimacyId,
150
+ ...(missing ? {} : { suppliedLegitimacyId: supplied }),
151
+ },
152
+ });
153
+ }
154
+ const message = `request invalid: ${reason}`;
155
+ return fail(message, { error: message });
156
+ }
157
+
158
+ function hostedResult(value, fallback) {
159
+ const normalized = unwrapProxyResponse(value);
160
+ if (normalized && typeof normalized === 'object' && !Array.isArray(normalized) && 'error' in normalized) {
161
+ return fail(`${fallback}: ${String(normalized.error)}`, normalized);
162
+ }
163
+ return ok(normalized);
164
+ }
165
+
166
+ function errorBody(err) {
167
+ if (err && typeof err === 'object' && 'body' in err && err.body && typeof err.body === 'object') return err.body;
168
+ return null;
169
+ }
170
+
171
+ async function hostedJson(path, init, extra) {
172
+ const apiKey = getApiKey(extra);
173
+ if (!apiKey) throw new Error(NEEDS_KEY);
174
+ const res = await fetch(HOSTED_BASE_URL + path, {
175
+ ...init,
176
+ headers: {
177
+ 'Content-Type': 'application/json',
178
+ 'X-Api-Key': apiKey,
179
+ ...(init?.headers ?? {}),
180
+ },
181
+ });
182
+ const body = await res.json().catch(() => null);
183
+ if (!res.ok) {
184
+ const err = new Error(body?.message || body?.error || `AgentEnvelope API error ${res.status}`);
185
+ err.status = res.status;
186
+ err.body = body;
187
+ throw err;
188
+ }
189
+ return body;
190
+ }
191
+
192
+ function extractBearer(req) {
193
+ const header = req.headers.authorization;
194
+ if (typeof header !== 'string') return null;
195
+ const [scheme, token] = header.split(/\s+/, 2);
196
+ if (scheme?.toLowerCase() !== 'bearer' || !token?.trim()) return null;
197
+ return token.trim();
198
+ }
199
+
200
+ function jsonResponse(res, statusCode, body) {
201
+ res.writeHead(statusCode, { 'content-type': 'application/json' });
202
+ res.end(JSON.stringify(body));
203
+ }
204
+
205
+ async function readJsonBody(req) {
206
+ const chunks = [];
207
+ for await (const chunk of req) chunks.push(chunk);
208
+ if (chunks.length === 0) return undefined;
209
+ const text = Buffer.concat(chunks).toString('utf8');
210
+ if (!text.trim()) return undefined;
211
+ return JSON.parse(text);
212
+ }
213
+
214
+ export function decisionFromReport(report, input) {
215
+ let denialReason;
216
+ if (report?.valid !== true) {
217
+ denialReason = report?.reason || report?.legitimacyReason || 'verification_failed';
218
+ } else if (report.agentId !== input.agentId || report.actionIndex !== input.actionIndex) {
219
+ denialReason = 'action_reference_mismatch';
220
+ } else if (input.expectedActionEnvelopeHash !== undefined && report.actionEnvelopeHash !== input.expectedActionEnvelopeHash) {
221
+ denialReason = 'action_envelope_hash_mismatch';
222
+ } else if (input.operation !== undefined && report.envelope?.operation !== input.operation) {
223
+ denialReason = typeof report.envelope?.operation === 'string' ? 'operation_mismatch' : 'operation_missing';
224
+ } else if (input.resource !== undefined && !Array.isArray(report.envelope?.resources)) {
225
+ denialReason = 'resources_missing';
226
+ } else if (input.resource !== undefined && !resourceAllowed(report.envelope.resources, input.resource)) {
227
+ denialReason = 'resource_mismatch';
228
+ }
229
+ const valid = denialReason === undefined;
230
+ const reason = denialReason ?? 'verified';
231
+ return {
232
+ type: 'agentenvelope.authorizationDecision',
233
+ version: 1,
234
+ allowed: valid,
235
+ decision: valid ? 'allowed' : 'denied',
236
+ reason,
237
+ message: valid ? 'AgentEnvelope verified authority for this action.' : `AgentEnvelope denied this action: ${reason}`,
238
+ agentId: input.agentId,
239
+ ...(input.operation ? { operation: input.operation } : {}),
240
+ ...(input.resource ? { resource: input.resource } : {}),
241
+ ...(input.actionIndex !== undefined ? { actionIndex: input.actionIndex } : {}),
242
+ checkedAt: report?.checkedAt ?? new Date().toISOString(),
243
+ ...(report?.recordId ? { recordId: report.recordId } : {}),
244
+ ...(report?.actionEnvelopeHash ? { actionEnvelopeHash: report.actionEnvelopeHash } : {}),
245
+ ...(report?.expectedActionEnvelopeHash ? { expectedActionEnvelopeHash: report.expectedActionEnvelopeHash } : {}),
246
+ ...(report?.legitimacyRef ? { legitimacyRef: report.legitimacyRef } : {}),
247
+ report,
248
+ };
249
+ }
250
+
251
+ function resourceAllowed(allowedResources, resource) {
252
+ const prefix = resource.split(':')[0];
253
+ return allowedResources.some((allowed) => allowed === resource || allowed === `${prefix}:*` || allowed === '*');
254
+ }
255
+
256
+ const signedMessageSchema = jsonWithin(MAX_SIGNED_MESSAGE_BYTES, 'signed message');
257
+ const mintObjectSchema = jsonWithin(MAX_MINT_OBJECT_BYTES, 'mint object').refine(isPlainObject, 'expected a signed JSON object');
258
+ const agentIdSchema = z.string().regex(AGENT_ID, 'agentId must be 1-128 letters, numbers, underscores, colons, hyphens, or non-leading dots');
259
+ const addressSchema = z.string().regex(ADDRESS, 'address must be a 0x-prefixed 20-byte hex address');
260
+ const hashSchema = z.string().regex(HASH, 'hash must be a 0x-prefixed lowercase 32-byte hex value');
261
+ const signatureSchema = z.string().regex(SIGNATURE, 'signature must be a 0x-prefixed 65-byte recoverable signature');
262
+ const delegateIdSchema = z.string().regex(DELEGATE_ID, 'delegateId must be an ae-delegate id');
263
+ const legitimacyIdSchema = z.string().regex(LEGITIMACY_ID, 'legitimacyId must be an ae-legit id');
264
+ const operationSchema = z.string().regex(SAFE_TEXT_ID, 'operation contains unsupported characters');
265
+ const resourceSchema = z.string().regex(SAFE_TEXT_ID, 'resource contains unsupported characters');
266
+
267
+ const hostedDomainSchema = z.object({
268
+ domainInfo: z.object({
269
+ type: z.literal('agentenvelope.domainInfo'),
270
+ version: z.literal(1),
271
+ namespace: z.string().min(1).max(128),
272
+ domainId: z.string().min(1).max(128),
273
+ kind: z.string().min(1).max(128),
274
+ }).passthrough(),
275
+ canonicalDomainInfo: z.string().min(1).max(4096),
276
+ domainHash: hashSchema,
277
+ domainAddress: addressSchema,
278
+ domainFingerprint: z.string().min(1).max(128),
279
+ createdAt: z.string().min(1).max(64),
280
+ }).passthrough();
281
+
282
+ const publicActionRecordSchema = z.object({
283
+ type: z.literal('agentenvelope.publicActionRecord'),
284
+ version: z.literal(1),
285
+ recordId: z.string().min(1).max(256),
286
+ agentId: agentIdSchema,
287
+ agentAddress: addressSchema,
288
+ status: z.string().min(1).max(32),
289
+ domain: hostedDomainSchema,
290
+ actionEnvelope: z.object({
291
+ actionIndex: z.number().int().nonnegative(),
292
+ }).passthrough(),
293
+ canonicalActionEnvelope: z.string().min(1),
294
+ actionEnvelopeHash: hashSchema,
295
+ expiry: z.string().nullable().optional(),
296
+ }).passthrough();
297
+
298
+ const recordSizeLimit = record => jsonByteLength(record) <= MAX_RECORD_BYTES;
299
+ const recordSizeError = { message: `public action record exceeds ${MAX_RECORD_BYTES} JSON bytes` };
300
+ const hostedRecordSchema = publicActionRecordSchema.refine(recordSizeLimit, recordSizeError);
301
+ const sovereignRecordSchema = publicActionRecordSchema.extend({
302
+ domain: z.union([hostedDomainSchema, z.object({
303
+ domainId: z.string().min(1),
304
+ domainHash: hashSchema,
305
+ domainInfo: z.never().optional(),
306
+ canonicalDomainInfo: z.never().optional(),
307
+ }).passthrough()]),
308
+ }).refine(recordSizeLimit, recordSizeError);
309
+
310
+ const readOnlyLocal = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
311
+ const readOnlyHosted = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true };
312
+ const governedHosted = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true };
313
+
314
+ export function createServer() {
315
+ const server = new McpServer({ name: 'agent-envelope', version: SERVER_VERSION });
316
+
317
+ server.registerTool(
318
+ 'ae_verify_sovereign',
319
+ {
320
+ title: 'Verify signature (sovereign, offline)',
321
+ description:
322
+ 'Signature-only check: verify a signed message against a known agent address. Pure crypto, no vault, no API key, no network. This does not check scope, expiry, usage limits, or hosted record status.',
323
+ annotations: readOnlyLocal,
324
+ inputSchema: {
325
+ message: signedMessageSchema.describe('The exact signed message value'),
326
+ signature: signatureSchema.describe('0x-prefixed 65-byte signature'),
327
+ expectedAddress: addressSchema.describe("The agent's 0x address to check against"),
328
+ },
329
+ },
330
+ async ({ message, signature, expectedAddress }) => {
331
+ try {
332
+ return ok(verifyActionSovereign({ message, signature, expectedAddress }));
333
+ } catch (err) {
334
+ return fail(err instanceof Error ? err.message : 'verification failed');
335
+ }
336
+ },
337
+ );
338
+
339
+ server.registerTool(
340
+ 'ae_verify_sovereign_record',
341
+ {
342
+ title: 'Verify public action record (sovereign, offline)',
343
+ description:
344
+ 'Verify a signed action against a public action record. Checks record status, domain and envelope integrity, action index, signature/address match, optional expected envelope hash, and time decay. No API key or network call.',
345
+ annotations: readOnlyLocal,
346
+ inputSchema: {
347
+ record: sovereignRecordSchema.describe('The public action record received from AgentEnvelope or another trusted store'),
348
+ actionIndex: z.number().int().nonnegative().describe('The action index being invoked'),
349
+ payload: signedMessageSchema.describe('The exact signed action payload'),
350
+ signature: signatureSchema.describe('0x-prefixed 65-byte signature'),
351
+ expectedActionEnvelopeHash: hashSchema.optional().describe('Optional expected action-envelope hash'),
352
+ },
353
+ },
354
+ async ({ record, actionIndex, payload, signature, expectedActionEnvelopeHash }) => {
355
+ try {
356
+ return ok(verifyRecordSovereign(record, { payload, signature, actionIndex, expectedActionEnvelopeHash }));
357
+ } catch (err) {
358
+ return fail(err instanceof Error ? err.message : 'record verification failed');
359
+ }
360
+ },
361
+ );
362
+
363
+ if (!SOVEREIGN_ONLY) {
364
+ server.registerTool(
365
+ 'ae_get_agent',
366
+ {
367
+ title: 'Look up registered agent',
368
+ description: 'Fetch the hosted public record for an agent id. Requires a portal-issued API key.',
369
+ annotations: readOnlyHosted,
370
+ inputSchema: {
371
+ agentId: agentIdSchema.describe('The registered agent id'),
372
+ },
373
+ },
374
+ async ({ agentId }, extra) => {
375
+ const client = governanceClient(extra);
376
+ if (!client) return fail(NEEDS_KEY);
377
+ try {
378
+ return hostedResult(await client.getAgent(agentId), 'lookup failed');
379
+ } catch (err) {
380
+ return fail(err instanceof Error ? err.message : 'lookup failed', errorBody(err));
381
+ }
382
+ },
383
+ );
384
+
385
+ server.registerTool(
386
+ 'ae_verify_action',
387
+ {
388
+ title: 'Verify action (hosted record)',
389
+ description: 'Verify a signed action against the hosted public record for an agent. Requires a portal-issued API key.',
390
+ annotations: readOnlyHosted,
391
+ inputSchema: {
392
+ agentId: agentIdSchema.describe('The registered agent id'),
393
+ actionIndex: z.number().int().nonnegative().describe('The action index'),
394
+ payload: signedMessageSchema.describe('The signed action payload'),
395
+ signature: signatureSchema.describe('0x-prefixed 65-byte signature'),
396
+ expectedActionEnvelopeHash: hashSchema.optional().describe('Optional expected action-envelope hash'),
397
+ },
398
+ },
399
+ async ({ agentId, actionIndex, payload, signature, expectedActionEnvelopeHash }, extra) => {
400
+ const client = governanceClient(extra);
401
+ if (!client) return fail(NEEDS_KEY);
402
+ try {
403
+ return hostedResult(await client.verifyAction({ agentId, actionIndex, payload, signature, expectedActionEnvelopeHash }), 'verification failed');
404
+ } catch (err) {
405
+ return fail(err instanceof Error ? err.message : 'verification failed', errorBody(err));
406
+ }
407
+ },
408
+ );
409
+
410
+ server.registerTool(
411
+ 'ae_authorize_action',
412
+ {
413
+ title: 'Authorize action (hosted decision)',
414
+ description:
415
+ 'One-call AgentEnvelope decision for a proposed agent action. It normalizes hosted verification into allowed/denied and checks optional operation/resource labels against the verified record envelope when present.',
416
+ annotations: readOnlyHosted,
417
+ inputSchema: {
418
+ agentId: agentIdSchema.describe('The registered agent id'),
419
+ operation: operationSchema.optional().describe('The proposed operation, for decision context and audit readability'),
420
+ resource: resourceSchema.optional().describe('The proposed resource, for decision context and audit readability'),
421
+ actionIndex: z.number().int().nonnegative().describe('The action index'),
422
+ payload: signedMessageSchema.describe('The exact signed action payload'),
423
+ signature: signatureSchema.describe('0x-prefixed 65-byte signature'),
424
+ expectedActionEnvelopeHash: hashSchema.optional().describe('Optional expected action-envelope hash'),
425
+ },
426
+ },
427
+ async (input, extra) => {
428
+ const client = governanceClient(extra);
429
+ if (!client) return fail(NEEDS_KEY);
430
+ try {
431
+ const report = unwrapProxyResponse(await client.verifyAction(input));
432
+ return ok(decisionFromReport(report, input));
433
+ } catch (err) {
434
+ const body = errorBody(err);
435
+ return ok({
436
+ type: 'agentenvelope.authorizationDecision',
437
+ version: 1,
438
+ allowed: false,
439
+ decision: 'denied',
440
+ reason: body?.code || body?.error || (err instanceof Error ? err.message : 'verification_failed'),
441
+ message: body?.message || (err instanceof Error ? err.message : 'AgentEnvelope denied this action.'),
442
+ agentId: input.agentId,
443
+ ...(input.operation ? { operation: input.operation } : {}),
444
+ ...(input.resource ? { resource: input.resource } : {}),
445
+ actionIndex: input.actionIndex,
446
+ checkedAt: new Date().toISOString(),
447
+ ...(body ? { report: body } : {}),
448
+ });
449
+ }
450
+ },
451
+ );
452
+
453
+ server.registerTool(
454
+ 'ae_get_delegate',
455
+ {
456
+ title: 'Get mint delegate',
457
+ description: 'Fetch one active hosted mint delegate by delegate id. Returns an error if the delegate is revoked. Requires a portal-issued API key.',
458
+ annotations: readOnlyHosted,
459
+ inputSchema: {
460
+ delegateId: delegateIdSchema.describe('The hosted delegate id'),
461
+ },
462
+ },
463
+ async ({ delegateId }, extra) => {
464
+ try {
465
+ return hostedResult(await hostedJson('/sovereign/delegates/' + encodeURIComponent(delegateId), { method: 'GET' }, extra), 'delegate lookup failed');
466
+ } catch (err) {
467
+ return fail(err instanceof Error ? err.message : 'delegate lookup failed', errorBody(err));
468
+ }
469
+ },
470
+ );
471
+
472
+ server.registerTool(
473
+ 'ae_check_legitimacy',
474
+ {
475
+ title: 'Check legitimacy state',
476
+ description: 'Fetch and normalize a hosted legitimacy state. Returns allowed when the state is legitimate and not expired. Requires a portal-issued API key.',
477
+ annotations: readOnlyHosted,
478
+ inputSchema: {
479
+ legitimacyId: legitimacyIdSchema.describe('The hosted legitimacy id'),
480
+ },
481
+ },
482
+ async ({ legitimacyId }, extra) => {
483
+ const client = governanceClient(extra);
484
+ if (!client) return fail(NEEDS_KEY);
485
+ try {
486
+ const result = await client.getLegitimacyState(legitimacyId);
487
+ const state = result?.legitimacy ?? result?.state ?? result;
488
+ const check = isAuthorityLegitimate(state);
489
+ const allowed = check.valid && state.legitimacyId === legitimacyId;
490
+ return ok({
491
+ type: 'agentenvelope.legitimacyDecision',
492
+ version: 1,
493
+ legitimacyId,
494
+ allowed,
495
+ decision: allowed ? 'allowed' : 'denied',
496
+ status: state?.status ?? 'unknown',
497
+ ...(!allowed ? { reason: check.reason ?? 'legitimacyId mismatch' } : {}),
498
+ checkedAt: new Date().toISOString(),
499
+ state,
500
+ });
501
+ } catch (err) {
502
+ return fail(err instanceof Error ? err.message : 'legitimacy check failed', errorBody(err));
503
+ }
504
+ },
505
+ );
506
+
507
+ if (MINT_ENABLED) {
508
+ server.registerTool(
509
+ 'ae_mint',
510
+ {
511
+ title: 'Verify mint request (hosted receipt)',
512
+ description:
513
+ 'Verify a MintDelegate and signed MintRequest through hosted governance. Returns a mint receipt; it does not return private capability material. Requires a portal-issued API key. This is a governed action.',
514
+ annotations: governedHosted,
515
+ inputSchema: {
516
+ delegate: mintObjectSchema.describe('The signed MintDelegate'),
517
+ request: mintObjectSchema.describe('The bot-signed MintRequest'),
518
+ },
519
+ },
520
+ async ({ delegate, request }, extra) => {
521
+ const client = governanceClient(extra);
522
+ if (!client) return fail(NEEDS_KEY);
523
+ try {
524
+ const permit = verifyMintDelegate(delegate, delegate.issuerAddress);
525
+ if (!permit.valid) return fail(`delegate invalid: ${permit.reason}`);
526
+ const mint = verifyMintRequest(request, delegate);
527
+ if (!mint.valid) return mintRequestFailure(mint.reason, delegate, request);
528
+ return hostedResult(await client.mint({ delegate, request }), 'mint failed');
529
+ } catch (err) {
530
+ return fail(err instanceof Error ? err.message : 'mint failed', errorBody(err));
531
+ }
532
+ },
533
+ );
534
+
535
+ server.registerTool(
536
+ 'ae_register_delegated_action',
537
+ {
538
+ title: 'Register delegated action record',
539
+ description:
540
+ 'Publish a verifier-safe public action record after a successful hosted mint. The hosted service confirms the delegate, signed request, mint nonce, record metadata, plan limits, and legitimacy before registration.',
541
+ annotations: governedHosted,
542
+ inputSchema: {
543
+ record: hostedRecordSchema.describe('The public action record derived from the minted capability'),
544
+ request: mintObjectSchema.describe('The same signed MintRequest accepted by ae_mint'),
545
+ delegateId: delegateIdSchema.describe('The hosted delegate used for the mint'),
546
+ },
547
+ },
548
+ async ({ record, request, delegateId }, extra) => {
549
+ try {
550
+ if (request.delegateId !== delegateId) return fail('request delegateId mismatch');
551
+ return hostedResult(await hostedJson('/sovereign/agents/register-delegated', {
552
+ method: 'POST',
553
+ body: JSON.stringify({ record, request, delegateId }),
554
+ }, extra), 'delegated record registration failed');
555
+ } catch (err) {
556
+ return fail(err instanceof Error ? err.message : 'delegated record registration failed', errorBody(err));
557
+ }
558
+ },
559
+ );
560
+ }
561
+ }
562
+
563
+ return server;
564
+ }
565
+
566
+ /** Build the server and connect it over stdio. */
567
+ export async function start() {
568
+ const server = createServer();
569
+ await server.connect(new StdioServerTransport());
570
+ console.error('AgentEnvelope MCP server ready on stdio.');
571
+ }
572
+
573
+ /** Build the server and expose it over Streamable HTTP. */
574
+ export async function startHttp({ port = 8787, host = '127.0.0.1', path = '/mcp' } = {}) {
575
+ const transports = new Map();
576
+ const closeSession = (id, entry) => {
577
+ transports.delete(id);
578
+ try {
579
+ const closeResult = entry?.transport?.close?.();
580
+ if (closeResult && typeof closeResult.catch === 'function') closeResult.catch(() => {});
581
+ } catch {
582
+ // Session eviction should never crash the HTTP listener.
583
+ }
584
+ };
585
+ const sweepIdleSessions = () => {
586
+ const cutoff = Date.now() - HTTP_SESSION_IDLE_MS;
587
+ for (const [id, entry] of transports) {
588
+ if (entry.lastSeen <= cutoff) closeSession(id, entry);
589
+ }
590
+ };
591
+ const sweepTimer = setInterval(sweepIdleSessions, HTTP_SESSION_SWEEP_MS);
592
+ sweepTimer.unref?.();
593
+
594
+ const httpServer = createHttpServer(async (req, res) => {
595
+ try {
596
+ sweepIdleSessions();
597
+ const url = new URL(req.url || '/', `http://${req.headers.host || `${host}:${port}`}`);
598
+
599
+ if (url.pathname === '/health') {
600
+ jsonResponse(res, 200, { ok: true, name: 'agent-envelope', transport: 'streamable-http' });
601
+ return;
602
+ }
603
+
604
+ if (url.pathname !== path) {
605
+ jsonResponse(res, 404, { error: 'not found' });
606
+ return;
607
+ }
608
+
609
+ const token = extractBearer(req);
610
+ if (token) req.auth = { token, clientId: 'bearer', scopes: ['agent-envelope'] };
611
+
612
+ const rawSessionId = req.headers['mcp-session-id'];
613
+ const sessionId = Array.isArray(rawSessionId) ? rawSessionId[0] : rawSessionId;
614
+ const body = req.method === 'POST' ? await readJsonBody(req) : undefined;
615
+ const entry = sessionId ? transports.get(sessionId) : undefined;
616
+ let transport = entry?.transport;
617
+ if (entry) entry.lastSeen = Date.now();
618
+
619
+ if (!transport) {
620
+ if (req.method !== 'POST' || !isInitializeRequest(body)) {
621
+ jsonResponse(res, 400, {
622
+ jsonrpc: '2.0',
623
+ error: { code: -32000, message: 'Bad Request: initialize before using this MCP session' },
624
+ id: null,
625
+ });
626
+ return;
627
+ }
628
+
629
+ transport = new StreamableHTTPServerTransport({
630
+ sessionIdGenerator: () => randomUUID(),
631
+ enableJsonResponse: true,
632
+ onsessioninitialized: (id) => transports.set(id, { transport, lastSeen: Date.now() }),
633
+ });
634
+
635
+ transport.onclose = () => {
636
+ if (transport?.sessionId) transports.delete(transport.sessionId);
637
+ };
638
+
639
+ const mcpServer = createServer();
640
+ await mcpServer.connect(transport);
641
+ }
642
+
643
+ await transport.handleRequest(req, res, body);
644
+ } catch (err) {
645
+ if (!res.headersSent) {
646
+ jsonResponse(res, 500, {
647
+ jsonrpc: '2.0',
648
+ error: { code: -32603, message: err instanceof Error ? err.message : 'Internal server error' },
649
+ id: null,
650
+ });
651
+ }
652
+ }
653
+ });
654
+
655
+ httpServer.on('close', () => {
656
+ clearInterval(sweepTimer);
657
+ for (const [id, entry] of transports) closeSession(id, entry);
658
+ });
659
+
660
+ await new Promise((resolve, reject) => {
661
+ httpServer.once('error', reject);
662
+ httpServer.listen(port, host, resolve);
663
+ });
664
+
665
+ console.error(`AgentEnvelope MCP server ready on http://${host}:${port}${path}`);
666
+ return httpServer;
667
+ }