-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathserver.ts
More file actions
207 lines (188 loc) · 6.33 KB
/
server.ts
File metadata and controls
207 lines (188 loc) · 6.33 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
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { Endpoint, endpoints, HandlerFunction, query } from './tools';
import {
CallToolRequestSchema,
ListToolsRequestSchema,
SetLevelRequestSchema,
Implementation,
Tool,
} from '@modelcontextprotocol/sdk/types.js';
import { ClientOptions } from '@imagekit/nodejs';
import ImageKit from '@imagekit/nodejs';
import {
applyCompatibilityTransformations,
ClientCapabilities,
defaultClientCapabilities,
knownClients,
parseEmbeddedJSON,
} from './compat';
import { dynamicTools } from './dynamic-tools';
import { codeTool } from './code-tool';
import docsSearchTool from './docs-search-tool';
import { McpOptions } from './options';
export { McpOptions } from './options';
export { ClientType } from './compat';
export { Filter } from './tools';
export { ClientOptions } from '@imagekit/nodejs';
export { endpoints } from './tools';
export const newMcpServer = () =>
new McpServer(
{
name: 'imagekit_nodejs_api',
version: '7.1.1',
},
{ capabilities: { tools: {}, logging: {} } },
);
// Create server instance
export const server = newMcpServer();
/**
* Initializes the provided MCP Server with the given tools and handlers.
* If not provided, the default client, tools and handlers will be used.
*/
export function initMcpServer(params: {
server: Server | McpServer;
clientOptions?: ClientOptions;
mcpOptions?: McpOptions;
}) {
const server = params.server instanceof McpServer ? params.server.server : params.server;
const mcpOptions = params.mcpOptions ?? {};
let providedEndpoints: Endpoint[] | null = null;
let endpointMap: Record<string, Endpoint> | null = null;
const initTools = async (implementation?: Implementation) => {
if (implementation && (!mcpOptions.client || mcpOptions.client === 'infer')) {
mcpOptions.client =
implementation.name.toLowerCase().includes('claude') ? 'claude'
: implementation.name.toLowerCase().includes('cursor') ? 'cursor'
: undefined;
mcpOptions.capabilities = {
...(mcpOptions.client && knownClients[mcpOptions.client]),
...mcpOptions.capabilities,
};
}
providedEndpoints ??= await selectTools(endpoints, mcpOptions);
endpointMap ??= Object.fromEntries(providedEndpoints.map((endpoint) => [endpoint.tool.name, endpoint]));
};
const logAtLevel =
(level: 'debug' | 'info' | 'warning' | 'error') =>
(message: string, ...rest: unknown[]) => {
void server.sendLoggingMessage({
level,
data: { message, rest },
});
};
const logger = {
debug: logAtLevel('debug'),
info: logAtLevel('info'),
warn: logAtLevel('warning'),
error: logAtLevel('error'),
};
let client = new ImageKit({
logger,
...params.clientOptions,
defaultHeaders: {
...params.clientOptions?.defaultHeaders,
'X-Stainless-MCP': 'true',
},
});
server.setRequestHandler(ListToolsRequestSchema, async () => {
if (providedEndpoints === null) {
await initTools(server.getClientVersion());
}
return {
tools: providedEndpoints!.map((endpoint) => endpoint.tool),
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (endpointMap === null) {
await initTools(server.getClientVersion());
}
const { name, arguments: args } = request.params;
const endpoint = endpointMap![name];
if (!endpoint) {
throw new Error(`Unknown tool: ${name}`);
}
return executeHandler(endpoint.tool, endpoint.handler, client, args, mcpOptions.capabilities);
});
server.setRequestHandler(SetLevelRequestSchema, async (request) => {
const { level } = request.params;
switch (level) {
case 'debug':
client = client.withOptions({ logLevel: 'debug' });
break;
case 'info':
client = client.withOptions({ logLevel: 'info' });
break;
case 'notice':
case 'warning':
client = client.withOptions({ logLevel: 'warn' });
break;
case 'error':
client = client.withOptions({ logLevel: 'error' });
break;
default:
client = client.withOptions({ logLevel: 'off' });
break;
}
return {};
});
}
/**
* Selects the tools to include in the MCP Server based on the provided options.
*/
export async function selectTools(endpoints: Endpoint[], options?: McpOptions): Promise<Endpoint[]> {
const filteredEndpoints = query(options?.filters ?? [], endpoints);
let includedTools = filteredEndpoints.slice();
if (includedTools.length > 0) {
if (options?.includeDynamicTools) {
includedTools = dynamicTools(includedTools);
}
} else {
if (options?.includeAllTools) {
includedTools = endpoints.slice();
} else if (options?.includeDynamicTools) {
includedTools = dynamicTools(endpoints);
} else if (options?.includeCodeTools) {
includedTools = [await codeTool()];
} else {
includedTools = endpoints.slice();
}
}
if (options?.includeDocsTools ?? true) {
includedTools.push(docsSearchTool);
}
const capabilities = { ...defaultClientCapabilities, ...options?.capabilities };
return applyCompatibilityTransformations(includedTools, capabilities);
}
/**
* Runs the provided handler with the given client and arguments.
*/
export async function executeHandler(
tool: Tool,
handler: HandlerFunction,
client: ImageKit,
args: Record<string, unknown> | undefined,
compatibilityOptions?: Partial<ClientCapabilities>,
) {
const options = { ...defaultClientCapabilities, ...compatibilityOptions };
if (!options.validJson && args) {
args = parseEmbeddedJSON(args, tool.inputSchema);
}
return await handler(client, args || {});
}
export const readEnv = (env: string): string | undefined => {
if (typeof (globalThis as any).process !== 'undefined') {
return (globalThis as any).process.env?.[env]?.trim();
} else if (typeof (globalThis as any).Deno !== 'undefined') {
return (globalThis as any).Deno.env?.get?.(env)?.trim();
}
return;
};
export const readEnvOrError = (env: string): string => {
let envValue = readEnv(env);
if (envValue === undefined) {
throw new Error(`Environment variable ${env} is not set`);
}
return envValue;
};