@augno/sdk-mcp 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +103 -0
- package/auth.d.mts +6 -0
- package/auth.d.mts.map +1 -0
- package/auth.d.ts +6 -0
- package/auth.d.ts.map +1 -0
- package/auth.js +37 -0
- package/auth.js.map +1 -0
- package/auth.mjs +32 -0
- package/auth.mjs.map +1 -0
- package/code-tool-paths.cjs +8 -0
- package/code-tool-paths.cjs.map +1 -0
- package/code-tool-paths.d.cts +2 -0
- package/code-tool-paths.d.cts.map +1 -0
- package/code-tool-types.d.mts +14 -0
- package/code-tool-types.d.mts.map +1 -0
- package/code-tool-types.d.ts +14 -0
- package/code-tool-types.d.ts.map +1 -0
- package/code-tool-types.js +4 -0
- package/code-tool-types.js.map +1 -0
- package/code-tool-types.mjs +3 -0
- package/code-tool-types.mjs.map +1 -0
- package/code-tool-worker.d.mts +5 -0
- package/code-tool-worker.d.mts.map +1 -0
- package/code-tool-worker.d.ts +5 -0
- package/code-tool-worker.d.ts.map +1 -0
- package/code-tool-worker.js +486 -0
- package/code-tool-worker.js.map +1 -0
- package/code-tool-worker.mjs +448 -0
- package/code-tool-worker.mjs.map +1 -0
- package/code-tool.d.mts +21 -0
- package/code-tool.d.mts.map +1 -0
- package/code-tool.d.ts +21 -0
- package/code-tool.d.ts.map +1 -0
- package/code-tool.js +287 -0
- package/code-tool.js.map +1 -0
- package/code-tool.mjs +251 -0
- package/code-tool.mjs.map +1 -0
- package/http.d.mts +12 -0
- package/http.d.mts.map +1 -0
- package/http.d.ts +12 -0
- package/http.d.ts.map +1 -0
- package/http.js +190 -0
- package/http.js.map +1 -0
- package/http.mjs +182 -0
- package/http.mjs.map +1 -0
- package/index.d.mts +3 -0
- package/index.d.mts.map +1 -0
- package/index.d.ts +3 -0
- package/index.d.ts.map +1 -0
- package/index.js +60 -0
- package/index.js.map +1 -0
- package/index.mjs +58 -0
- package/index.mjs.map +1 -0
- package/instructions.d.mts +5 -0
- package/instructions.d.mts.map +1 -0
- package/instructions.d.ts +5 -0
- package/instructions.d.ts.map +1 -0
- package/instructions.js +47 -0
- package/instructions.js.map +1 -0
- package/instructions.mjs +41 -0
- package/instructions.mjs.map +1 -0
- package/logger.d.mts +7 -0
- package/logger.d.mts.map +1 -0
- package/logger.d.ts +7 -0
- package/logger.d.ts.map +1 -0
- package/logger.js +29 -0
- package/logger.js.map +1 -0
- package/logger.mjs +22 -0
- package/logger.mjs.map +1 -0
- package/methods.d.mts +10 -0
- package/methods.d.mts.map +1 -0
- package/methods.d.ts +10 -0
- package/methods.d.ts.map +1 -0
- package/methods.js +1385 -0
- package/methods.js.map +1 -0
- package/methods.mjs +1381 -0
- package/methods.mjs.map +1 -0
- package/options.d.mts +20 -0
- package/options.d.mts.map +1 -0
- package/options.d.ts +20 -0
- package/options.d.ts.map +1 -0
- package/options.js +121 -0
- package/options.js.map +1 -0
- package/options.mjs +114 -0
- package/options.mjs.map +1 -0
- package/package.json +216 -0
- package/server.d.mts +38 -0
- package/server.d.mts.map +1 -0
- package/server.d.ts +38 -0
- package/server.d.ts.map +1 -0
- package/server.js +162 -0
- package/server.js.map +1 -0
- package/server.mjs +152 -0
- package/server.mjs.map +1 -0
- package/src/auth.ts +42 -0
- package/src/code-tool-paths.cts +5 -0
- package/src/code-tool-types.ts +17 -0
- package/src/code-tool-worker.ts +499 -0
- package/src/code-tool.ts +316 -0
- package/src/http.ts +227 -0
- package/src/index.ts +67 -0
- package/src/instructions.ts +59 -0
- package/src/logger.ts +28 -0
- package/src/methods.ts +1406 -0
- package/src/options.ts +159 -0
- package/src/server.ts +202 -0
- package/src/stdio.ts +17 -0
- package/src/tsconfig.json +11 -0
- package/src/types.ts +126 -0
- package/src/util.ts +25 -0
- package/stdio.d.mts +3 -0
- package/stdio.d.mts.map +1 -0
- package/stdio.d.ts +3 -0
- package/stdio.d.ts.map +1 -0
- package/stdio.js +18 -0
- package/stdio.js.map +1 -0
- package/stdio.mjs +14 -0
- package/stdio.mjs.map +1 -0
- package/types.d.mts +65 -0
- package/types.d.mts.map +1 -0
- package/types.d.ts +65 -0
- package/types.d.ts.map +1 -0
- package/types.js +58 -0
- package/types.js.map +1 -0
- package/types.mjs +53 -0
- package/types.mjs.map +1 -0
- package/util.d.mts +4 -0
- package/util.d.mts.map +1 -0
- package/util.d.ts +4 -0
- package/util.d.ts.map +1 -0
- package/util.js +30 -0
- package/util.js.map +1 -0
- package/util.mjs +24 -0
- package/util.mjs.map +1 -0
package/src/code-tool.ts
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
|
+
|
|
3
|
+
import { ContentBlock, McpRequestContext, McpTool, Metadata, ToolCallResult, asErrorResult } from './types';
|
|
4
|
+
import { Tool } from '@modelcontextprotocol/sdk/types.js';
|
|
5
|
+
import { WorkerOutput } from './code-tool-types';
|
|
6
|
+
import { getLogger } from './logger';
|
|
7
|
+
import { SdkMethod } from './methods';
|
|
8
|
+
import { McpCodeExecutionMode } from './options';
|
|
9
|
+
import { ClientOptions } from '@augno/sdk';
|
|
10
|
+
|
|
11
|
+
const prompt = `Runs JavaScript code to interact with the Augno API.
|
|
12
|
+
|
|
13
|
+
You are a skilled TypeScript programmer writing code to interface with the service.
|
|
14
|
+
Define an async function named "run" that takes a single parameter of an initialized SDK client and it will be run.
|
|
15
|
+
For example:
|
|
16
|
+
|
|
17
|
+
\`\`\`
|
|
18
|
+
async function run(client) {
|
|
19
|
+
const listItem = await client.catalog.items.list();
|
|
20
|
+
|
|
21
|
+
console.log(listItem.data);
|
|
22
|
+
}
|
|
23
|
+
\`\`\`
|
|
24
|
+
|
|
25
|
+
You will be returned anything that your function returns, plus the results of any console.log statements.
|
|
26
|
+
Do not add try-catch blocks for single API calls. The tool will handle errors for you.
|
|
27
|
+
Do not add comments unless necessary for generating better code.
|
|
28
|
+
Code will run in a container, and cannot interact with the network outside of the given SDK client.
|
|
29
|
+
Variables will not persist between calls, so make sure to return or log any data you might need later.
|
|
30
|
+
Remember that you are writing TypeScript code, so you need to be careful with your types.
|
|
31
|
+
Always type dynamic key-value stores explicitly as Record<string, YourValueType> instead of {}.`;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* A tool that runs code against a copy of the SDK.
|
|
35
|
+
*
|
|
36
|
+
* Instead of exposing every endpoint as its own tool, which uses up too many tokens for LLMs to use at once,
|
|
37
|
+
* we expose a single tool that can be used to search for endpoints by name, resource, operation, or tag, and then
|
|
38
|
+
* a generic endpoint that can be used to invoke any endpoint with the provided arguments.
|
|
39
|
+
*
|
|
40
|
+
* @param blockedMethods - The methods to block for code execution. Blocking is done by simple string
|
|
41
|
+
* matching, so it is not secure against obfuscation. For stronger security, block in the downstream API
|
|
42
|
+
* with limited API keys.
|
|
43
|
+
* @param codeExecutionMode - Whether to execute code in a local Deno environment or in a remote
|
|
44
|
+
* sandbox environment hosted by Stainless.
|
|
45
|
+
*/
|
|
46
|
+
export function codeTool({
|
|
47
|
+
blockedMethods,
|
|
48
|
+
codeExecutionMode,
|
|
49
|
+
}: {
|
|
50
|
+
blockedMethods: SdkMethod[] | undefined;
|
|
51
|
+
codeExecutionMode: McpCodeExecutionMode;
|
|
52
|
+
}): McpTool {
|
|
53
|
+
const metadata: Metadata = { resource: 'all', operation: 'write', tags: [] };
|
|
54
|
+
const tool: Tool = {
|
|
55
|
+
name: 'execute',
|
|
56
|
+
description: prompt,
|
|
57
|
+
inputSchema: {
|
|
58
|
+
type: 'object',
|
|
59
|
+
properties: {
|
|
60
|
+
code: {
|
|
61
|
+
type: 'string',
|
|
62
|
+
description: 'Code to execute.',
|
|
63
|
+
},
|
|
64
|
+
intent: {
|
|
65
|
+
type: 'string',
|
|
66
|
+
description: 'Task you are trying to perform. Used for improving the service.',
|
|
67
|
+
},
|
|
68
|
+
},
|
|
69
|
+
required: ['code'],
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const logger = getLogger();
|
|
74
|
+
|
|
75
|
+
const handler = async ({
|
|
76
|
+
reqContext,
|
|
77
|
+
args,
|
|
78
|
+
}: {
|
|
79
|
+
reqContext: McpRequestContext;
|
|
80
|
+
args: any;
|
|
81
|
+
}): Promise<ToolCallResult> => {
|
|
82
|
+
const code = args.code as string;
|
|
83
|
+
// Do very basic blocking of code that includes forbidden method names.
|
|
84
|
+
//
|
|
85
|
+
// WARNING: This is not secure against obfuscation and other evasion methods. If
|
|
86
|
+
// stronger security blocks are required, then these should be enforced in the downstream
|
|
87
|
+
// API (e.g., by having users call the MCP server with API keys with limited permissions).
|
|
88
|
+
if (blockedMethods) {
|
|
89
|
+
const blockedMatches = blockedMethods.filter((method) => code.includes(method.fullyQualifiedName));
|
|
90
|
+
if (blockedMatches.length > 0) {
|
|
91
|
+
return asErrorResult(
|
|
92
|
+
`The following methods have been blocked by the MCP server and cannot be used in code execution: ${blockedMatches
|
|
93
|
+
.map((m) => m.fullyQualifiedName)
|
|
94
|
+
.join(', ')}`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
let result: ToolCallResult;
|
|
100
|
+
const startTime = Date.now();
|
|
101
|
+
|
|
102
|
+
logger.debug('Executing code in local Deno environment');
|
|
103
|
+
result = await localDenoHandler({ reqContext, args });
|
|
104
|
+
|
|
105
|
+
logger.info(
|
|
106
|
+
{
|
|
107
|
+
codeExecutionMode,
|
|
108
|
+
durationMs: Date.now() - startTime,
|
|
109
|
+
isError: result.isError,
|
|
110
|
+
contentRows: result.content?.length ?? 0,
|
|
111
|
+
},
|
|
112
|
+
'Got code tool execution result',
|
|
113
|
+
);
|
|
114
|
+
return result;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
return { metadata, tool, handler };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const localDenoHandler = async ({
|
|
121
|
+
reqContext,
|
|
122
|
+
args,
|
|
123
|
+
}: {
|
|
124
|
+
reqContext: McpRequestContext;
|
|
125
|
+
args: unknown;
|
|
126
|
+
}): Promise<ToolCallResult> => {
|
|
127
|
+
const fs = await import('node:fs');
|
|
128
|
+
const path = await import('node:path');
|
|
129
|
+
const url = await import('node:url');
|
|
130
|
+
const { newDenoHTTPWorker } = await import('@valtown/deno-http-worker');
|
|
131
|
+
const { getWorkerPath } = await import('./code-tool-paths.cjs');
|
|
132
|
+
const workerPath = getWorkerPath();
|
|
133
|
+
|
|
134
|
+
const client = reqContext.client;
|
|
135
|
+
const baseURLHostname = new URL(client.baseURL).hostname;
|
|
136
|
+
const { code } = args as { code: string };
|
|
137
|
+
|
|
138
|
+
let denoPath: string;
|
|
139
|
+
|
|
140
|
+
const packageRoot = path.resolve(path.dirname(workerPath), '..');
|
|
141
|
+
const packageNodeModulesPath = path.resolve(packageRoot, 'node_modules');
|
|
142
|
+
|
|
143
|
+
// Check if deno is in PATH
|
|
144
|
+
const { execSync } = await import('node:child_process');
|
|
145
|
+
try {
|
|
146
|
+
execSync('command -v deno', { stdio: 'ignore' });
|
|
147
|
+
denoPath = 'deno';
|
|
148
|
+
} catch {
|
|
149
|
+
try {
|
|
150
|
+
// Use deno binary in node_modules if it's found
|
|
151
|
+
const denoNodeModulesPath = path.resolve(packageNodeModulesPath, 'deno', 'bin.cjs');
|
|
152
|
+
await fs.promises.access(denoNodeModulesPath, fs.constants.X_OK);
|
|
153
|
+
denoPath = denoNodeModulesPath;
|
|
154
|
+
} catch {
|
|
155
|
+
return asErrorResult(
|
|
156
|
+
'Deno is required for code execution but was not found. ' +
|
|
157
|
+
'Install it from https://deno.land or run: npm install deno',
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
const allowReadPaths = [
|
|
163
|
+
'code-tool-worker.mjs',
|
|
164
|
+
`${workerPath.replace(/([\/\\]node_modules)[\/\\].+$/, '$1')}/`,
|
|
165
|
+
packageRoot,
|
|
166
|
+
];
|
|
167
|
+
|
|
168
|
+
// Follow symlinks in node_modules to allow read access to workspace-linked packages
|
|
169
|
+
try {
|
|
170
|
+
const sdkPkgName = '@augno/sdk';
|
|
171
|
+
const sdkDir = path.resolve(packageNodeModulesPath, sdkPkgName);
|
|
172
|
+
const realSdkDir = fs.realpathSync(sdkDir);
|
|
173
|
+
if (realSdkDir !== sdkDir) {
|
|
174
|
+
allowReadPaths.push(realSdkDir);
|
|
175
|
+
}
|
|
176
|
+
} catch {
|
|
177
|
+
// Ignore if symlink resolution fails
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const allowRead = allowReadPaths.join(',');
|
|
181
|
+
|
|
182
|
+
const worker = await newDenoHTTPWorker(url.pathToFileURL(workerPath), {
|
|
183
|
+
denoExecutable: denoPath,
|
|
184
|
+
runFlags: [
|
|
185
|
+
`--node-modules-dir=manual`,
|
|
186
|
+
`--allow-read=${allowRead}`,
|
|
187
|
+
`--allow-net=${baseURLHostname}`,
|
|
188
|
+
// Allow environment variables because instantiating the client will try to read from them,
|
|
189
|
+
// even though they are not set.
|
|
190
|
+
'--allow-env',
|
|
191
|
+
],
|
|
192
|
+
printOutput: true,
|
|
193
|
+
spawnOptions: {
|
|
194
|
+
cwd: path.dirname(workerPath),
|
|
195
|
+
// Merge any upstream client envs into the Deno subprocess environment,
|
|
196
|
+
// with the upstream env vars taking precedence.
|
|
197
|
+
env: { ...process.env, ...reqContext.upstreamClientEnvs },
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
try {
|
|
202
|
+
const resp = await new Promise<Response>((resolve, reject) => {
|
|
203
|
+
worker.addEventListener('exit', (exitCode) => {
|
|
204
|
+
reject(new Error(`Worker exited with code ${exitCode}`));
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
// Strip null/undefined values so that the worker SDK client can fall back to
|
|
208
|
+
// reading from environment variables (including any upstreamClientEnvs).
|
|
209
|
+
const opts = {
|
|
210
|
+
...(client.baseURL != null ? { baseURL: client.baseURL } : undefined),
|
|
211
|
+
...(client.bearerToken != null ? { bearerToken: client.bearerToken } : undefined),
|
|
212
|
+
...(client.augnoAccountID != null ? { augnoAccountID: client.augnoAccountID } : undefined),
|
|
213
|
+
defaultHeaders: {
|
|
214
|
+
'X-Stainless-MCP': 'true',
|
|
215
|
+
},
|
|
216
|
+
} satisfies Partial<ClientOptions> as ClientOptions;
|
|
217
|
+
|
|
218
|
+
const req = worker.request(
|
|
219
|
+
'http://localhost',
|
|
220
|
+
{
|
|
221
|
+
headers: {
|
|
222
|
+
'content-type': 'application/json',
|
|
223
|
+
},
|
|
224
|
+
method: 'POST',
|
|
225
|
+
},
|
|
226
|
+
(resp) => {
|
|
227
|
+
const body: Uint8Array[] = [];
|
|
228
|
+
resp.on('error', (err) => {
|
|
229
|
+
reject(err);
|
|
230
|
+
});
|
|
231
|
+
resp.on('data', (chunk) => {
|
|
232
|
+
body.push(chunk);
|
|
233
|
+
});
|
|
234
|
+
resp.on('end', () => {
|
|
235
|
+
resolve(
|
|
236
|
+
new Response(Buffer.concat(body).toString(), {
|
|
237
|
+
status: resp.statusCode ?? 200,
|
|
238
|
+
headers: resp.headers as any,
|
|
239
|
+
}),
|
|
240
|
+
);
|
|
241
|
+
});
|
|
242
|
+
},
|
|
243
|
+
);
|
|
244
|
+
|
|
245
|
+
const body = JSON.stringify({
|
|
246
|
+
opts,
|
|
247
|
+
code,
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
req.write(body, (err) => {
|
|
251
|
+
if (err != null) {
|
|
252
|
+
reject(err);
|
|
253
|
+
}
|
|
254
|
+
});
|
|
255
|
+
|
|
256
|
+
req.end();
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
if (resp.status === 200) {
|
|
260
|
+
const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
|
|
261
|
+
const returnOutput: ContentBlock | null =
|
|
262
|
+
result == null ? null : (
|
|
263
|
+
{
|
|
264
|
+
type: 'text',
|
|
265
|
+
text: typeof result === 'string' ? result : JSON.stringify(result),
|
|
266
|
+
}
|
|
267
|
+
);
|
|
268
|
+
const logOutput: ContentBlock | null =
|
|
269
|
+
log_lines.length === 0 ?
|
|
270
|
+
null
|
|
271
|
+
: {
|
|
272
|
+
type: 'text',
|
|
273
|
+
text: log_lines.join('\n'),
|
|
274
|
+
};
|
|
275
|
+
const errOutput: ContentBlock | null =
|
|
276
|
+
err_lines.length === 0 ?
|
|
277
|
+
null
|
|
278
|
+
: {
|
|
279
|
+
type: 'text',
|
|
280
|
+
text: 'Error output:\n' + err_lines.join('\n'),
|
|
281
|
+
};
|
|
282
|
+
return {
|
|
283
|
+
content: [returnOutput, logOutput, errOutput].filter((block) => block !== null),
|
|
284
|
+
};
|
|
285
|
+
} else {
|
|
286
|
+
const { result, log_lines, err_lines } = (await resp.json()) as WorkerOutput;
|
|
287
|
+
const messageOutput: ContentBlock | null =
|
|
288
|
+
result == null ? null : (
|
|
289
|
+
{
|
|
290
|
+
type: 'text',
|
|
291
|
+
text: typeof result === 'string' ? result : JSON.stringify(result),
|
|
292
|
+
}
|
|
293
|
+
);
|
|
294
|
+
const logOutput: ContentBlock | null =
|
|
295
|
+
log_lines.length === 0 ?
|
|
296
|
+
null
|
|
297
|
+
: {
|
|
298
|
+
type: 'text',
|
|
299
|
+
text: log_lines.join('\n'),
|
|
300
|
+
};
|
|
301
|
+
const errOutput: ContentBlock | null =
|
|
302
|
+
err_lines.length === 0 ?
|
|
303
|
+
null
|
|
304
|
+
: {
|
|
305
|
+
type: 'text',
|
|
306
|
+
text: 'Error output:\n' + err_lines.join('\n'),
|
|
307
|
+
};
|
|
308
|
+
return {
|
|
309
|
+
content: [messageOutput, logOutput, errOutput].filter((block) => block !== null),
|
|
310
|
+
isError: true,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
} finally {
|
|
314
|
+
worker.terminate();
|
|
315
|
+
}
|
|
316
|
+
};
|
package/src/http.ts
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
|
+
|
|
3
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
|
4
|
+
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
5
|
+
import { ClientOptions } from '@augno/sdk';
|
|
6
|
+
import express from 'express';
|
|
7
|
+
import pino from 'pino';
|
|
8
|
+
import pinoHttp from 'pino-http';
|
|
9
|
+
import { getStainlessApiKey, parseClientAuthHeaders } from './auth';
|
|
10
|
+
import { getLogger } from './logger';
|
|
11
|
+
import { McpOptions } from './options';
|
|
12
|
+
import { initMcpServer, newMcpServer } from './server';
|
|
13
|
+
|
|
14
|
+
const newServer = async ({
|
|
15
|
+
clientOptions,
|
|
16
|
+
mcpOptions,
|
|
17
|
+
req,
|
|
18
|
+
res,
|
|
19
|
+
}: {
|
|
20
|
+
clientOptions: ClientOptions;
|
|
21
|
+
mcpOptions: McpOptions;
|
|
22
|
+
req: express.Request;
|
|
23
|
+
res: express.Response;
|
|
24
|
+
}): Promise<McpServer | null> => {
|
|
25
|
+
const stainlessApiKey = getStainlessApiKey(req, mcpOptions);
|
|
26
|
+
const customInstructionsPath = mcpOptions.customInstructionsPath;
|
|
27
|
+
const server = await newMcpServer({ stainlessApiKey, customInstructionsPath });
|
|
28
|
+
|
|
29
|
+
const authOptions = parseClientAuthHeaders(req, false);
|
|
30
|
+
|
|
31
|
+
let upstreamClientEnvs: Record<string, string> | undefined;
|
|
32
|
+
const clientEnvsHeader = req.headers['x-stainless-mcp-client-envs'];
|
|
33
|
+
if (typeof clientEnvsHeader === 'string') {
|
|
34
|
+
try {
|
|
35
|
+
const parsed = JSON.parse(clientEnvsHeader);
|
|
36
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
37
|
+
upstreamClientEnvs = parsed;
|
|
38
|
+
}
|
|
39
|
+
} catch {
|
|
40
|
+
// Ignore malformed header
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Parse x-stainless-mcp-client-permissions header to override permission options
|
|
45
|
+
//
|
|
46
|
+
// Note: Permissions are best-effort and intended to prevent clients from doing unexpected things;
|
|
47
|
+
// they're not a hard security boundary, so we allow arbitrary, client-driven overrides.
|
|
48
|
+
//
|
|
49
|
+
// See the Stainless MCP documentation for more details.
|
|
50
|
+
let effectiveMcpOptions = mcpOptions;
|
|
51
|
+
const clientPermissionsHeader = req.headers['x-stainless-mcp-client-permissions'];
|
|
52
|
+
if (typeof clientPermissionsHeader === 'string') {
|
|
53
|
+
try {
|
|
54
|
+
const parsed = JSON.parse(clientPermissionsHeader);
|
|
55
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
56
|
+
effectiveMcpOptions = {
|
|
57
|
+
...mcpOptions,
|
|
58
|
+
...(typeof parsed.allow_http_gets === 'boolean' && { codeAllowHttpGets: parsed.allow_http_gets }),
|
|
59
|
+
...(Array.isArray(parsed.allowed_methods) && { codeAllowedMethods: parsed.allowed_methods }),
|
|
60
|
+
...(Array.isArray(parsed.blocked_methods) && { codeBlockedMethods: parsed.blocked_methods }),
|
|
61
|
+
};
|
|
62
|
+
getLogger().info(
|
|
63
|
+
{ clientPermissions: parsed },
|
|
64
|
+
'Overriding code execution permissions from x-stainless-mcp-client-permissions header',
|
|
65
|
+
);
|
|
66
|
+
}
|
|
67
|
+
} catch (error) {
|
|
68
|
+
getLogger().warn({ error }, 'Failed to parse x-stainless-mcp-client-permissions header');
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const mcpClientInfo =
|
|
73
|
+
typeof req.body?.params?.clientInfo?.name === 'string' ?
|
|
74
|
+
{ name: req.body.params.clientInfo.name, version: String(req.body.params.clientInfo.version ?? '') }
|
|
75
|
+
: undefined;
|
|
76
|
+
|
|
77
|
+
await initMcpServer({
|
|
78
|
+
server: server,
|
|
79
|
+
mcpOptions: effectiveMcpOptions,
|
|
80
|
+
clientOptions: {
|
|
81
|
+
...clientOptions,
|
|
82
|
+
...authOptions,
|
|
83
|
+
},
|
|
84
|
+
stainlessApiKey: stainlessApiKey,
|
|
85
|
+
upstreamClientEnvs,
|
|
86
|
+
mcpSessionId: (req as any).mcpSessionId,
|
|
87
|
+
mcpClientInfo,
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
if (mcpClientInfo) {
|
|
91
|
+
getLogger().info({ mcpSessionId: (req as any).mcpSessionId, mcpClientInfo }, 'MCP client connected');
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return server;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
const post =
|
|
98
|
+
(options: { clientOptions: ClientOptions; mcpOptions: McpOptions }) =>
|
|
99
|
+
async (req: express.Request, res: express.Response) => {
|
|
100
|
+
const server = await newServer({ ...options, req, res });
|
|
101
|
+
// If we return null, we already set the authorization error.
|
|
102
|
+
if (server === null) return;
|
|
103
|
+
const transport = new StreamableHTTPServerTransport();
|
|
104
|
+
await server.connect(transport as any);
|
|
105
|
+
await transport.handleRequest(req, res, req.body);
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
const get = async (req: express.Request, res: express.Response) => {
|
|
109
|
+
res.status(405).json({
|
|
110
|
+
jsonrpc: '2.0',
|
|
111
|
+
error: {
|
|
112
|
+
code: -32000,
|
|
113
|
+
message: 'Method not supported',
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const del = async (req: express.Request, res: express.Response) => {
|
|
119
|
+
res.status(405).json({
|
|
120
|
+
jsonrpc: '2.0',
|
|
121
|
+
error: {
|
|
122
|
+
code: -32000,
|
|
123
|
+
message: 'Method not supported',
|
|
124
|
+
},
|
|
125
|
+
});
|
|
126
|
+
};
|
|
127
|
+
|
|
128
|
+
const redactHeaders = (headers: Record<string, any>) => {
|
|
129
|
+
const hiddenHeaders = /auth|cookie|key|token|x-stainless-mcp-client-envs/i;
|
|
130
|
+
const filtered = { ...headers };
|
|
131
|
+
Object.keys(filtered).forEach((key) => {
|
|
132
|
+
if (hiddenHeaders.test(key)) {
|
|
133
|
+
filtered[key] = '[REDACTED]';
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
return filtered;
|
|
137
|
+
};
|
|
138
|
+
|
|
139
|
+
export const streamableHTTPApp = ({
|
|
140
|
+
clientOptions = {},
|
|
141
|
+
mcpOptions,
|
|
142
|
+
}: {
|
|
143
|
+
clientOptions?: ClientOptions;
|
|
144
|
+
mcpOptions: McpOptions;
|
|
145
|
+
}): express.Express => {
|
|
146
|
+
const app = express();
|
|
147
|
+
app.set('query parser', 'extended');
|
|
148
|
+
app.use(express.json());
|
|
149
|
+
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
|
|
150
|
+
const existing = req.headers['mcp-session-id'];
|
|
151
|
+
const sessionId = (Array.isArray(existing) ? existing[0] : existing) || crypto.randomUUID();
|
|
152
|
+
(req as any).mcpSessionId = sessionId;
|
|
153
|
+
const origWriteHead = res.writeHead.bind(res);
|
|
154
|
+
res.writeHead = function (statusCode: number, ...rest: any[]) {
|
|
155
|
+
res.setHeader('mcp-session-id', sessionId);
|
|
156
|
+
return origWriteHead(statusCode, ...rest);
|
|
157
|
+
} as typeof res.writeHead;
|
|
158
|
+
next();
|
|
159
|
+
});
|
|
160
|
+
app.use(
|
|
161
|
+
pinoHttp({
|
|
162
|
+
logger: getLogger(),
|
|
163
|
+
customProps: (req) => ({
|
|
164
|
+
mcpSessionId: (req as any).mcpSessionId,
|
|
165
|
+
}),
|
|
166
|
+
customLogLevel: (req, res) => {
|
|
167
|
+
if (res.statusCode >= 500) {
|
|
168
|
+
return 'error';
|
|
169
|
+
} else if (res.statusCode >= 400) {
|
|
170
|
+
return 'warn';
|
|
171
|
+
}
|
|
172
|
+
return 'info';
|
|
173
|
+
},
|
|
174
|
+
customSuccessMessage: function (req, res) {
|
|
175
|
+
return `Request ${req.method} to ${req.url} completed with status ${res.statusCode}`;
|
|
176
|
+
},
|
|
177
|
+
customErrorMessage: function (req, res, err) {
|
|
178
|
+
return `Request ${req.method} to ${req.url} errored with status ${res.statusCode}`;
|
|
179
|
+
},
|
|
180
|
+
serializers: {
|
|
181
|
+
req: pino.stdSerializers.wrapRequestSerializer((req) => {
|
|
182
|
+
return {
|
|
183
|
+
...req,
|
|
184
|
+
headers: redactHeaders(req.raw.headers),
|
|
185
|
+
};
|
|
186
|
+
}),
|
|
187
|
+
res: pino.stdSerializers.wrapResponseSerializer((res) => {
|
|
188
|
+
return {
|
|
189
|
+
...res,
|
|
190
|
+
headers: redactHeaders(res.headers),
|
|
191
|
+
};
|
|
192
|
+
}),
|
|
193
|
+
},
|
|
194
|
+
}),
|
|
195
|
+
);
|
|
196
|
+
|
|
197
|
+
app.get('/health', async (req: express.Request, res: express.Response) => {
|
|
198
|
+
res.status(200).send('OK');
|
|
199
|
+
});
|
|
200
|
+
app.get('/', get);
|
|
201
|
+
app.post('/', post({ clientOptions, mcpOptions }));
|
|
202
|
+
app.delete('/', del);
|
|
203
|
+
|
|
204
|
+
return app;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
export const launchStreamableHTTPServer = async ({
|
|
208
|
+
mcpOptions,
|
|
209
|
+
port,
|
|
210
|
+
}: {
|
|
211
|
+
mcpOptions: McpOptions;
|
|
212
|
+
port: number | string | undefined;
|
|
213
|
+
}) => {
|
|
214
|
+
const app = streamableHTTPApp({ mcpOptions });
|
|
215
|
+
const server = app.listen(port);
|
|
216
|
+
const address = server.address();
|
|
217
|
+
|
|
218
|
+
const logger = getLogger();
|
|
219
|
+
|
|
220
|
+
if (typeof address === 'string') {
|
|
221
|
+
logger.info(`MCP Server running on streamable HTTP at ${address}`);
|
|
222
|
+
} else if (address !== null) {
|
|
223
|
+
logger.info(`MCP Server running on streamable HTTP on port ${address.port}`);
|
|
224
|
+
} else {
|
|
225
|
+
logger.info(`MCP Server running on streamable HTTP on port ${port}`);
|
|
226
|
+
}
|
|
227
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { selectTools } from './server';
|
|
4
|
+
import { McpOptions, parseCLIOptions } from './options';
|
|
5
|
+
import { launchStdioServer } from './stdio';
|
|
6
|
+
import { launchStreamableHTTPServer } from './http';
|
|
7
|
+
import type { McpTool } from './types';
|
|
8
|
+
import { configureLogger, getLogger } from './logger';
|
|
9
|
+
|
|
10
|
+
async function main() {
|
|
11
|
+
const options = parseOptionsOrError();
|
|
12
|
+
configureLogger({
|
|
13
|
+
level: options.debug ? 'debug' : 'info',
|
|
14
|
+
pretty: options.logFormat === 'pretty',
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
const selectedTools = await selectToolsOrError(options);
|
|
18
|
+
|
|
19
|
+
getLogger().info(
|
|
20
|
+
{ tools: selectedTools.map((e) => e.tool.name) },
|
|
21
|
+
`MCP Server starting with ${selectedTools.length} tools`,
|
|
22
|
+
);
|
|
23
|
+
|
|
24
|
+
switch (options.transport) {
|
|
25
|
+
case 'stdio':
|
|
26
|
+
await launchStdioServer(options);
|
|
27
|
+
break;
|
|
28
|
+
case 'http':
|
|
29
|
+
await launchStreamableHTTPServer({
|
|
30
|
+
mcpOptions: options,
|
|
31
|
+
port: options.socket ?? options.port,
|
|
32
|
+
});
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
if (require.main === module) {
|
|
38
|
+
main().catch((error) => {
|
|
39
|
+
// Logger might not be initialized yet
|
|
40
|
+
console.error('Fatal error in main()', error);
|
|
41
|
+
process.exit(1);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parseOptionsOrError() {
|
|
46
|
+
try {
|
|
47
|
+
return parseCLIOptions();
|
|
48
|
+
} catch (error) {
|
|
49
|
+
// Logger is initialized after options, so use console.error here
|
|
50
|
+
console.error('Error parsing options', error);
|
|
51
|
+
process.exit(1);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function selectToolsOrError(options: McpOptions): Promise<McpTool[]> {
|
|
56
|
+
try {
|
|
57
|
+
const includedTools = selectTools(options);
|
|
58
|
+
if (includedTools.length === 0) {
|
|
59
|
+
getLogger().error('No tools match the provided filters');
|
|
60
|
+
process.exit(1);
|
|
61
|
+
}
|
|
62
|
+
return includedTools;
|
|
63
|
+
} catch (error) {
|
|
64
|
+
getLogger().error({ error }, 'Error filtering tools');
|
|
65
|
+
process.exit(1);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
|
+
|
|
3
|
+
import fs from 'fs/promises';
|
|
4
|
+
import { getLogger } from './logger';
|
|
5
|
+
|
|
6
|
+
const INSTRUCTIONS_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes
|
|
7
|
+
|
|
8
|
+
interface InstructionsCacheEntry {
|
|
9
|
+
fetchedInstructions: string;
|
|
10
|
+
fetchedAt: number;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
const instructionsCache = new Map<string, InstructionsCacheEntry>();
|
|
14
|
+
|
|
15
|
+
export async function getInstructions({
|
|
16
|
+
stainlessApiKey,
|
|
17
|
+
customInstructionsPath,
|
|
18
|
+
}: {
|
|
19
|
+
stainlessApiKey?: string | undefined;
|
|
20
|
+
customInstructionsPath?: string | undefined;
|
|
21
|
+
}): Promise<string> {
|
|
22
|
+
const now = Date.now();
|
|
23
|
+
const cacheKey = customInstructionsPath ?? stainlessApiKey ?? '';
|
|
24
|
+
const cached = instructionsCache.get(cacheKey);
|
|
25
|
+
|
|
26
|
+
if (cached && now - cached.fetchedAt <= INSTRUCTIONS_CACHE_TTL_MS) {
|
|
27
|
+
return cached.fetchedInstructions;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Evict stale entries so the cache doesn't grow unboundedly.
|
|
31
|
+
for (const [key, entry] of instructionsCache) {
|
|
32
|
+
if (now - entry.fetchedAt > INSTRUCTIONS_CACHE_TTL_MS) {
|
|
33
|
+
instructionsCache.delete(key);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
let fetchedInstructions: string;
|
|
38
|
+
|
|
39
|
+
if (customInstructionsPath) {
|
|
40
|
+
fetchedInstructions = await fetchLatestInstructionsFromFile(customInstructionsPath);
|
|
41
|
+
} else {
|
|
42
|
+
fetchedInstructions =
|
|
43
|
+
'\n This is the augno MCP server.\n\n Available tools:\n - search_docs: Search SDK documentation to find the right methods and parameters.\n - execute: Run TypeScript code against a pre-authenticated SDK client. Define an async run(client) function.\n\n Workflow:\n - If unsure about the API, call search_docs first.\n - Write complete solutions in a single execute call when possible. For large datasets, use API filters to narrow results or paginate within a single execute block.\n - If execute returns an error, read the error and fix your code rather than retrying the same approach.\n - Variables do not persist between execute calls. Return or log all data you need.\n - Individual HTTP requests to the API have a 30-second timeout. If a request times out, try a smaller query or add filters.\n - Code execution has a total timeout of approximately 5 minutes. If your code times out, simplify it or break it into smaller steps.\n ';
|
|
44
|
+
fetchedInstructions +=
|
|
45
|
+
'\nThis MCP server wraps the Augno API (production management for SMB\nmanufacturers). Use the code tool to call the API by writing TypeScript\nagainst the Augno SDK. Authenticate with an Augno API key as a Bearer\ntoken; set the active account with the Augno-Account header when\noperating across multiple accounts.\n';
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
instructionsCache.set(cacheKey, { fetchedInstructions, fetchedAt: now });
|
|
49
|
+
return fetchedInstructions;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function fetchLatestInstructionsFromFile(path: string): Promise<string> {
|
|
53
|
+
try {
|
|
54
|
+
return await fs.readFile(path, 'utf-8');
|
|
55
|
+
} catch (error) {
|
|
56
|
+
getLogger().error({ error, path }, 'Error fetching instructions from file');
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/logger.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
|
+
|
|
3
|
+
import { pino, type Level, type Logger } from 'pino';
|
|
4
|
+
import pretty from 'pino-pretty';
|
|
5
|
+
|
|
6
|
+
let _logger: Logger | undefined;
|
|
7
|
+
|
|
8
|
+
export function configureLogger({ level, pretty: usePretty }: { level: Level; pretty: boolean }): void {
|
|
9
|
+
_logger = pino(
|
|
10
|
+
{
|
|
11
|
+
level,
|
|
12
|
+
timestamp: pino.stdTimeFunctions.isoTime,
|
|
13
|
+
formatters: {
|
|
14
|
+
level(label) {
|
|
15
|
+
return { level: label };
|
|
16
|
+
},
|
|
17
|
+
},
|
|
18
|
+
},
|
|
19
|
+
usePretty ? pretty({ colorize: true, levelFirst: true, destination: 2 }) : process.stderr,
|
|
20
|
+
);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function getLogger(): Logger {
|
|
24
|
+
if (!_logger) {
|
|
25
|
+
throw new Error('Logger has not been configured. Call configureLogger() before using the logger.');
|
|
26
|
+
}
|
|
27
|
+
return _logger;
|
|
28
|
+
}
|