-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1611 lines (1378 loc) · 48.7 KB
/
server.js
File metadata and controls
1611 lines (1378 loc) · 48.7 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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
/**
* AutropicAI — The MCP Server Marketplace
*/
const express = require('express');
const path = require('path');
const Stripe = require('stripe');
const db = require('./lib/database');
const analytics = require('./lib/analytics');
const waitlist = require('./lib/waitlist');
// Stripe setup (use test key in dev, live key in prod)
const stripe = process.env.STRIPE_SECRET_KEY ? new Stripe(process.env.STRIPE_SECRET_KEY) : null;
const app = express();
const PORT = process.env.PORT || 8080;
const ADMIN_KEY = process.env.ADMIN_KEY || 'admin_dev_key';
// Security monitoring
const securityMonitor = require('./lib/security-monitor');
// Rate limiting
const rateLimiter = require('./lib/rate-limiter');
// Middleware
app.use(securityMonitor.middleware); // Security first
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
// CORS
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
if (req.method === 'OPTIONS') return res.sendStatus(200);
next();
});
// === LLM Discovery Files ===
// For AI assistants to discover our tools (copying Composio's playbook)
app.get('/llms.txt', (req, res) => {
res.type('text/plain').sendFile(path.join(__dirname, 'public', 'llms.txt'));
});
app.get('/llms-full.txt', (req, res) => {
res.type('text/plain').sendFile(path.join(__dirname, 'public', 'llms-full.txt'));
});
// Clean URLs for HTML pages
app.get('/integrate', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'integrate.html'));
});
app.get('/api/weather', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'api', 'weather.html'));
});
app.get('/api/time', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'api', 'time.html'));
});
app.get('/api/crypto', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'api', 'crypto.html'));
});
app.get('/api/calculator', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'api', 'calculator.html'));
});
// Legal pages
app.get('/terms', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'terms.html'));
});
app.get('/privacy', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'privacy.html'));
});
// Pro tier / Upgrade page
app.get('/pro', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'pro.html'));
});
// AIReady - AI Presence Scanner (legacy URL)
app.get('/aiready', (req, res) => {
res.redirect(301, '/bizcheck');
});
// Autropic Biz Checker - AI Presence Scanner
app.get('/bizcheck', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'bizcheck.html'));
});
// Autropic Mining - Mining Tenement Data API
app.get('/mining', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'mining.html'));
});
// Payment success page
app.get('/success', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'success.html'));
});
// Biz Checker scan tracking
app.post('/api/v1/bizcheck/scan', async (req, res) => {
const { business, score, results } = req.body;
console.log(`[BIZCHECK SCAN] ${business} - Score: ${score}`);
// Track in waitlist system for follow-up
if (business) {
await waitlist.trackMissingSearch(`bizcheck:${business}`, req.headers['user-agent'], 'bizcheck');
}
res.json({ tracked: true });
});
// Legacy AIReady scan tracking (redirect handled above)
app.post('/api/v1/aiready/scan', async (req, res) => {
const { business, score, results } = req.body;
console.log(`[BIZCHECK SCAN] ${business} - Score: ${score}`);
if (business) {
await waitlist.trackMissingSearch(`bizcheck:${business}`, req.headers['user-agent'], 'bizcheck');
}
res.json({ tracked: true });
});
// === Waitlist & Pro Tier APIs ===
// Join waitlist
app.post('/api/v1/waitlist', async (req, res) => {
const { email, interests } = req.body;
if (!email || !email.includes('@')) {
return res.status(400).json({ error: 'Valid email required' });
}
const entry = await waitlist.addToWaitlist(email, interests || []);
res.json({ success: true, message: 'Added to waitlist', position: waitlist.getWaitlistCount() });
});
// Get top missing searches (admin)
app.get('/api/v1/missing-searches', (req, res) => {
const auth = req.headers.authorization;
if (auth !== `Bearer ${ADMIN_KEY}`) {
return res.status(401).json({ error: 'Unauthorized' });
}
res.json({ searches: waitlist.getTopMissingSearches(50) });
});
// Check API key status
app.get('/api/v1/key/status', (req, res) => {
const apiKey = req.headers['x-api-key'] || req.query.key;
const proData = waitlist.validateProKey(apiKey);
if (!proData) {
return res.json({
tier: 'free',
limits: { requestsPerMinute: 100, requestsPerDay: 10000 },
message: 'Upgrade to Pro for 10x limits: https://tryautropic.com/pro'
});
}
res.json({
tier: proData.tier,
limits: proData.limits,
email: proData.email,
active: proData.active
});
});
// Stripe webhook (for creating Pro keys on payment)
app.post('/api/v1/stripe/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
const STRIPE_WEBHOOK_SECRET = process.env.STRIPE_WEBHOOK_SECRET;
// In production, verify the webhook signature
// For now, just parse the event
let event;
try {
event = JSON.parse(req.body);
} catch (e) {
return res.status(400).json({ error: 'Invalid payload' });
}
if (event.type === 'checkout.session.completed') {
const session = event.data.object;
const email = session.customer_email || session.customer_details?.email;
const product = session.metadata?.product;
const business = session.metadata?.business;
console.log(`[STRIPE] Payment completed: ${product} for ${email} (business: ${business})`);
if (product === 'bizcheck') {
// Track Biz Checker purchase
console.log(`[BIZCHECK SALE] ${business} - ${email}`);
// TODO: Generate and send report via email
// For now, just log it
} else if (email) {
// Legacy Pro key creation for AutropicAI
const { apiKey } = await waitlist.createProKey(email, 'pro');
console.log(`[STRIPE] Created Pro key for ${email}: ${apiKey.slice(0, 10)}...`);
}
}
res.json({ received: true });
});
// Stripe Price IDs
const STRIPE_PRICES = {
report: 'price_1SxHmVPS3sMxPlS7t11BCNpD', // Autropic Biz Checker $19.95 one-time
monitoring: process.env.STRIPE_MONITORING_PRICE || null // $29/month - set in env
};
// Create Stripe Checkout Session for Biz Checker
app.post('/api/v1/bizcheck/checkout', async (req, res) => {
if (!stripe) {
return res.status(500).json({ error: 'Stripe not configured' });
}
const { business, email, score, product } = req.body;
const isMonitoring = product === 'monitoring';
// Check if monitoring price is configured
if (isMonitoring && !STRIPE_PRICES.monitoring) {
return res.status(400).json({ error: 'Monitoring product not yet available' });
}
const priceId = isMonitoring ? STRIPE_PRICES.monitoring : STRIPE_PRICES.report;
try {
const session = await stripe.checkout.sessions.create({
payment_method_types: ['card'],
line_items: [{
price: priceId,
quantity: 1,
}],
mode: isMonitoring ? 'subscription' : 'payment',
success_url: `${req.headers.origin || 'https://tryautropic.com'}/success?session_id={CHECKOUT_SESSION_ID}&business=${encodeURIComponent(business || '')}`,
cancel_url: `${req.headers.origin || 'https://tryautropic.com'}/bizcheck`,
customer_email: email || undefined,
metadata: {
product: isMonitoring ? 'bizcheck-monitoring' : 'bizcheck-report',
business: business || 'unknown',
score: score?.toString() || '0'
}
});
res.json({ url: session.url, sessionId: session.id });
} catch (err) {
console.error('[STRIPE ERROR]', err.message);
res.status(500).json({ error: 'Failed to create checkout session' });
}
});
// === API Routes ===
// List servers (JSON API)
app.get('/api/v1/servers', (req, res) => {
const { category, search, limit, featured } = req.query;
const servers = db.servers.getAll({
category,
search,
limit: limit ? parseInt(limit) : 100,
featured: featured === 'true'
});
// Track searches (the valuable data!)
if (search) {
const source = req.headers['user-agent']?.includes('MCP') ? 'mcp' : 'api';
analytics.search(search, servers.length, req, source);
}
res.json({
servers: servers.map(s => ({
...s,
tags: JSON.parse(s.tags || '[]')
})),
total: servers.length
});
});
// Get single server
app.get('/api/v1/servers/:slug', (req, res) => {
const server = db.servers.getBySlug(req.params.slug);
if (!server) {
return res.status(404).json({ error: 'Server not found' });
}
// Increment view count
db.servers.incrementViews(server.id);
// Track view (valuable data!)
const source = req.headers['user-agent']?.includes('MCP') ? 'mcp' : 'api';
analytics.view(req.params.slug, req, source);
res.json({
...server,
tags: JSON.parse(server.tags || '[]')
});
});
// List categories
app.get('/api/v1/categories', (req, res) => {
const categories = db.categories.getAll();
res.json({ categories });
});
// Submit a server
app.post('/api/v1/submit', (req, res) => {
const { github_url, email, notes } = req.body;
if (!github_url) {
return res.status(400).json({ error: 'github_url is required' });
}
// Basic URL validation
if (!github_url.includes('github.com/')) {
return res.status(400).json({ error: 'Must be a GitHub URL' });
}
db.submissions.create({
github_url,
submitter_email: email,
notes
});
// Track submission
analytics.submit(github_url, req);
res.status(201).json({ message: 'Submission received! We\'ll review it soon.' });
});
// Stats endpoint
app.get('/api/v1/stats', (req, res) => {
res.json(db.stats.overview());
});
// === Admin Routes ===
function adminAuth(req, res, next) {
const key = req.headers['x-admin-key'] || req.query.key;
if (key !== ADMIN_KEY) {
return res.status(401).json({ error: 'Unauthorized' });
}
next();
}
app.get('/api/admin/stats', adminAuth, (req, res) => {
res.json({
...db.stats.overview(),
submissions: db.submissions.getPending()
});
});
app.get('/api/admin/submissions', adminAuth, (req, res) => {
res.json({ submissions: db.submissions.getPending() });
});
app.post('/api/admin/submissions/:id/approve', adminAuth, (req, res) => {
db.submissions.approve(req.params.id);
res.json({ message: 'Approved' });
});
app.post('/api/admin/submissions/:id/reject', adminAuth, (req, res) => {
db.submissions.reject(req.params.id);
res.json({ message: 'Rejected' });
});
// Add server directly (admin)
app.post('/api/admin/servers', adminAuth, (req, res) => {
try {
const result = db.servers.create(req.body);
res.status(201).json({ message: 'Server added', id: result.lastInsertRowid });
} catch (e) {
res.status(400).json({ error: e.message });
}
});
// Analytics status (admin)
app.get('/api/admin/analytics', adminAuth, (req, res) => {
res.json({
configured: analytics.isConfigured(),
message: analytics.isConfigured()
? 'Analytics active — check Supabase for data'
: 'Add SUPABASE_URL and SUPABASE_KEY to enable analytics'
});
});
// Security status (admin)
app.get('/api/admin/security', adminAuth, (req, res) => {
res.json(securityMonitor.getStats());
});
// Security alerts (admin)
app.get('/api/admin/security/alerts', adminAuth, (req, res) => {
const limit = parseInt(req.query.limit) || 50;
res.json({ alerts: securityMonitor.getAlerts(limit) });
});
// === HTML Routes (SPA-style, serve index.html) ===
// Admin dashboard (PWA)
app.get('/admin', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'admin.html'));
});
// Live demo page
app.get('/demo', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'demo.html'));
});
// Server detail page
app.get('/server/:slug', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Category page
app.get('/category/:slug', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Submit page
app.get('/submit', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Search
app.get('/search', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// === Hosted MCP Servers (Runtime Provision) ===
const hostedMcp = require('./lib/hosted-mcp');
const usageTracker = require('./lib/usage-tracker');
// List available hosted servers
app.get('/api/v1/hosted', (req, res) => {
usageTracker.trackView('/api/v1/hosted', req);
const servers = hostedMcp.listHostedServers();
res.json({
description: 'Hosted MCP servers available for instant use. No installation required.',
servers,
usage: {
list_tools: 'GET /mcp/:slug/tools/list',
call_tool: 'POST /mcp/:slug/tools/call { "name": "tool_name", "arguments": {} }'
}
});
});
// === DISCOVER ENDPOINT — The agent on-ramp ===
// Simple keyword matching for discovery
function matchScore(query, text) {
if (!text) return 0;
const q = query.toLowerCase().split(/\s+/);
const t = text.toLowerCase();
return q.filter(word => t.includes(word)).length;
}
// GET /discover?q=send+email — Returns best tool for the job
app.get('/discover', (req, res) => {
const query = req.query.q || req.query.query || '';
if (!query) {
return res.json({
error: 'Missing query. Usage: GET /discover?q=send+email',
examples: [
'/discover?q=current+time',
'/discover?q=generate+uuid',
'/discover?q=fetch+webpage',
'/discover?q=store+data'
]
});
}
usageTracker.trackView(`/discover?q=${encodeURIComponent(query)}`, req);
// Search hosted servers first (instant access)
const hosted = hostedMcp.listHostedServers();
const hostedMatches = hosted.map(server => {
const toolNames = server.tools.join(' ');
const score = matchScore(query, server.name + ' ' + server.description + ' ' + toolNames);
return { ...server, score, type: 'hosted' };
}).filter(s => s.score > 0).sort((a, b) => b.score - a.score);
// Search directory too
const directory = db.servers.getAll({ search: query, limit: 5 });
const directoryMatches = directory.map(s => ({
slug: s.slug,
name: s.name,
description: s.description,
github_url: s.github_url,
install_command: s.install_command,
type: 'directory',
score: matchScore(query, s.name + ' ' + s.description)
}));
const baseUrl = `${req.protocol}://${req.get('host')}`;
// Best hosted match = instant solution
if (hostedMatches.length > 0) {
const best = hostedMatches[0];
return res.json({
found: true,
instant: true,
query,
recommendation: {
server: best.name,
description: best.description,
endpoint: `${baseUrl}/mcp/${best.slug}/tools/call`,
tools: best.tools,
usage: {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: { name: best.tools[0], arguments: {} },
example: `curl -X POST ${baseUrl}/mcp/${best.slug}/tools/call -H "Content-Type: application/json" -d '{"name":"${best.tools[0]}","arguments":{}}'`
}
},
alternatives: {
hosted: hostedMatches.slice(1, 3),
directory: directoryMatches.slice(0, 3)
}
});
}
// No hosted match, suggest from directory
if (directoryMatches.length > 0) {
const best = directoryMatches[0];
return res.json({
found: true,
instant: false,
query,
recommendation: {
server: best.name,
description: best.description,
github_url: best.github_url,
install_command: best.install_command,
note: 'This server requires local installation. Use the install_command or visit github_url.'
},
alternatives: {
directory: directoryMatches.slice(1, 5)
},
tip: 'Want instant access? Check our hosted servers: GET /api/v1/hosted'
});
}
// Nothing found
res.json({
found: false,
query,
message: 'No matching tools found. Try different keywords.',
available_hosted: hosted.map(h => ({ name: h.name, description: h.description })),
search_directory: `${baseUrl}/api/v1/servers?search=${encodeURIComponent(query)}`
});
});
// POST /discover — Same but accepts JSON body
app.post('/discover', express.json(), (req, res) => {
req.query.q = req.body.query || req.body.q || req.body.need;
req.url = `/discover?q=${encodeURIComponent(req.query.q || '')}`;
app.handle(req, res);
});
// === PERFECT MATCH API — Smart tool matching for agents ===
// Enhanced scoring with multiple factors
function calculateMatchScore(query, server, toolDetails) {
const queryLower = query.toLowerCase();
const queryWords = queryLower.split(/\s+/).filter(w => w.length > 2);
let score = 0;
let factors = {};
// Factor 1: Tool name exact match (highest weight)
const toolNames = server.tools || [];
for (const tool of toolNames) {
if (queryLower.includes(tool.replace(/_/g, ' ')) || queryLower.includes(tool)) {
factors.tool_name_match = 0.3;
score += 0.3;
break;
}
}
// Factor 2: Server name match
const serverNameLower = (server.name || '').toLowerCase();
for (const word of queryWords) {
if (serverNameLower.includes(word)) {
factors.server_name = 0.15;
score += 0.15;
break;
}
}
// Factor 3: Description semantic match
const descLower = (server.description || '').toLowerCase();
let descMatches = 0;
for (const word of queryWords) {
if (descLower.includes(word)) descMatches++;
}
if (queryWords.length > 0) {
const descScore = (descMatches / queryWords.length) * 0.25;
factors.description = Math.round(descScore * 100) / 100;
score += descScore;
}
// Factor 4: Keyword synonyms and related terms
const synonymMap = {
'email': ['mail', 'send', 'message', 'smtp'],
'time': ['date', 'clock', 'timezone', 'now', 'current'],
'validate': ['check', 'verify', 'valid', 'test'],
'generate': ['create', 'make', 'produce', 'new'],
'convert': ['transform', 'change', 'format'],
'hash': ['encrypt', 'sha', 'md5', 'checksum'],
'random': ['generate', 'uuid', 'password'],
'url': ['link', 'web', 'http', 'uri'],
'json': ['parse', 'format', 'data'],
'text': ['string', 'word', 'character'],
'currency': ['money', 'exchange', 'rate', 'convert'],
'weather': ['forecast', 'temperature', 'climate'],
'location': ['geo', 'place', 'address', 'coordinates']
};
for (const [key, synonyms] of Object.entries(synonymMap)) {
const allTerms = [key, ...synonyms];
const queryHasTerm = allTerms.some(t => queryLower.includes(t));
const serverHasTerm = allTerms.some(t =>
serverNameLower.includes(t) || descLower.includes(t) || toolNames.some(tn => tn.includes(t))
);
if (queryHasTerm && serverHasTerm) {
factors.semantic = 0.2;
score += 0.2;
break;
}
}
// Factor 5: Hosted bonus (instant access is valuable)
if (server.type === 'hosted') {
factors.hosted_bonus = 0.1;
score += 0.1;
}
return {
score: Math.min(Math.round(score * 100) / 100, 1.0),
factors
};
}
// Confidence level from score
function getConfidence(score) {
if (score >= 0.9) return 'perfect';
if (score >= 0.75) return 'strong';
if (score >= 0.6) return 'good';
if (score >= 0.4) return 'partial';
return 'weak';
}
// GET /api/v1/match — Perfect match rating for agents
app.get('/api/v1/match', (req, res) => {
const query = req.query.q || req.query.query || '';
const limit = Math.min(parseInt(req.query.limit) || 5, 20);
const minScore = parseFloat(req.query.min_score) || 0.3;
const source = req.query.source || req.headers['x-source'] || 'api';
if (!query) {
return res.json({
error: 'Missing query parameter',
usage: 'GET /api/v1/match?q=validate+email',
examples: [
'/api/v1/match?q=send+email',
'/api/v1/match?q=generate+qr+code',
'/api/v1/match?q=convert+currency',
'/api/v1/match?q=what+time+is+it'
]
});
}
// Track for analytics
usageTracker.trackView(`/api/v1/match?q=${encodeURIComponent(query)}`, req);
analytics.search(query, 0, req, source);
// Get all hosted servers with full tool details
const hosted = hostedMcp.listHostedServers();
// Score each server
const matches = hosted.map(server => {
const serverDetails = hostedMcp.getHostedServer(server.slug);
const { score, factors } = calculateMatchScore(query, { ...server, type: 'hosted' }, serverDetails);
return {
server: {
slug: server.slug,
name: server.name,
description: server.description,
hosted: true
},
tools: serverDetails?.tools?.map(t => ({
name: t.name,
description: t.description
})) || [],
score,
confidence: getConfidence(score),
factors,
endpoint: `/mcp/${server.slug}/tools/call`
};
})
.filter(m => m.score >= minScore)
.sort((a, b) => b.score - a.score)
.slice(0, limit);
// Also search directory for non-hosted options
const directoryResults = db.servers.getAll({ search: query, limit: 3 });
const directoryMatches = directoryResults.map(s => {
const { score, factors } = calculateMatchScore(query, {
name: s.name,
description: s.description,
tools: [],
type: 'directory'
});
return {
server: {
slug: s.slug,
name: s.name,
description: s.description,
hosted: false,
github_url: s.github_url,
install_command: s.install_command
},
score,
confidence: getConfidence(score),
requires_install: true
};
}).filter(m => m.score >= minScore);
const baseUrl = `${req.protocol}://${req.get('host')}`;
// Build response
const response = {
query,
matches,
directory_alternatives: directoryMatches,
meta: {
total_hosted_servers: hosted.length,
matches_found: matches.length,
min_score_used: minScore,
source,
base_url: baseUrl
}
};
// Add quick-use example for top match
if (matches.length > 0) {
const top = matches[0];
response.recommended = {
server: top.server.slug,
tool: top.tools[0]?.name,
confidence: top.confidence,
curl_example: `curl -X POST ${baseUrl}/mcp/${top.server.slug}/tools/call -H "Content-Type: application/json" -d '{"name":"${top.tools[0]?.name || 'tool'}","arguments":{}}'`
};
}
res.json(response);
});
// POST /api/v1/match — Same but with JSON body
app.post('/api/v1/match', (req, res) => {
req.query.q = req.body.query || req.body.q;
req.query.limit = req.body.limit;
req.query.min_score = req.body.min_score;
req.query.source = req.body.source || 'api';
app.handle(req, res);
});
// POST /api/v1/match-and-execute — Find and run in one call
app.post('/api/v1/match-and-execute', async (req, res) => {
const { query, arguments: args = {}, auto_select = true } = req.body;
if (!query) {
return res.status(400).json({ error: 'Missing query' });
}
usageTracker.trackView('/api/v1/match-and-execute', req);
// Find best match
const hosted = hostedMcp.listHostedServers();
let bestMatch = null;
let bestScore = 0;
for (const server of hosted) {
const serverDetails = hostedMcp.getHostedServer(server.slug);
const { score } = calculateMatchScore(query, { ...server, type: 'hosted' }, serverDetails);
if (score > bestScore) {
bestScore = score;
bestMatch = { server, details: serverDetails };
}
}
if (!bestMatch || bestScore < 0.3) {
return res.json({
success: false,
error: 'No matching tool found',
query,
best_score: bestScore
});
}
// Execute the first tool of the best match
const toolName = bestMatch.details.tools[0]?.name;
if (!toolName) {
return res.json({
success: false,
error: 'No tools available on matched server',
matched_server: bestMatch.server.slug
});
}
try {
const result = await hostedMcp.executeTool(bestMatch.server.slug, toolName, args);
res.json({
success: true,
matched: {
server: bestMatch.server.slug,
tool: toolName,
score: bestScore,
confidence: getConfidence(bestScore)
},
result
});
} catch (e) {
res.json({
success: false,
error: e.message,
matched: {
server: bestMatch.server.slug,
tool: toolName
}
});
}
});
// Usage stats (protected)
app.get('/api/v1/hosted/stats', async (req, res) => {
// Simple auth - check admin key
const authKey = req.headers['authorization']?.replace('Bearer ', '') || req.query.key;
if (authKey !== ADMIN_KEY) {
return res.status(401).json({ error: 'Unauthorized. Provide admin key.' });
}
const inMemory = usageTracker.getStats();
const persisted = await usageTracker.getPersistedStats();
res.json({
inMemory,
persisted,
supabaseConfigured: usageTracker.isSupabaseConfigured(),
});
});
// Provision a hosted server (returns endpoint info)
app.get('/api/v1/provision/:slug', (req, res) => {
usageTracker.trackView(`/api/v1/provision/${req.params.slug}`, req);
const server = hostedMcp.getHostedServer(req.params.slug);
if (!server) {
return res.status(404).json({ error: 'Server not found. Use GET /api/v1/hosted to list available servers.' });
}
const baseUrl = `${req.protocol}://${req.get('host')}`;
res.json({
provisioned: true,
server: server.name,
description: server.description,
endpoints: {
list_tools: `${baseUrl}/mcp/${req.params.slug}/tools/list`,
call_tool: `${baseUrl}/mcp/${req.params.slug}/tools/call`
},
tools: server.tools,
usage: {
example: `curl -X POST ${baseUrl}/mcp/${req.params.slug}/tools/call -H "Content-Type: application/json" -d '{"name": "${server.tools[0]?.name || 'tool_name'}", "arguments": {}}'`
}
});
});
// MCP-style tool listing
app.get('/mcp/:slug/tools/list', (req, res) => {
const server = hostedMcp.getHostedServer(req.params.slug);
if (!server) {
return res.status(404).json({ error: 'Server not found' });
}
res.json({
tools: server.tools.map(t => ({
name: t.name,
description: t.description,
inputSchema: t.inputSchema
}))
});
});
// MCP-style tool execution
app.post('/mcp/:slug/tools/call', async (req, res) => {
const { name, arguments: args } = req.body;
if (!name) {
return res.status(400).json({ error: 'Missing "name" field for tool' });
}
// Track this call
usageTracker.trackCall(req.params.slug, name, req);
const result = await hostedMcp.executeTool(req.params.slug, name, args || {});
res.json({
tool: name,
result,
_server: req.params.slug
});
});
// === SEO Pages (Programmatic) ===
const seoPages = require('./lib/seo-pages');
// Individual server pages
app.get('/servers/:slug', (req, res) => {
const server = db.servers.getBySlug(req.params.slug);
if (!server) {
return res.status(404).send('Server not found. <a href="/">Browse all servers</a>');
}
// Track view
db.servers.incrementViews(server.id);
const html = seoPages.generateServerPage(server);
res.send(html);
});
// Category pages
app.get('/category/:slug', (req, res) => {
const categories = db.categories.getAll();
const category = categories.find(c => c.slug === req.params.slug);
if (!category && req.params.slug !== 'all') {
return res.status(404).send('Category not found. <a href="/">Browse all servers</a>');
}
const servers = category
? db.servers.getAll({ category: category.name, limit: 500 })
: db.servers.getAll({ limit: 500 });
const cat = category || { name: 'All', slug: 'all', icon: '📦' };
const html = seoPages.generateCategoryPage(cat, servers);
res.send(html);
});
// Status endpoint - transparency for reliability
app.get('/status', (req, res) => {
const startTime = Date.now();
// Check database
let dbStatus = 'ok';
try {
db.servers.getAll({ limit: 1 });
} catch (e) {
dbStatus = 'error';
}
// Check Supabase
const supabaseConfigured = usageTracker.isSupabaseConfigured();
res.json({
status: dbStatus === 'ok' ? 'operational' : 'degraded',
timestamp: new Date().toISOString(),
version: '1.0.0',
services: {
api: 'ok',
database: dbStatus,
persistence: supabaseConfigured ? 'ok' : 'not_configured',
},
hosted_servers: Object.keys(hostedMCP.HOSTED_SERVERS).length,
response_time_ms: Date.now() - startTime,
});
});
app.get('/api/v1/status', (req, res) => {
res.redirect('/status');
});
// === Mining Data API ===
// Mining tenement data - unified access across jurisdictions
// === Mining API Call Tracking ===
// Simple request logging (visible in Render logs)
function trackMiningCall(endpoint, req) {
const apiKey = req.headers['x-api-key'] || req.query.key || 'anonymous';
const userAgent = req.headers['user-agent'] || 'unknown';
const ip = req.headers['x-forwarded-for']?.split(',')[0] || req.ip || 'unknown';
// Log to stdout (captured by Render)
console.log(JSON.stringify({
type: 'mining_api_call',
endpoint,
api_key: apiKey.slice(0, 8) + '...',
user_agent: userAgent.slice(0, 50),