-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
190 lines (175 loc) · 5.25 KB
/
server.ts
File metadata and controls
190 lines (175 loc) · 5.25 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
// 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 {
CallToolRequestSchema,
ListToolsRequestSchema,
SetLevelRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { ClientOptions } from 'cas-parser-node';
import CasParser from 'cas-parser-node';
import { codeTool } from './code-tool';
import docsSearchTool from './docs-search-tool';
import { getInstructions } from './instructions';
import { McpOptions } from './options';
import { blockedMethodsForCodeTool } from './methods';
import { HandlerFunction, McpRequestContext, ToolCallResult, McpTool } from './types';
export const newMcpServer = async (stainlessApiKey: string | undefined) =>
new McpServer(
{
name: 'cas_parser_node_api',
version: '1.10.2',
},
{
instructions: await getInstructions(stainlessApiKey),
capabilities: { tools: {}, logging: {} },
},
);
/**
* Initializes the provided MCP Server with the given tools and handlers.
* If not provided, the default client, tools and handlers will be used.
*/
export async function initMcpServer(params: {
server: Server | McpServer;
clientOptions?: ClientOptions;
mcpOptions?: McpOptions;
stainlessApiKey?: string | undefined;
upstreamClientEnvs?: Record<string, string> | undefined;
}) {
const server = params.server instanceof McpServer ? params.server.server : params.server;
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: CasParser | undefined;
let _clientError: Error | undefined;
let _logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off' | undefined;
const getClient = (): CasParser => {
if (_clientError) throw _clientError;
if (!_client) {
try {
_client = new CasParser({
logger,
...params.clientOptions,
defaultHeaders: {
...params.clientOptions?.defaultHeaders,
'X-Stainless-MCP': 'true',
},
});
if (_logLevel) {
_client = _client.withOptions({ logLevel: _logLevel });
}
} catch (e) {
_clientError = e instanceof Error ? e : new Error(String(e));
throw _clientError;
}
}
return _client;
};
const providedTools = selectTools(params.mcpOptions);
const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool]));
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: providedTools.map((mcpTool) => mcpTool.tool),
};
});
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
const mcpTool = toolMap[name];
if (!mcpTool) {
throw new Error(`Unknown tool: ${name}`);
}
let client: CasParser;
try {
client = getClient();
} catch (error) {
return {
content: [
{
type: 'text' as const,
text: `Failed to initialize client: ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
};
}
return executeHandler({
handler: mcpTool.handler,
reqContext: {
client,
stainlessApiKey: params.stainlessApiKey ?? params.mcpOptions?.stainlessApiKey,
upstreamClientEnvs: params.upstreamClientEnvs,
},
args,
});
});
server.setRequestHandler(SetLevelRequestSchema, async (request) => {
const { level } = request.params;
let logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off';
switch (level) {
case 'debug':
logLevel = 'debug';
break;
case 'info':
logLevel = 'info';
break;
case 'notice':
case 'warning':
logLevel = 'warn';
break;
case 'error':
logLevel = 'error';
break;
default:
logLevel = 'off';
break;
}
_logLevel = logLevel;
if (_client) {
_client = _client.withOptions({ logLevel });
}
return {};
});
}
/**
* Selects the tools to include in the MCP Server based on the provided options.
*/
export function selectTools(options?: McpOptions): McpTool[] {
const includedTools = [];
if (options?.includeCodeTool ?? true) {
includedTools.push(
codeTool({
blockedMethods: blockedMethodsForCodeTool(options),
codeExecutionMode: options?.codeExecutionMode ?? 'stainless-sandbox',
}),
);
}
if (options?.includeDocsTools ?? true) {
includedTools.push(docsSearchTool);
}
return includedTools;
}
/**
* Runs the provided handler with the given client and arguments.
*/
export async function executeHandler({
handler,
reqContext,
args,
}: {
handler: HandlerFunction;
reqContext: McpRequestContext;
args: Record<string, unknown> | undefined;
}): Promise<ToolCallResult> {
return await handler({ reqContext, args: args || {} });
}