-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
188 lines (165 loc) · 5.78 KB
/
server.js
File metadata and controls
188 lines (165 loc) · 5.78 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
#!/usr/bin/env node
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const { CallToolRequestSchema, ListToolsRequestSchema } = require('@modelcontextprotocol/sdk/types.js');
const { exec } = require('child_process');
const fs = require('fs');
const path = require('path');
class NPMMCPServer {
constructor() {
this.server = new Server(
{
name: 'npm-mcp-server',
version: '1.0.0',
},
{
capabilities: {
tools: {},
},
}
);
this.setupToolHandlers();
}
setupToolHandlers() {
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: 'install_npm_package',
description: 'Install an NPM package and generate MCP wrapper files',
inputSchema: {
type: 'object',
properties: {
packageName: {
type: 'string',
description: 'NPM package name to install',
},
},
required: ['packageName'],
},
},
{
name: 'list_installed_packages',
description: 'List all installed NPM packages with MCP wrappers',
inputSchema: {
type: 'object',
properties: {},
},
},
],
};
});
this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
switch (request.params.name) {
case 'install_npm_package':
return this.installPackage(request.params.arguments?.packageName);
case 'list_installed_packages':
return this.listPackages();
default:
throw new Error(`Unknown tool: ${request.params.name}`);
}
});
}
async installPackage(packageName) {
return new Promise((resolve, reject) => {
exec(`npm install ${packageName}`, (error, stdout, stderr) => {
if (error) {
reject(new Error(`Failed to install ${packageName}: ${error.message}`));
return;
}
try {
this.generateWrapperFiles(packageName);
resolve({
content: [
{
type: 'text',
text: `Successfully installed ${packageName} and generated wrapper files. Restart Claude Desktop to use new tools.`,
},
],
});
} catch (genError) {
reject(new Error(`Package installed but wrapper generation failed: ${genError.message}`));
}
});
});
}
generateWrapperFiles(packageName) {
try {
const pkg = require(packageName);
const exports = Object.keys(pkg).filter(key => typeof pkg[key] === 'function');
const chunkSize = 50;
const chunks = [];
for (let i = 0; i < exports.length; i += chunkSize) {
chunks.push(exports.slice(i, i + chunkSize));
}
chunks.forEach((chunk, index) => {
const fileName = chunks.length === 1
? `${packageName.replace(/[^a-zA-Z0-9]/g, '_')}.js`
: `${packageName.replace(/[^a-zA-Z0-9]/g, '_')}_${index + 1}.js`;
this.createWrapperFile(packageName, chunk, fileName);
});
} catch (error) {
throw new Error(`Failed to introspect package ${packageName}: ${error.message}`);
}
}
createWrapperFile(packageName, functionNames, fileName) {
const filePath = path.join(__dirname, 'wrappers', fileName);
if (!fs.existsSync(path.dirname(filePath))) {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
}
const tools = functionNames.map(fnName => {
return `{
name:'${packageName}_${fnName}',
description:'${packageName}.${fnName} function',
inputSchema:{type:'object',properties:{args:{type:'array',description:'Function arguments'}},required:['args']},
}`;
}).join(',');
const handlers = functionNames.map(fnName => {
return `case'${packageName}_${fnName}':return{content:[{type:'text',text:JSON.stringify(a.${fnName}(...(b.args||[])))}]};`;
}).join('');
const content = `const {Server}=require('@modelcontextprotocol/sdk/server/index.js');
const {StdioServerTransport}=require('@modelcontextprotocol/sdk/server/stdio.js');
const {CallToolRequestSchema,ListToolsRequestSchema}=require('@modelcontextprotocol/sdk/types.js');
const a=require('${packageName}');
const s=new Server({name:'${fileName}',version:'1.0.0'},{capabilities:{tools:{}}});
s.setRequestHandler(ListToolsRequestSchema,async()=>({tools:[${tools}]}));
s.setRequestHandler(CallToolRequestSchema,async r=>{const b=r.params.arguments||{};switch(r.params.name){${handlers}default:throw new Error('Unknown tool:'+r.params.name);}});
async function main(){const t=new StdioServerTransport();await s.connect(t);}
if(require.main===module){main().catch(console.error);}`;
fs.writeFileSync(filePath, content);
}
async listPackages() {
const wrappersDir = path.join(__dirname, 'wrappers');
if (!fs.existsSync(wrappersDir)) {
return {
content: [
{
type: 'text',
text: 'No packages installed yet.',
},
],
};
}
const files = fs.readdirSync(wrappersDir);
const packages = files.map(f => f.replace(/\.js$/, '').replace(/_\d+$/, '')).filter((v, i, a) => a.indexOf(v) === i);
return {
content: [
{
type: 'text',
text: `Installed packages: ${packages.join(', ')}`,
},
],
};
}
async run() {
const transport = new StdioServerTransport();
await this.server.connect(transport);
}
}
async function main() {
const server = new NPMMCPServer();
await server.run();
}
if (require.main === module) {
main().catch(console.error);
}