Repository navigation
Expand file tree
/
Copy pathmcp-wrapper.js
More file actions
152 lines (135 loc) · 4.3 KB
/
Copy pathmcp-wrapper.js
File metadata and controls
152 lines (135 loc) · 4.3 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
#!/usr/bin/env node
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { SERVER_IDENTITY, buildStructuredResult } from './src/toolMeta.js';
const API_KEY = process.env.SOCIALAPIS_API_KEY || process.argv[2];
const MCP_PROXY_URL = process.env.MCP_PROXY_URL || 'https://mcp.socialapis.io';
if (!API_KEY) {
console.error('Error: SOCIALAPIS_API_KEY environment variable or API key argument required');
console.error('Usage: socialapis-mcp <api-key>');
process.exit(1);
}
const server = new Server(
{
...SERVER_IDENTITY,
version: '2.2.0',
},
{
capabilities: {
// The tool list follows the live SocialAPIs catalog (prices,
// descriptions, parameters): re-fetched every 10 minutes, and clients
// are told when it changes. Tool and action names never change.
tools: { listChanged: true },
},
}
);
const TOOLS_REFRESH_MS = Number(process.env.SOCIALAPIS_CATALOG_REFRESH_MS) || 600_000;
// Fetch tools from server. null on failure (the caller keeps what it has).
async function getTools() {
try {
// format=full adds titles, annotations and outputSchema. This client
// returns structuredContent on success, which outputSchema requires.
const response = await fetch(`${MCP_PROXY_URL}/tools?format=full`, { signal: AbortSignal.timeout(10_000) });
const data = await response.json();
return Array.isArray(data?.tools) && data.tools.length ? data.tools : null;
} catch (error) {
console.error('Failed to fetch tools:', error);
return null;
}
}
let cachedTools = null;
let cachedAt = 0;
/** Re-fetch the list; true if it changed. Keeps the last good list on failure. */
async function refreshTools() {
const fresh = await getTools();
if (!fresh) return false;
const changed = cachedTools !== null && JSON.stringify(fresh) !== JSON.stringify(cachedTools);
cachedTools = fresh;
cachedAt = Date.now();
return changed;
}
function clientLabel() {
const info = server.getClientVersion();
return info?.name ? `${info.name}/${info.version || '?'} (npm 2.2.0)` : 'unknown (npm 2.2.0)';
}
server.setRequestHandler(ListToolsRequestSchema, async () => {
if (!cachedTools || Date.now() - cachedAt > TOOLS_REFRESH_MS) {
await refreshTools();
}
return { tools: cachedTools || [] };
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
try {
const response = await fetch(`${MCP_PROXY_URL}/proxy`, {
method: 'POST',
headers: {
'x-api-key': API_KEY,
'Content-Type': 'application/json',
// Lets the server's call log say which MCP client is in use.
'x-mcp-client': clientLabel(),
},
body: JSON.stringify({
tool: name,
arguments: args,
}),
});
const result = await response.json();
if (result.success) {
return {
content: [
{
type: 'text',
text: JSON.stringify(result.data, null, 2),
},
],
structuredContent: buildStructuredResult(result.data),
};
} else {
return {
content: [
{
type: 'text',
text: JSON.stringify(result.data || result, null, 2),
},
],
isError: true,
};
}
} catch (error) {
return {
content: [
{
type: 'text',
text: JSON.stringify({
error: error.message,
tool: name,
}),
},
],
isError: true,
};
}
});
async function main() {
const transport = new StdioServerTransport();
await server.connect(transport);
console.error('✅ SocialAPIs MCP Client running');
console.error(`🔑 Using API key: ${API_KEY.substring(0, 8)}...`);
console.error(`🌐 Proxy URL: ${MCP_PROXY_URL}`);
// Tell the client when prices, descriptions or parameters change.
const timer = setInterval(async () => {
if (cachedTools && (await refreshTools())) {
server.sendToolListChanged().catch(() => {});
}
}, TOOLS_REFRESH_MS);
timer.unref();
}
main().catch((error) => {
console.error('❌ Server error:', error);
process.exit(1);
});