-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
193 lines (160 loc) · 5.85 KB
/
server.js
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
import { logRPC } from './src/logging.js';
import { fetchResource } from './src/utils.js';
import { ResponseFormats } from './src/response-formats.js';
import { PROTOCOL_VERSION, RPC_ERROR_CODES } from './src/constants.js';
/**
* Class representing a MCP server
* @param {Object} infos - The server infos { name, version }
* @param {Object} prompts - The server prompts
* @param {Object} resources - The server resources
* @param {Object} tools - The server tools
* @returns {MCP} - A new MCP server instance
*/
export class MCP {
constructor(infos, prompts, resources, tools) {
this.infos = infos;
this.tools = tools;
this.prompts = prompts;
this.resources = resources;
this.isConnected = false;
this.buffer = '';
this.initializeServer();
}
initializeServer() {
process.stdin.setEncoding('utf8');
process.stdin.on('data', this.handleInput.bind(this));
process.on('SIGTERM', this.handleTermination.bind(this));
}
async handleInput(chunk) {
this.buffer += chunk;
let newlineIndex;
while ((newlineIndex = this.buffer.indexOf('\n')) !== -1) {
const line = this.buffer.slice(0, newlineIndex);
this.buffer = this.buffer.slice(newlineIndex + 1);
if (line.trim()) await this.processRequest(line);
}
}
createResponse(id, result) {
return ResponseFormats.jsonRPC(id, result);
}
createErrorResponse(id, code, message, data) {
return ResponseFormats.error(id, code, message, data);
}
async processRequest(line) {
try {
const request = JSON.parse(line);
await logRPC('request', request);
const response = await this.handleMethod(request);
if (request.id !== undefined) {
await logRPC('response', response);
process.stdout.write(JSON.stringify(response) + '\n');
}
} catch (error) {
const errorResponse = this.createErrorResponse(null, RPC_ERROR_CODES.PARSE_ERROR, 'Parse error', error.message);
await logRPC('error', errorResponse);
process.stdout.write(JSON.stringify(errorResponse) + '\n');
}
}
async handleMethod(request) {
const { method, params, id } = request;
const methodHandlers = {
initialize: () => this.handleInitialize(params),
shutdown: () => this.handleShutdown(),
exit: () => this.handleExit(),
'tools/list': () => this.handleToolsList(),
'tools/call': () => this.handleToolsCall(params),
'notifications/cancelled': () => this.handleNotificationsCancelled(),
'notifications/initialized': () => this.handleNotificationsInitialized(),
'ping': () => this.handlePing(),
'prompts/list': () => this.handlePromptsList(),
'prompts/get': () => this.handlePromptsGet(params),
'resources/list': () => this.handleResourcesList(),
'resources/read': () => this.handleResourcesRead(params),
'resources/templates/list': () => this.handleResourcesTemplatesList()
};
const handler = methodHandlers[method];
if (!handler) {
return this.createErrorResponse(id, RPC_ERROR_CODES.METHOD_NOT_FOUND, 'Method not found');
}
return this.createResponse(id, await handler());
}
handlePing() {
return {};
}
handleShutdown() {
this.isConnected = false;
return null;
}
handleExit() {
process.exit(0);
}
handleNotificationsCancelled() {
return null;
}
handleNotificationsInitialized() {
return null;
}
handleResourcesList() {
return ResponseFormats.resources.list(Object.entries(this.resources));
}
async handleResourcesRead(params) {
const { uri } = params;
const resource = Object.values(this.resources).find(r => r.uri === uri);
if (!resource) {
throw new Error('Resource not found');
}
if (uri.startsWith('http')) {
try {
const { content, mimeType } = await fetchResource(uri);
return ResponseFormats.resources.read({
...resource,
mimeType,
content
});
} catch (error) {
throw new Error(`Failed to fetch resource: ${error.message}`);
}
}
return ResponseFormats.resources.read(resource);
}
handleResourcesTemplatesList() {
return ResponseFormats.resources.templates();
}
handlePromptsList() {
return ResponseFormats.prompts.list(Object.entries(this.prompts));
}
handlePromptsGet(params) {
const { name } = params;
const prompt = this.prompts[name];
if (!prompt) {
throw new Error('Prompt not found');
}
return ResponseFormats.prompts.get(prompt);
}
handleInitialize(params) {
if (params?.protocolVersion !== PROTOCOL_VERSION) {
throw new Error('Protocol version not supported');
}
this.isConnected = true;
process.stdin.resume();
return ResponseFormats.initialize(PROTOCOL_VERSION, this.infos);
}
async handleTermination() {
if (this.isConnected) {
await logRPC('info', { message: 'Server shutting down' });
}
process.exit(0);
}
async handleToolsList() {
return ResponseFormats.tools.list(Object.entries(this.tools));
}
async handleToolsCall(params) {
const { name, arguments: args } = params;
const tool = this.tools[name];
if (!tool) {
throw new Error('Tool not found');
}
const result = await tool.handler(args);
return ResponseFormats.tools.call(result);
}
}