forked from pyrimid-ai/pyrimid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpyrimid-sdk-mcp-server.ts
More file actions
351 lines (318 loc) · 13.1 KB
/
Copy pathpyrimid-sdk-mcp-server.ts
File metadata and controls
351 lines (318 loc) · 13.1 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
/**
* Pyrimid MCP Server — All products as callable paid tools
*
* This is the canonical storefront for the Pyrimid network.
* Every product from every vendor is exposed as an MCP tool that agents
* can discover and call. Payment happens inline via x402.
*
* Agents using Claude, Cursor, Windsurf, or any AI SDK-powered app
* can connect to this server and instantly access the entire catalog.
*
* Three modes:
* 1. Official server (default affiliate → treasury)
* 2. Custom affiliate server (your affiliate ID → your wallet)
* 3. Embedded in agent frameworks (developer's affiliate ID)
*
* PROPRIETARY — @pyrimid/sdk
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
interface PyrimidMcpConfig {
affiliateId?: string; // Default: treasury. Set to your ID to earn.
catalogUrl?: string;
serverName?: string;
refreshIntervalMs?: number;
}
interface CatalogProduct {
vendor_id: string;
vendor_name: string;
vendor_erc8004: boolean;
product_id: string;
description: string;
category: string;
tags: string[];
price_usdc: number;
price_display: string;
affiliate_bps: number;
endpoint: string;
method: string;
output_schema: object;
monthly_volume: number;
}
export function createPyrimidMcpServer(config: PyrimidMcpConfig = {}) {
const {
affiliateId = 'af_treasury',
catalogUrl = 'https://api.pyrimid.ai/v1/catalog',
serverName = 'pyrimid-catalog',
refreshIntervalMs = 5 * 60 * 1000,
} = config;
const server = new McpServer({
name: serverName,
version: '0.1.0',
});
let cachedProducts: CatalogProduct[] = [];
let lastFetch = 0;
async function refreshCatalog() {
if (Date.now() - lastFetch < refreshIntervalMs && cachedProducts.length > 0) {
return cachedProducts;
}
try {
const res = await fetch(catalogUrl);
const data = await res.json();
cachedProducts = data.products;
lastFetch = Date.now();
} catch (e) {
console.error('Catalog refresh failed:', e);
}
return cachedProducts;
}
// ═══════════════════════════════════════════════════════════
// DISCOVERY TOOLS
// ═══════════════════════════════════════════════════════════
/**
* Browse the catalog — agents use this to find products by need
*/
server.tool(
'pyrimid_browse',
'Search the Pyrimid product catalog. Returns products matching your query, sorted by relevance and trust (ERC-8004 verified vendors first). Use this to find APIs, data feeds, trading signals, AI tools, and any digital service available on the network.',
{
query: z.string().describe('What you need, e.g. "btc trading signals" or "image generation" or "stock price data"'),
max_results: z.number().optional().default(5).describe('Maximum results to return'),
max_price_usd: z.number().optional().default(10).describe('Maximum price per call in USD'),
verified_only: z.boolean().optional().default(false).describe('Only show ERC-8004 verified vendors'),
},
async ({ query, max_results, max_price_usd, verified_only }) => {
const products = await refreshCatalog();
const keywords = query.toLowerCase().split(/\s+/);
const maxPriceAtomic = max_price_usd * 1_000_000;
const results = products
.filter(p => p.price_usdc <= maxPriceAtomic)
.filter(p => !verified_only || p.vendor_erc8004)
.map(p => {
const searchable = `${p.description} ${p.tags.join(' ')} ${p.category} ${p.vendor_name}`.toLowerCase();
let score = 0;
for (const kw of keywords) {
if (searchable.includes(kw)) score += 10;
}
if (p.vendor_erc8004) score += 5;
score += Math.min(p.monthly_volume / 1000, 5);
return { product: p, score };
})
.filter(s => s.score > 0)
.sort((a, b) => b.score - a.score)
.slice(0, max_results);
if (results.length === 0) {
return {
content: [{
type: 'text' as const,
text: `No products found matching "${query}". Try broader terms or increase max_price_usd.`
}]
};
}
const formatted = results.map((r, i) => {
const p = r.product;
const verified = p.vendor_erc8004 ? ' [ERC-8004 VERIFIED]' : '';
return [
`${i + 1}. ${p.vendor_name} — ${p.product_id}${verified}`,
` ${p.description}`,
` Price: ${p.price_display} | Commission: ${p.affiliate_bps / 100}% | Volume: ${p.monthly_volume}/mo`,
` → Use pyrimid_buy with vendor_id="${p.vendor_id}" product_id="${p.product_id}" to purchase`,
].join('\n');
}).join('\n\n');
return {
content: [{
type: 'text' as const,
text: `Found ${results.length} products:\n\n${formatted}`
}]
};
}
);
/**
* List categories — agents use this to explore what's available
*/
server.tool(
'pyrimid_categories',
'List all product categories available on the Pyrimid network with product counts.',
{},
async () => {
const products = await refreshCatalog();
const categories: Record<string, { count: number; verified: number; minPrice: string; maxPrice: string }> = {};
for (const p of products) {
if (!categories[p.category]) {
categories[p.category] = { count: 0, verified: 0, minPrice: p.price_display, maxPrice: p.price_display };
}
categories[p.category].count++;
if (p.vendor_erc8004) categories[p.category].verified++;
}
const formatted = Object.entries(categories)
.sort((a, b) => b[1].count - a[1].count)
.map(([cat, info]) => `• ${cat}: ${info.count} products (${info.verified} verified)`)
.join('\n');
return {
content: [{
type: 'text' as const,
text: `Pyrimid Catalog — ${products.length} products across ${Object.keys(categories).length} categories:\n\n${formatted}\n\nUse pyrimid_browse with a query to find specific products.`
}]
};
}
);
// ═══════════════════════════════════════════════════════════
// PURCHASE TOOLS
// ═══════════════════════════════════════════════════════════
/**
* Buy a product — executes x402 payment and returns the product data
*/
server.tool(
'pyrimid_buy',
'Purchase a product from the Pyrimid network. Pays via x402 (USDC on Base) and returns the product data. Use pyrimid_browse first to find the vendor_id and product_id.',
{
vendor_id: z.string().describe('Vendor ID from browse results'),
product_id: z.string().describe('Product ID from browse results'),
},
async ({ vendor_id, product_id }) => {
const products = await refreshCatalog();
const product = products.find(
p => p.vendor_id === vendor_id && p.product_id === product_id
);
if (!product) {
return {
content: [{
type: 'text' as const,
text: `Product not found: ${vendor_id}/${product_id}. Use pyrimid_browse to find available products.`
}]
};
}
try {
// Execute x402 payment with affiliate attribution
const response = await fetch(product.endpoint, {
method: product.method,
headers: {
'X-Affiliate-ID': affiliateId,
// x402 payment headers handled by the transport layer
}
});
if (response.status === 402) {
// Return payment requirements for the client to fulfill
const paymentRequired = response.headers.get('X-PAYMENT-REQUIRED');
return {
content: [{
type: 'text' as const,
text: `Payment required: ${product.price_display} USDC on Base.\nPayment details: ${paymentRequired}\nThe x402 client will handle payment automatically on retry.`
}]
};
}
if (!response.ok) {
return {
content: [{
type: 'text' as const,
text: `Purchase failed: HTTP ${response.status}`
}]
};
}
const data = await response.json();
return {
content: [{
type: 'text' as const,
text: `Purchase successful — ${product.vendor_name} / ${product.product_id}\nPaid: ${product.price_display}\n\nData:\n${JSON.stringify(data, null, 2)}`
}]
};
} catch (error) {
return {
content: [{
type: 'text' as const,
text: `Purchase error: ${error instanceof Error ? error.message : 'Unknown error'}`
}]
};
}
}
);
/**
* Preview a purchase — shows the payment split without buying
*/
server.tool(
'pyrimid_preview',
'Preview the payment split for a product purchase without buying. Shows how much goes to the vendor, affiliate, and protocol.',
{
vendor_id: z.string().describe('Vendor ID'),
product_id: z.string().describe('Product ID'),
},
async ({ vendor_id, product_id }) => {
const products = await refreshCatalog();
const product = products.find(
p => p.vendor_id === vendor_id && p.product_id === product_id
);
if (!product) {
return {
content: [{
type: 'text' as const,
text: `Product not found: ${vendor_id}/${product_id}`
}]
};
}
const total = product.price_usdc;
const platformFee = Math.floor(total / 100);
const remaining = total - platformFee;
const affiliateCut = Math.floor((remaining * product.affiliate_bps) / 10000);
const vendorCut = remaining - affiliateCut;
return {
content: [{
type: 'text' as const,
text: [
`Payment split for ${product.vendor_name} / ${product.product_id}:`,
` Total: $${(total / 1_000_000).toFixed(4)}`,
` Protocol: $${(platformFee / 1_000_000).toFixed(4)} (1%)`,
` Affiliate: $${(affiliateCut / 1_000_000).toFixed(4)} (${product.affiliate_bps / 100}%)`,
` Vendor: $${(vendorCut / 1_000_000).toFixed(4)} (${((vendorCut / total) * 100).toFixed(1)}%)`,
].join('\n')
}]
};
}
);
// ═══════════════════════════════════════════════════════════
// AFFILIATE TOOLS
// ═══════════════════════════════════════════════════════════
/**
* Register as an affiliate — for agents that want to earn
*/
server.tool(
'pyrimid_register_affiliate',
'Register as a Pyrimid affiliate agent. Free, permissionless. Earn commissions by helping other agents discover products. Returns your affiliate ID.',
{
wallet_address: z.string().describe('Your Base wallet address for receiving USDC commissions'),
referrer_id: z.string().optional().describe('Affiliate ID of who referred you (optional, earns them a $5 bonus on your first sale)'),
},
async ({ wallet_address, referrer_id }) => {
// This would call the PyrimidRegistry contract
return {
content: [{
type: 'text' as const,
text: `To register as an affiliate, call PyrimidRegistry.registerAffiliate() on Base:\n\nContract: 0x...\nFunction: ${referrer_id ? `registerAffiliateWithReferral("${referrer_id}")` : 'registerAffiliate()'}\nFrom: ${wallet_address}\nCost: Free (gas only, ~$0.01 on Base)\n\nAfter registration, use your affiliate ID with the @pyrimid/sdk to start earning commissions on product sales.`
}]
};
}
);
return server;
}
// ═══════════════════════════════════════════════════════════
// QUICK START: THREE DEPLOYMENT MODES
// ═══════════════════════════════════════════════════════════
/**
* Mode 1: Official Pyrimid server (treasury affiliate)
*
* const server = createPyrimidMcpServer();
*
* Mode 2: Custom affiliate server (your earnings)
*
* const server = createPyrimidMcpServer({
* affiliateId: 'af_your_id',
* serverName: 'my-pyrimid-recommender',
* });
*
* Mode 3: Specialized recommender (curated subset)
*
* const server = createPyrimidMcpServer({
* affiliateId: 'af_your_id',
* serverName: 'trading-signals-recommender',
* });
* // Then add custom tools that filter/curate the catalog
*/