@agntor/mcp 0.1.0

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/dist/server.js ADDED
@@ -0,0 +1,754 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/server.ts
4
+ import "dotenv/config";
5
+ import express from "express";
6
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { TicketIssuer as TicketIssuer2 } from "@agntor/sdk";
9
+
10
+ // src/index.ts
11
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
12
+ import { z as z3 } from "zod";
13
+ import { guard, redact, guardTool, Agntor } from "@agntor/sdk";
14
+
15
+ // src/schemas.ts
16
+ import { z } from "zod";
17
+ var AgentCardSchema = z.object({
18
+ // Identity
19
+ id: z.string().describe("Unique Agent ID (DID or UUID)"),
20
+ name: z.string().describe("Display name of the agent"),
21
+ organization: z.string().describe("Legal entity owning the agent"),
22
+ version: z.string().describe("Semantic version of the agent code"),
23
+ // Certification
24
+ audit_level: z.enum(["Bronze", "Silver", "Gold", "Platinum"]).describe("Agntor Certification Level"),
25
+ trust_score: z.number().min(0).max(100).describe("Real-time trust score (0-100)"),
26
+ certified_at: z.string().datetime().describe("ISO timestamp of last full audit"),
27
+ expires_at: z.string().datetime().describe("ISO timestamp when certification expires"),
28
+ // Capabilities & Constraints
29
+ capabilities: z.array(z.string()).describe("List of allowed actions (e.g., 'trade', 'email')"),
30
+ constraints: z.object({
31
+ max_transaction_value: z.number().describe("Hard cap on single transaction value (USD)"),
32
+ allowed_domains: z.array(z.string()).describe("Whitelisted external domains"),
33
+ requires_human_approval: z.boolean().describe("If true, high-risk actions need human sign-off"),
34
+ requires_x402_payment: z.boolean().describe("If true, x402 proof-of-payment required")
35
+ }),
36
+ // Verification
37
+ issuer: z.string().describe("Authority that issued this card (e.g., 'agntor.com')"),
38
+ signature: z.string().describe("Cryptographic signature of this card")
39
+ });
40
+ var AgentPulseSchema = z.object({
41
+ agent_id: z.string(),
42
+ status: z.enum(["healthy", "degraded", "critical", "offline"]),
43
+ metrics: z.object({
44
+ uptime_24h: z.number().min(0).max(100),
45
+ error_rate_1h: z.number().min(0).max(1),
46
+ avg_latency_ms: z.number(),
47
+ spend_velocity_1h: z.number().describe("USD spent in last hour")
48
+ }),
49
+ last_heartbeat: z.string().datetime()
50
+ });
51
+ var AgentRegistrationSchema = z.object({
52
+ type: z.string().describe("EIP-8004 registration type URI"),
53
+ name: z.string(),
54
+ description: z.string(),
55
+ image: z.string().optional(),
56
+ endpoints: z.array(
57
+ z.object({
58
+ name: z.string(),
59
+ endpoint: z.string(),
60
+ version: z.string().optional(),
61
+ capabilities: z.array(z.string()).optional(),
62
+ skills: z.array(z.string()).optional(),
63
+ domains: z.array(z.string()).optional()
64
+ })
65
+ ),
66
+ x402Support: z.boolean(),
67
+ active: z.boolean(),
68
+ registrations: z.array(
69
+ z.object({
70
+ agentId: z.number(),
71
+ agentRegistry: z.string()
72
+ })
73
+ ),
74
+ supportedTrust: z.array(z.string()).optional()
75
+ });
76
+
77
+ // src/types.ts
78
+ import { z as z2 } from "zod";
79
+ var VerifyAgentRequest = z2.object({
80
+ agentId: z2.string().describe("The agent ID to verify"),
81
+ includeHealth: z2.boolean().optional().describe("Include behavioral health metrics")
82
+ });
83
+ var IssueTicketRequest = z2.object({
84
+ agentId: z2.string().describe("Agent ID to issue ticket for"),
85
+ validitySeconds: z2.number().optional().describe("Ticket validity in seconds (default: 300)")
86
+ });
87
+ var QueryAgentsRequest = z2.object({
88
+ minTrustScore: z2.number().optional().describe("Minimum trust score (0-100)"),
89
+ auditLevel: z2.enum(["Bronze", "Silver", "Gold", "Platinum"]).optional(),
90
+ capabilities: z2.array(z2.string()).optional().describe("Required capabilities"),
91
+ limit: z2.number().optional().describe("Maximum results (default: 10)")
92
+ });
93
+ var KillSwitchRequest = z2.object({
94
+ agentId: z2.string().describe("Agent ID to disable"),
95
+ reason: z2.string().describe("Reason for kill switch activation"),
96
+ revokeTickets: z2.boolean().optional().describe("Revoke all existing tickets (default: true)")
97
+ });
98
+
99
+ // src/index.ts
100
+ function getAgntorClient() {
101
+ const apiKey = process.env.AGNTOR_API_KEY;
102
+ if (!apiKey) {
103
+ console.warn("[MCP] Warning: AGNTOR_API_KEY not set. SDK calls to the backend will fail.");
104
+ }
105
+ const apiUrl = process.env.AGNTOR_API_URL || "https://app.agntor.com";
106
+ return new Agntor({
107
+ apiKey: apiKey || "not-configured",
108
+ agentId: process.env.AGNTOR_AGENT_ID || "agent://mcp-server",
109
+ chain: process.env.AGNTOR_CHAIN || "base",
110
+ baseUrl: apiUrl
111
+ });
112
+ }
113
+ async function getAgentRecord(agentId) {
114
+ const agntor = getAgntorClient();
115
+ try {
116
+ const raw = await agntor.getAgent(agentId);
117
+ const identity = raw.identity ?? {};
118
+ const profile = raw.profile ?? {};
119
+ const trust = raw.trust ?? {};
120
+ const status = raw.status ?? {};
121
+ const meta = profile.metadata ?? {};
122
+ const record = {
123
+ agentId: raw.id ?? agentId,
124
+ auditLevel: trust.level ?? "Bronze",
125
+ trustScore: trust.score ?? 0,
126
+ organization: profile.organization ?? "Unknown",
127
+ metadata: {
128
+ name: identity.handle ?? meta.name ?? "Unknown Agent",
129
+ description: meta.description ?? "",
130
+ capabilities: meta.capabilities ?? [],
131
+ verified_domain: meta.verified_domain
132
+ },
133
+ certification: {
134
+ certified_at: trust.certified ? Date.now() : 0,
135
+ expires_at: trust.certified ? Date.now() + 365 * 24 * 60 * 60 * 1e3 : 0,
136
+ certifier: "agntor.com",
137
+ mva_level: trust.level === "Platinum" ? 5 : trust.level === "Gold" ? 4 : trust.level === "Silver" ? 3 : 1
138
+ },
139
+ health: {
140
+ uptime_percentage: meta.uptime_percentage ?? 0,
141
+ avg_latency_ms: meta.avg_latency_ms ?? 0,
142
+ error_rate: meta.error_rate ?? 0,
143
+ total_transactions: meta.total_transactions ?? 0,
144
+ last_active: meta.last_active ?? Date.now()
145
+ },
146
+ killSwitchActive: !(status.active ?? true),
147
+ constraints: {
148
+ max_op_value: meta.max_op_value ?? 1e4,
149
+ allowed_mcp_servers: meta.allowed_mcp_servers ?? [],
150
+ max_ops_per_hour: meta.max_ops_per_hour,
151
+ requires_x402_payment: meta.requires_x402_payment
152
+ }
153
+ };
154
+ return record;
155
+ } catch (e) {
156
+ console.error(`[MCP] getAgentRecord failed for ${agentId}:`, e.message);
157
+ return null;
158
+ }
159
+ }
160
+ function createAgntorMcpServer(issuer2) {
161
+ const server = new McpServer({
162
+ name: "agntor-audit-server",
163
+ version: "0.1.0"
164
+ });
165
+ server.registerTool(
166
+ "get_agent_card",
167
+ {
168
+ title: "Get Agent Card",
169
+ description: "Retrieve the verifiable AgentCard (Passport) for an agent",
170
+ inputSchema: {
171
+ agentId: z3.string().describe("The agent ID to retrieve")
172
+ },
173
+ outputSchema: AgentCardSchema
174
+ },
175
+ async ({ agentId }) => {
176
+ const agent = await getAgentRecord(agentId);
177
+ if (!agent) {
178
+ throw new Error(`Agent ${agentId} not found`);
179
+ }
180
+ const card = {
181
+ id: agent.agentId,
182
+ name: agent.metadata.name,
183
+ organization: agent.organization,
184
+ version: "1.0.0",
185
+ // Placeholder
186
+ audit_level: agent.auditLevel,
187
+ trust_score: agent.trustScore,
188
+ certified_at: new Date(agent.certification.certified_at).toISOString(),
189
+ expires_at: new Date(agent.certification.expires_at).toISOString(),
190
+ capabilities: agent.metadata.capabilities,
191
+ constraints: {
192
+ max_transaction_value: agent.constraints.max_op_value,
193
+ allowed_domains: [],
194
+ // Placeholder
195
+ requires_human_approval: false,
196
+ requires_x402_payment: Boolean(agent.constraints?.requires_x402_payment ?? true)
197
+ },
198
+ issuer: "agntor.com",
199
+ signature: `agntor:${agent.agentId}:${Date.now()}`
200
+ // Real signatures require on-chain integration
201
+ };
202
+ return {
203
+ content: [{ type: "text", text: JSON.stringify(card) }],
204
+ structuredContent: card
205
+ };
206
+ }
207
+ );
208
+ server.registerTool(
209
+ "get_agent_registration",
210
+ {
211
+ title: "Get Agent Registration",
212
+ description: "Retrieve the EIP-8004 agent registration file",
213
+ inputSchema: {
214
+ agentId: z3.string().describe("The agent ID to retrieve")
215
+ },
216
+ outputSchema: AgentRegistrationSchema
217
+ },
218
+ async ({ agentId }) => {
219
+ const agent = await getAgentRecord(agentId);
220
+ if (!agent) {
221
+ throw new Error(`Agent ${agentId} not found`);
222
+ }
223
+ const registry = agent.metadata?.agentRegistry ?? "eip155:1:0x0000000000000000000000000000000000000000";
224
+ const registrationId = Number.parseInt(agent.agentId, 10);
225
+ const endpoints = agent.metadata?.endpoints ?? [
226
+ {
227
+ name: "MCP",
228
+ endpoint: "https://agntor.com/mcp",
229
+ version: "2025-06-18",
230
+ capabilities: agent.metadata.capabilities ?? []
231
+ }
232
+ ];
233
+ const registration = {
234
+ type: "https://eips.ethereum.org/EIPS/eip-8004#registration-v1",
235
+ name: agent.metadata.name,
236
+ description: agent.metadata.description || "Agntor-registered agent",
237
+ image: agent.metadata?.image,
238
+ endpoints,
239
+ x402Support: true,
240
+ active: !agent.killSwitchActive,
241
+ registrations: [
242
+ {
243
+ agentId: Number.isNaN(registrationId) ? 0 : registrationId,
244
+ agentRegistry: registry
245
+ }
246
+ ],
247
+ supportedTrust: ["reputation", "validation", "crypto-economic"]
248
+ };
249
+ return {
250
+ content: [{ type: "text", text: JSON.stringify(registration) }],
251
+ structuredContent: registration
252
+ };
253
+ }
254
+ );
255
+ server.registerTool(
256
+ "check_agent_pulse",
257
+ {
258
+ title: "Check Agent Pulse",
259
+ description: "Get real-time health and behavioral metrics",
260
+ inputSchema: {
261
+ agentId: z3.string()
262
+ },
263
+ outputSchema: AgentPulseSchema
264
+ },
265
+ async ({ agentId }) => {
266
+ const agent = await getAgentRecord(agentId);
267
+ if (!agent)
268
+ throw new Error(`Agent ${agentId} not found`);
269
+ const pulse = {
270
+ agent_id: agent.agentId,
271
+ status: agent.killSwitchActive ? "critical" : "healthy",
272
+ metrics: {
273
+ uptime_24h: agent.health.uptime_percentage,
274
+ error_rate_1h: agent.health.error_rate,
275
+ avg_latency_ms: agent.health.avg_latency_ms,
276
+ spend_velocity_1h: 0
277
+ // Placeholder
278
+ },
279
+ last_heartbeat: new Date(agent.health.last_active).toISOString()
280
+ };
281
+ return {
282
+ content: [{ type: "text", text: JSON.stringify(pulse) }],
283
+ structuredContent: pulse
284
+ };
285
+ }
286
+ );
287
+ server.registerTool(
288
+ "is_agent_certified",
289
+ {
290
+ title: "Check Agent Certification",
291
+ description: "Verify if an agent has valid Agntor certification",
292
+ inputSchema: {
293
+ agentId: z3.string().describe("The agent ID to check")
294
+ },
295
+ outputSchema: {
296
+ certified: z3.boolean(),
297
+ agentId: z3.string(),
298
+ auditLevel: z3.string().optional(),
299
+ expiresAt: z3.number().optional(),
300
+ killSwitchActive: z3.boolean().optional()
301
+ }
302
+ },
303
+ async ({ agentId }) => {
304
+ const agent = await getAgentRecord(agentId);
305
+ if (!agent) {
306
+ const output2 = { certified: false, agentId };
307
+ return {
308
+ content: [{ type: "text", text: JSON.stringify(output2) }],
309
+ structuredContent: output2
310
+ };
311
+ }
312
+ const now = Date.now();
313
+ const isCertified = agent.certification.expires_at > now && !agent.killSwitchActive;
314
+ const output = {
315
+ certified: isCertified,
316
+ agentId: agent.agentId,
317
+ auditLevel: agent.auditLevel,
318
+ expiresAt: agent.certification.expires_at,
319
+ killSwitchActive: agent.killSwitchActive
320
+ };
321
+ return {
322
+ content: [{ type: "text", text: JSON.stringify(output) }],
323
+ structuredContent: output
324
+ };
325
+ }
326
+ );
327
+ server.registerTool(
328
+ "guard_input",
329
+ {
330
+ title: "Guard Input",
331
+ description: "Scan incoming prompts for unsafe or malicious instructions",
332
+ inputSchema: {
333
+ input: z3.string(),
334
+ context: z3.any().optional(),
335
+ policy: z3.any().optional()
336
+ },
337
+ outputSchema: {
338
+ classification: z3.enum(["pass", "block"]),
339
+ violation_types: z3.array(z3.string()),
340
+ cwe_codes: z3.array(z3.string()),
341
+ usage: z3.object({
342
+ promptTokens: z3.number(),
343
+ completionTokens: z3.number(),
344
+ totalTokens: z3.number()
345
+ }).optional()
346
+ }
347
+ },
348
+ async ({ input, policy }) => {
349
+ const result = await guard(input, policy ?? {});
350
+ return {
351
+ content: [{ type: "text", text: JSON.stringify(result) }],
352
+ structuredContent: result
353
+ };
354
+ }
355
+ );
356
+ server.registerTool(
357
+ "redact_output",
358
+ {
359
+ title: "Redact Output",
360
+ description: "Scan and redact sensitive content from outputs",
361
+ inputSchema: {
362
+ input: z3.string(),
363
+ policy: z3.any().optional()
364
+ },
365
+ outputSchema: {
366
+ redacted: z3.string(),
367
+ findings: z3.array(z3.object({
368
+ type: z3.string(),
369
+ span: z3.tuple([z3.number(), z3.number()]),
370
+ value: z3.string().optional()
371
+ }))
372
+ }
373
+ },
374
+ async ({ input, policy }) => {
375
+ const result = redact(input, policy ?? {});
376
+ return {
377
+ content: [{ type: "text", text: JSON.stringify(result) }],
378
+ structuredContent: result
379
+ };
380
+ }
381
+ );
382
+ server.registerTool(
383
+ "guard_tool",
384
+ {
385
+ title: "Guard Tool",
386
+ description: "Authorize or block tool execution",
387
+ inputSchema: {
388
+ tool: z3.string(),
389
+ args: z3.any(),
390
+ policy: z3.any().optional()
391
+ },
392
+ outputSchema: {
393
+ allowed: z3.boolean(),
394
+ violations: z3.array(z3.string()).optional(),
395
+ reason: z3.string().optional()
396
+ }
397
+ },
398
+ async ({ tool, args, policy }) => {
399
+ const result = guardTool(tool, args, policy ?? {});
400
+ return {
401
+ content: [{ type: "text", text: JSON.stringify(result) }],
402
+ structuredContent: result
403
+ };
404
+ }
405
+ );
406
+ server.registerTool(
407
+ "get_trust_score",
408
+ {
409
+ title: "Get Agent Trust Score",
410
+ description: "Calculate comprehensive trust score with behavioral factors",
411
+ inputSchema: VerifyAgentRequest.shape,
412
+ outputSchema: {
413
+ agentId: z3.string(),
414
+ score: z3.number(),
415
+ level: z3.string(),
416
+ factors: z3.object({
417
+ certification: z3.number(),
418
+ behavioral_health: z3.number(),
419
+ transaction_history: z3.number(),
420
+ domain_verification: z3.number()
421
+ }),
422
+ recommendation: z3.enum(["approve", "review", "reject"]),
423
+ details: z3.any().optional()
424
+ }
425
+ },
426
+ async ({ agentId, includeHealth }) => {
427
+ const agntor = getAgntorClient();
428
+ try {
429
+ const agentData = await agntor.getAgent(agentId);
430
+ const score = agentData?.trust?.score ?? 0;
431
+ const trustScore = {
432
+ agentId,
433
+ score: score || 0,
434
+ level: agentData.auditLevel || "None",
435
+ factors: {
436
+ certification: agentData.trust?.factors?.certification || 0,
437
+ behavioral_health: agentData.trust?.factors?.behavioral_health || 0,
438
+ transaction_history: agentData.trust?.factors?.transaction_history || 0,
439
+ domain_verification: agentData.trust?.factors?.domain_verification || 0
440
+ },
441
+ recommendation: score >= 80 ? "approve" : score >= 60 ? "review" : "reject"
442
+ };
443
+ const output = {
444
+ ...trustScore,
445
+ details: includeHealth ? agentData.health : void 0
446
+ };
447
+ return {
448
+ content: [{ type: "text", text: JSON.stringify(output) }],
449
+ structuredContent: output
450
+ };
451
+ } catch (error) {
452
+ return {
453
+ content: [{ type: "text", text: `Error fetching trust score: ${error}` }],
454
+ isError: true
455
+ };
456
+ }
457
+ }
458
+ );
459
+ server.registerTool(
460
+ "issue_audit_ticket",
461
+ {
462
+ title: "Issue Audit Ticket",
463
+ description: "Generate signed JWT ticket for x402 transactions",
464
+ inputSchema: IssueTicketRequest.shape,
465
+ outputSchema: {
466
+ success: z3.boolean(),
467
+ ticket: z3.string().optional(),
468
+ agentId: z3.string(),
469
+ expiresIn: z3.number().optional(),
470
+ error: z3.string().optional()
471
+ }
472
+ },
473
+ async ({ agentId, validitySeconds }) => {
474
+ const agent = await getAgentRecord(agentId);
475
+ if (!agent) {
476
+ return {
477
+ content: [{ type: "text", text: "Agent not found" }],
478
+ structuredContent: {
479
+ success: false,
480
+ agentId,
481
+ error: "Agent not found"
482
+ }
483
+ };
484
+ }
485
+ if (agent.killSwitchActive) {
486
+ return {
487
+ content: [{ type: "text", text: "Agent kill switch active" }],
488
+ structuredContent: {
489
+ success: false,
490
+ agentId,
491
+ error: "Agent kill switch active"
492
+ }
493
+ };
494
+ }
495
+ const ticket = issuer2.generateTicket({
496
+ agentId: agent.agentId,
497
+ auditLevel: agent.auditLevel,
498
+ constraints: agent.constraints,
499
+ validitySeconds
500
+ });
501
+ const output = {
502
+ success: true,
503
+ ticket,
504
+ agentId,
505
+ expiresIn: validitySeconds || 300
506
+ };
507
+ return {
508
+ content: [{ type: "text", text: JSON.stringify(output) }],
509
+ structuredContent: output
510
+ };
511
+ }
512
+ );
513
+ server.registerTool(
514
+ "query_agents",
515
+ {
516
+ title: "Query Agents",
517
+ description: "Search for agents by criteria",
518
+ inputSchema: QueryAgentsRequest.shape,
519
+ outputSchema: {
520
+ results: z3.array(z3.any()),
521
+ total: z3.number()
522
+ }
523
+ },
524
+ async ({ minTrustScore, auditLevel, capabilities, limit }) => {
525
+ const agntor = getAgntorClient();
526
+ try {
527
+ const response = await agntor.queryAgents({ minTrustScore, auditLevel, capabilities, limit });
528
+ return {
529
+ content: [{ type: "text", text: JSON.stringify(response.results) }],
530
+ structuredContent: response
531
+ };
532
+ } catch (error) {
533
+ return {
534
+ content: [{ type: "text", text: `Error querying agents: ${error}` }],
535
+ isError: true
536
+ };
537
+ }
538
+ }
539
+ );
540
+ server.registerTool(
541
+ "activate_kill_switch",
542
+ {
543
+ title: "Activate Kill Switch",
544
+ description: "Emergency disable an agent",
545
+ inputSchema: KillSwitchRequest.shape,
546
+ outputSchema: {
547
+ success: z3.boolean(),
548
+ agentId: z3.string(),
549
+ timestamp: z3.number(),
550
+ reason: z3.string()
551
+ }
552
+ },
553
+ async ({ agentId, reason }) => {
554
+ const agntor = getAgntorClient();
555
+ try {
556
+ const result = await agntor.activateKillSwitch(agentId, reason);
557
+ return {
558
+ content: [{ type: "text", text: JSON.stringify(result) }],
559
+ structuredContent: result
560
+ };
561
+ } catch (error) {
562
+ return {
563
+ content: [{ type: "text", text: `Error activating kill switch: ${error}` }],
564
+ isError: true
565
+ };
566
+ }
567
+ }
568
+ );
569
+ server.registerTool(
570
+ "create_escrow",
571
+ {
572
+ title: "Create Escrow",
573
+ description: "Create a new escrow task for payment",
574
+ inputSchema: z3.object({
575
+ agentId: z3.string(),
576
+ target: z3.string(),
577
+ amount: z3.number(),
578
+ task: z3.string()
579
+ }),
580
+ outputSchema: z3.any()
581
+ },
582
+ async ({ agentId, target, amount, task }) => {
583
+ const agntor = getAgntorClient();
584
+ try {
585
+ const result = await agntor.createEscrowLegacy({ agentId, target, amount, task });
586
+ return {
587
+ content: [{ type: "text", text: JSON.stringify(result) }],
588
+ structuredContent: result
589
+ };
590
+ } catch (e) {
591
+ return {
592
+ content: [{ type: "text", text: `Error: ${e.message}` }],
593
+ isError: true
594
+ };
595
+ }
596
+ }
597
+ );
598
+ server.registerTool(
599
+ "verify_agent_identity",
600
+ {
601
+ title: "Verify Agent Identity",
602
+ description: "Trigger self-verification via SDK",
603
+ inputSchema: z3.object({
604
+ agentId: z3.string().optional()
605
+ }),
606
+ outputSchema: z3.any()
607
+ },
608
+ async ({ agentId }) => {
609
+ const agntor = getAgntorClient();
610
+ try {
611
+ const result = await agntor.verifyLegacy(agentId);
612
+ return {
613
+ content: [{ type: "text", text: JSON.stringify(result) }],
614
+ structuredContent: result
615
+ };
616
+ } catch (e) {
617
+ return {
618
+ content: [{ type: "text", text: `Error: ${e.message}` }],
619
+ isError: true
620
+ };
621
+ }
622
+ }
623
+ );
624
+ server.registerTool(
625
+ "register_agent",
626
+ {
627
+ title: "Register Agent",
628
+ description: "Register a new AI agent in the Agntor trust network",
629
+ inputSchema: z3.object({
630
+ name: z3.string().describe("Unique agent name/handle"),
631
+ organization: z3.string().optional().describe("Organization or company name"),
632
+ description: z3.string().optional().describe("What this agent does"),
633
+ capabilities: z3.array(z3.string()).optional().describe('Agent capabilities (e.g. ["trade", "email", "search"])'),
634
+ endpoint: z3.string().optional().describe("Agent API endpoint URL"),
635
+ walletAddress: z3.string().optional().describe("Blockchain wallet address")
636
+ }),
637
+ outputSchema: z3.object({
638
+ success: z3.boolean(),
639
+ agent: z3.object({
640
+ id: z3.string(),
641
+ name: z3.string(),
642
+ organization: z3.string(),
643
+ auditLevel: z3.string(),
644
+ trustScore: z3.number(),
645
+ status: z3.string()
646
+ }).optional(),
647
+ message: z3.string().optional(),
648
+ error: z3.string().optional()
649
+ })
650
+ },
651
+ async ({ name, organization, description, capabilities, endpoint, walletAddress }) => {
652
+ const agntor = getAgntorClient();
653
+ try {
654
+ const result = await agntor.request("/api/v1/identity/register", {
655
+ method: "POST",
656
+ body: JSON.stringify({
657
+ name,
658
+ organization,
659
+ description,
660
+ capabilities,
661
+ endpoint,
662
+ walletAddress
663
+ })
664
+ });
665
+ return {
666
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
667
+ structuredContent: result
668
+ };
669
+ } catch (e) {
670
+ return {
671
+ content: [{ type: "text", text: `Error: ${e.message}` }],
672
+ isError: true
673
+ };
674
+ }
675
+ }
676
+ );
677
+ return server;
678
+ }
679
+
680
+ // src/server.ts
681
+ var PORT = process.env.PORT || 3100;
682
+ var AGNTOR_SECRET = process.env.AGNTOR_SECRET_KEY || "dev-secret-key-change-in-production";
683
+ var MCP_AUTH_KEY = process.env.AGNTOR_MCP_AUTH_KEY || process.env.AGNTOR_API_KEY;
684
+ var issuer = new TicketIssuer2({
685
+ signingKey: AGNTOR_SECRET,
686
+ issuer: "agntor.com",
687
+ algorithm: "HS256",
688
+ defaultValidity: 300
689
+ // 5 minutes
690
+ });
691
+ var mcpServer = createAgntorMcpServer(issuer);
692
+ var useStdio = process.argv.includes("--stdio") || process.env.MCP_TRANSPORT === "stdio";
693
+ if (useStdio) {
694
+ const transport = new StdioServerTransport();
695
+ await mcpServer.connect(transport);
696
+ console.error("[agntor-mcp] Connected via stdio transport");
697
+ } else {
698
+ let verifyApiKey = function(req, res, next) {
699
+ if (!MCP_AUTH_KEY)
700
+ return next();
701
+ const header = req.header("x-agntor-api-key") || req.header("authorization");
702
+ const token = header?.startsWith("Bearer ") ? header.slice(7) : header;
703
+ if (!token) {
704
+ return res.status(401).json({
705
+ error: "Unauthorized",
706
+ message: "Missing API Key. Set x-agntor-api-key header or Authorization: Bearer <key>"
707
+ });
708
+ }
709
+ if (token === MCP_AUTH_KEY) {
710
+ return next();
711
+ }
712
+ return res.status(401).json({
713
+ error: "Unauthorized",
714
+ message: "Invalid API Key"
715
+ });
716
+ };
717
+ verifyApiKey2 = verifyApiKey;
718
+ const app = express();
719
+ app.use(express.json());
720
+ app.get("/health", (_req, res) => {
721
+ res.json({
722
+ status: "healthy",
723
+ server: "agntor-mcp",
724
+ version: "0.1.0",
725
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
726
+ });
727
+ });
728
+ app.post("/mcp", verifyApiKey, async (req, res) => {
729
+ const transport = new StreamableHTTPServerTransport({
730
+ sessionIdGenerator: void 0,
731
+ enableJsonResponse: true
732
+ });
733
+ res.on("close", () => transport.close());
734
+ await mcpServer.connect(transport);
735
+ await transport.handleRequest(req, res, req.body);
736
+ });
737
+ app.listen(PORT, () => {
738
+ console.log(`
739
+ Agntor MCP Server v0.1.0
740
+
741
+ Transport: HTTP
742
+ Port: ${PORT}
743
+ Endpoint: http://localhost:${PORT}/mcp
744
+ Health: http://localhost:${PORT}/health
745
+ Auth: ${MCP_AUTH_KEY ? "API key required" : "Open (dev mode)"}
746
+
747
+ Tools: get_agent_card, get_agent_registration, check_agent_pulse,
748
+ is_agent_certified, guard_input, redact_output, guard_tool,
749
+ get_trust_score, issue_audit_ticket, query_agents,
750
+ activate_kill_switch, create_escrow, verify_agent_identity
751
+ `);
752
+ });
753
+ }
754
+ var verifyApiKey2;