const express = require('express');
const helmet = require('helmet');
const randomUseragent = require('random-useragent');
const fetch = require('node-fetch');
const wasmModule = require('./pkg/your_wasm_module');
const OpenAI = require ('openai');
const { BedrockRuntimeClient } = require("@aws-sdk/client-bedrock-runtime");
const { GoogleGenerativeAI } = require("@google/generative-ai");
const axios = require('axios');
const { McpServer, ResourceTemplate } = require("McpServer");
const { StdioServerTransport } = require("McpServer");
const { z } = require('zod');
const rateLimit = require('express-rate-limit');
main
const app = express();
app.use(express.json());
const PORT = process.env.PORT || 3000;
const verifyNostrIdentity = (req) => {
const didHeader = req.headers['x-did'];
const signatureHeader = req.headers['x-signature'];
if (!didHeader || !signatureHeader) return { valid: false, error: "Missing DID or Signature headers" };
try {
const pubkey = wasmModule.JsNostrPublicKey.from_hex(didHeader.replace('did:nostr:', ''));
const signature = wasmModule.JsNostrSignature.from_hex(signatureHeader);
const canonical = wasmModule.JsRequestCanonicalizer.canonicalize(
req.method,
req.path,
Object.entries(req.headers),
JSON.stringify(req.body)
);
return wasmModule.JsNostrVerifier.verify(pubkey, canonical, signature);
} catch (e) {
return { valid: false, error: e.message };
}
};
const server = new McpServer({
name: "Demo",
version: "1.0.0"
});
server.tool("add",
{ a: z.number(), b: z.number() },
async ({ a, b }) => ({
content: [{ type: "text", text: String(a + b) }]
})
);
server.resource(
"greeting",
new ResourceTemplate("greeting://{name}", { list: undefined }),
async (uri, { name }) => ({
contents: [{
uri: uri.href,
text: `Hello, ${name}!`
}]
})
);
(async () => {
const transport = new StdioServerTransport();
await server.connect(transport);
})();
app.use(helmet());
const jsonRpcLimiter = rateLimit({
windowMs: 15 * 60 * 1000, max: 100, message: { jsonrpc: '2.0', error: { code: -32009, message: 'Too many requests' } },
standardHeaders: true, legacyHeaders: false, });
app.get('/api/ai', async (req, res) => {
try {
const userAgent = randomUseragent.getRandom();
const aiApiUrl = 'https://api.x.ai/v1'; const MoonshootAPI= 'https://api.moonshot.ai/v1';
const apiXai = 'https://api.x.ai/v1';
const apiOpenai = 'https://api.openai.com/v1';
const QwenAPI = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
const Claude = 'https://claude.ai/api/';
const ollama = 'http://localhost:11434/api/generate';
const stabilityClient = new wasmModule.HttpClient("your-stability-ai-api-key");
const imageBase64 = stabilityClient.generate_image_sync("A serene landscape", 512, 512, 50);
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const inputData = { message: "Hello from WASM!" };
const processedData = wasmModule.process_message(JSON.stringify(inputData));
const Prompt = {
prompt: 'prompt text'
}
const response = await fetch(aiApiUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'User-Agent': userAgent,
},
body: processedData,
});
if (!response.ok) {
throw new Error(`API responded with status ${response.status}`);
}
const apiData = await response.json();
res.json(apiData);
} catch (error) {
console.error('Error calling AI API:', error);
res.status(500).json({ error: 'Failed to fetch data from AI API' });
}
});
const agentCard = {
name: "PrivacyServerJS",
description: "Privacy-focused HTTP server with A2A support",
url: "http://localhost:3000",
version: "1.0.0",
capabilities: {
streaming: false,
pushNotifications: false,
stateTransitionHistory: false
}
};
app.get('/.well-known/agent.json', (req, res) => {
res.json(agentCard);
});
app.post('/', jsonRpcLimiter, (req, res) => {
const { jsonrpc, id, method, params } = req.body;
const identity = verifyNostrIdentity(req);
if (!identity.valid && process.env.REQUIRE_DID === 'true') {
return res.status(401).json({ jsonrpc: '2.0', error: { code: -32000, message: 'Unauthorized: Invalid DID Signature' }, id });
}
if (jsonrpc !== '2.0' || !id || !method || !params) {
return res.status(400).json({ jsonrpc: '2.0', error: { code: -32600, message: 'Invalid Request' }, id });
}
if (method === 'tasks/send') {
const { message } = params;
const text = message?.parts?.[0]?.text || 'No text provided';
const response = {
jsonrpc: '2.0',
id,
result: {
id: params.id || 'task-' + Date.now(),
status: { state: 'completed', timestamp: new Date().toISOString() },
artifacts: [{ parts: [{ type: 'text', text: `Processed: ${text} (Verified DID: ${identity.did?.to_string() || 'None'})` }], index: 0 }]
}
};
return res.json(response);
}
res.status(400).json({ jsonrpc: '2.0', error: { code: -32601, message: 'Method not found' }, id });
});
app.get('/', (req, res) => {
res.json({ message: 'Privacy-focused HTTP server with A2A support' });
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});