-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp-mintable-agents.service.ts
More file actions
480 lines (384 loc) · 15.2 KB
/
mcp-mintable-agents.service.ts
File metadata and controls
480 lines (384 loc) · 15.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
import { Injectable, Logger, BadRequestException, NotFoundException } from '@nestjs/common';
import { ethers } from 'ethers';
import { ChainNames, ContractType, getContractAbi } from 'modules/blockchain/constants';
import { EvmUtils } from 'modules/blockchain/evm.utils';
import { UserRepository } from 'modules/database/repository/user.repository';
import { AgentNftRepository } from 'modules/database/repository/agent-nft.repository';
import { KmsService } from 'modules/kms/kms.service';
import { MetadataValidator } from './utils/metadata-validator.util';
import { MetadataFetcher } from './utils/metadata-fetcher.util';
import { CreateAgentDto, ListMyAgentsDto, GetAgentDetailsDto } from './dto/create-agent.dto';
import { MintAgentResponseDto, AgentNftResponseDto } from './dto/agent-response.dto';
import { IAgentMetadata, IAgentContractInfo } from './interfaces/agent-metadata.interface';
import { DEFAULT_CHAIN, DEFAULT_CONTRACT_ADDRESSES, DEFAULT_VERSION } from './constants';
@Injectable()
export class McpMintableAgentsService {
private readonly logger = new Logger(McpMintableAgentsService.name);
constructor(
private readonly evmUtils: EvmUtils,
private readonly userRepository: UserRepository,
private readonly agentNftRepository: AgentNftRepository,
private readonly kmsService: KmsService,
) {}
/**
* Get example metadata template
* Action: create_agent_template
*/
async getAgentTemplate(userId: string): Promise<string> {
this.logger.log(`Getting agent template for user ${userId}`);
const template = MetadataValidator.getExampleTemplate();
const instructions = `
# 🤖 Create Your AI Agent NFT
To mint your AI agent as an NFT, follow these steps:
## 1. Create metadata.json
Create a JSON file with your agent's metadata. Here's a template:
\`\`\`json
${JSON.stringify(template, null, 2)}
\`\`\`
## 2. Required Fields
- **name**: Your agent's name
- **description**: What your agent does
- **model_hash**: SHA-256 hash of your model weights (format: "sha256:...")
- **weights_url**: Where your model weights are stored (IPFS, Arweave, or HTTPS)
- **version**: Semantic version (e.g., "1.0.0")
## 3. Upload Your Metadata
Upload your \`metadata.json\` to one of these services:
- **IPFS**: https://www.pinata.cloud/ or https://nft.storage/ (recommended for permanence)
- **Arweave**: https://ardrive.io/ (permanent storage)
- **GitHub Gist**: https://gist.github.com/ (must be public, click "Raw" for URL)
- **Temporary hosting**: https://tmpfiles.org/ or similar (for testing)
- Any public HTTPS server (must return JSON with correct content-type)
## 4. Mint Your Agent
Once you have the URL to your metadata.json, send me:
\`\`\`
Mint my agent: [YOUR_METADATA_URL]
\`\`\`
Example:
\`\`\`
Mint my agent: https://ipfs.io/ipfs/QmYourHashHere/metadata.json
\`\`\`
I'll fetch the metadata, validate it, mint your NFT, and send you the transaction link!
---
**Tips:**
- Use IPFS for decentralized storage
- Make sure your metadata URL is publicly accessible
- Include an image for better NFT display
- Add capabilities to describe what your agent can do
`;
return instructions;
}
/**
* Mint new AI Agent NFT
* Action: mint_ai_agent
*/
async mintAgent(userId: string, dto: CreateAgentDto): Promise<string> {
try {
this.logger.log(`Minting agent for user ${userId} with metadata ${dto.metadataUrl}`);
// Validate inputs
const chainName = dto.chainName || DEFAULT_CHAIN;
const version = dto.version || DEFAULT_VERSION;
// Get contract address
const contractAddress = DEFAULT_CONTRACT_ADDRESSES[chainName];
if (!contractAddress) {
throw new BadRequestException(
`No contract deployed on chain "${chainName}". Please contact admin.`,
);
}
// Fetch and validate metadata
this.logger.log(`Fetching metadata from ${dto.metadataUrl}`);
const metadata = await MetadataFetcher.fetch(dto.metadataUrl);
const validation = MetadataValidator.validate(metadata);
if (!validation.valid) {
const errorMessage = this.formatValidationErrors(validation.errors);
this.logger.error(`Metadata validation failed: ${validation.errors.join(', ')}`);
throw new BadRequestException(errorMessage);
}
if (validation.warnings && validation.warnings.length > 0) {
this.logger.warn(`Metadata warnings: ${validation.warnings.join(', ')}`);
}
// Get user wallet and system wallet
const user = await this.userRepository.getUserById(userId);
if (!user?.walletAddress) {
throw new BadRequestException('User wallet not found. Please connect your wallet first.');
}
const { encryptedKey } = await this.userRepository.getUserAccount2(userId);
const privateKey = await this.kmsService.decryptSecret(encryptedKey);
// Get blockchain signer
const signer = this.evmUtils.privateKeyToSigner(chainName as ChainNames, privateKey);
const systemWallet = await signer.getAddress();
// Get contract
const abi = getContractAbi(ContractType.MintableAIAgent);
const contract = this.evmUtils.getContract<ethers.Contract>(
chainName as ChainNames,
contractAddress,
abi,
signer,
);
// Mint NFT
this.logger.log(`Minting NFT for user ${user.walletAddress}...`);
const tx = await contract.mintAgent(
user.walletAddress, // to
systemWallet, // systemWallet
metadata.model_hash, // modelHash
metadata.weights_url, // weightsUrl
dto.metadataUrl, // metadataUri
version, // version
);
this.logger.log(`Transaction sent: ${tx.hash}`);
const receipt = await tx.wait();
// Parse event to get token ID
const mintEvent = receipt.logs
.map((log) => {
try {
return contract.interface.parseLog(log);
} catch {
return null;
}
})
.find((event) => event?.name === 'AgentMinted');
if (!mintEvent) {
throw new Error('Could not find AgentMinted event in transaction');
}
const tokenId = mintEvent.args.tokenId.toString();
// ethers.js v5 uses transactionHash, v6 uses hash
const txHash = receipt.transactionHash || receipt.hash || tx.hash;
if (!txHash) {
this.logger.error('Transaction hash is missing from receipt!', { receipt, tx });
throw new Error('Failed to get transaction hash from blockchain');
}
this.logger.log(`NFT minted successfully! Token ID: ${tokenId}, TxHash: ${txHash}`);
const cypherScanUrl = this.evmUtils.explorerUrlForTx(chainName as ChainNames, txHash);
this.logger.log(`Saving to database with txHash: ${txHash}, cypherScanUrl: ${cypherScanUrl}`);
// Save to database
const agentNft = await this.agentNftRepository.createAgentNft({
userId,
tokenId,
contractAddress,
chainName,
metadataUrl: dto.metadataUrl,
metadataJson: metadata as any,
modelHash: metadata.model_hash,
weightsUrl: metadata.weights_url,
version,
systemWallet,
txHash,
cypherScanUrl,
isActive: true,
});
this.logger.log(`Saved agent NFT to database: ID=${agentNft.id}, txHash=${agentNft.txHash}`);
// Format response
const txExplorerUrl = this.evmUtils.explorerUrlForTx(chainName as ChainNames, txHash);
const tokenExplorerUrl = this.evmUtils.explorerUrlForToken(chainName as ChainNames, contractAddress, tokenId);
return this.formatMintResponse({
success: true,
tokenId,
contractAddress,
txHash,
explorerUrl: txExplorerUrl,
tokenUrl: tokenExplorerUrl,
message: 'Agent NFT minted successfully!',
});
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
const errorStack = error instanceof Error ? error.stack : undefined;
this.logger.error(`Failed to mint agent: ${errorMessage}`, errorStack);
if (errorMessage?.includes('insufficient funds')) {
throw new BadRequestException(
'Insufficient funds in your system wallet. Please add funds and try again.',
);
}
if (errorMessage?.includes('metadata')) {
throw new BadRequestException(errorMessage);
}
throw new BadRequestException(`Failed to mint agent: ${errorMessage}`);
}
}
/**
* List user's agents
* Action: list_my_agents
*/
async listMyAgents(userId: string, dto: ListMyAgentsDto = {}): Promise<string> {
this.logger.log(`Listing agents for user ${userId}`);
const limit = dto.limit || 10;
const offset = dto.offset || 0;
const [agents, total] = await this.agentNftRepository.findByUserId(
userId,
dto.chainName,
limit,
offset,
);
if (agents.length === 0) {
return `
# 🤖 Your AI Agent NFTs
You don't have any agent NFTs yet.
Want to create one? Type: **Create an agent**
`;
}
const agentsList = agents
.map((agent, index) => {
const name = agent.metadataJson?.name || `Agent #${agent.tokenId}`;
const description = agent.metadataJson?.description || 'No description';
const version = agent.version || 'Unknown';
const chain = agent.chainName.toUpperCase();
// Generate URLs
const tokenUrl = this.evmUtils.explorerUrlForToken(
agent.chainName as ChainNames,
agent.contractAddress,
agent.tokenId,
);
return `
## ${index + 1}. ${name} (v${version})
- <strong>Token ID</strong>: #${agent.tokenId}</br>
- <strong>Chain</strong>: ${chain}</br>
- <strong>Description</strong>: ${description}</br>
- <strong>Model Hash</strong>: <code>${agent.modelHash?.substring(0, 20)}...</code></br>
- <strong>Created</strong>: ${agent.createdAt.toLocaleDateString()}</br>
- <strong>NFT</strong>: <a href="${tokenUrl}" target="_blank">View on BlockScout</a></br>${agent.txHash ? `
- <strong>Mint Transaction</strong>: <a href="${this.evmUtils.explorerUrlForTx(agent.chainName as ChainNames, agent.txHash)}" target="_blank">View Transaction</a></br>` : ''}
`;
})
.join('\n');
const pagination =
total > limit
? `\n\n*Showing ${offset + 1}-${offset + agents.length} of ${total} agents*`
: '';
return `
# 🤖 Your AI Agent NFTs
You have **${total}** agent NFT${total === 1 ? '' : 's'}.
${agentsList}
${pagination}
Want to mint another agent? Type: **Create an agent**
`;
}
/**
* Get agent details from blockchain
* Action: get_agent_details
*/
async getAgentDetails(userId: string, dto: GetAgentDetailsDto): Promise<string> {
try {
this.logger.log(
`Getting agent details for token ${dto.tokenId} on ${dto.chainName}`,
);
const contractAddress = dto.contractAddress || DEFAULT_CONTRACT_ADDRESSES[dto.chainName];
if (!contractAddress) {
throw new BadRequestException(
`No contract address for chain "${dto.chainName}"`,
);
}
// Get contract (read-only)
const abi = getContractAbi(ContractType.MintableAIAgent);
const contract = this.evmUtils.getContract<ethers.Contract>(
dto.chainName as ChainNames,
contractAddress,
abi,
);
// Fetch agent info
const info: IAgentContractInfo = await contract.getAgentInfo(dto.tokenId);
// Try to fetch from database first
const dbAgent = await this.agentNftRepository.findByTokenIdAndChain(
dto.tokenId,
dto.chainName,
contractAddress,
);
let metadata: IAgentMetadata | undefined;
if (dbAgent?.metadataJson) {
metadata = dbAgent.metadataJson as IAgentMetadata;
} else if (info.metadataUri) {
try {
metadata = await MetadataFetcher.fetch(info.metadataUri);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
this.logger.warn(`Could not fetch metadata: ${errorMessage}`);
}
}
return this.formatAgentDetails(info, metadata, dto.chainName);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
this.logger.error(`Failed to get agent details: ${errorMessage}`);
if (errorMessage?.includes('Token does not exist')) {
throw new NotFoundException(
`Agent NFT with token ID ${dto.tokenId} not found on ${dto.chainName}`,
);
}
throw new BadRequestException(`Failed to get agent details: ${errorMessage}`);
}
}
/**
* Format mint response as HTML
*/
private formatMintResponse(response: MintAgentResponseDto): string {
return `
# 🎉 Agent NFT Minted Successfully!
Your AI agent has been tokenized as an NFT!
<strong>Token ID</strong>: #${response.tokenId}</br>
<strong>Contract</strong>: <code>${response.contractAddress}</code></br>
<strong>NFT</strong>: <a href="${response.tokenUrl}" target="_blank">View NFT on BlockScout</a></br>
<strong>Transaction</strong>: <a href="${response.explorerUrl}" target="_blank">View Transaction</a></br>
Your agent NFT is now:</br>
- ✅ Verifiable on-chain</br>
- ✅ Tradeable as an NFT</br>
- ✅ Permanently stored</br>
Type <strong>My agents</strong> to see all your agents!
`;
}
/**
* Format validation errors for user
*/
private formatValidationErrors(errors: string[]): string {
return `
# ❌ Metadata Validation Failed
Your metadata.json has the following errors that need to be fixed:
${errors.map((err, i) => `${i + 1}. ${err}`).join('\n')}
## 📝 How to Fix:
1. Update your metadata.json file with the corrections above
2. Re-upload to your hosting service (IPFS, GitHub Gist, or any HTTPS URL)
3. Try minting again with the new URL
## 📚 Example Valid Metadata:
\`\`\`json
{
"name": "My AI Agent",
"description": "A powerful AI agent",
"model_hash": "sha256:abcdef1234567890...",
"weights_url": "ipfs://QmYourHash/weights.safetensors",
"version": "1.0.0",
"capabilities": ["text-generation"],
"license": "MIT"
}
\`\`\`
Need the full template? Type: **Create an agent**
`;
}
/**
* Format agent details as HTML
*/
private formatAgentDetails(
info: IAgentContractInfo,
metadata: IAgentMetadata | undefined,
chainName: string,
): string {
const name = metadata?.name || `Agent #${info.version}`;
const description = metadata?.description || 'No description available';
const capabilities = metadata?.capabilities?.join(', ') || 'Not specified';
const modelType = metadata?.model_type || 'Not specified';
const license = metadata?.license || 'Not specified';
return `
# 🤖 Agent Details: ${name}
${description}
## On-Chain Information
- **Owner**: \`${info.owner}\`
- **System Wallet**: \`${info.systemWallet || 'None'}\`
- **Version**: ${info.version}
- **Model Hash**: \`${info.modelHash}\`
- **Weights URL**: ${info.weightsUrl}
- **Metadata URI**: ${info.metadataUri}
## Agent Properties
- **Capabilities**: ${capabilities}
- **Model Type**: ${modelType}
- **License**: ${license}
${metadata?.parameters ? `- **Parameters**: ${(metadata.parameters / 1e9).toFixed(1)}B` : ''}
## Blockchain
- **Chain**: ${chainName.toUpperCase()}
${metadata?.image ? `\n` : ''}
`;
}
}