anyformat-mcp 0.1.3
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 +101 -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 +282 -0
- package/code-tool-worker.js.map +1 -0
- package/code-tool-worker.mjs +244 -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 +335 -0
- package/code-tool.js.map +1 -0
- package/code-tool.mjs +299 -0
- package/code-tool.mjs.map +1 -0
- package/docs-search-tool.d.mts +59 -0
- package/docs-search-tool.d.mts.map +1 -0
- package/docs-search-tool.d.ts +59 -0
- package/docs-search-tool.d.ts.map +1 -0
- package/docs-search-tool.js +104 -0
- package/docs-search-tool.js.map +1 -0
- package/docs-search-tool.mjs +99 -0
- package/docs-search-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 +61 -0
- package/instructions.js.map +1 -0
- package/instructions.mjs +55 -0
- package/instructions.mjs.map +1 -0
- package/local-docs-search.d.mts +28 -0
- package/local-docs-search.d.mts.map +1 -0
- package/local-docs-search.d.ts +28 -0
- package/local-docs-search.d.ts.map +1 -0
- package/local-docs-search.js +731 -0
- package/local-docs-search.js.map +1 -0
- package/local-docs-search.mjs +691 -0
- package/local-docs-search.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 +161 -0
- package/methods.js.map +1 -0
- package/methods.mjs +157 -0
- package/methods.mjs.map +1 -0
- package/options.d.mts +23 -0
- package/options.d.mts.map +1 -0
- package/options.d.ts +23 -0
- package/options.d.ts.map +1 -0
- package/options.js +141 -0
- package/options.js.map +1 -0
- package/options.mjs +134 -0
- package/options.mjs.map +1 -0
- package/package.json +235 -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 +168 -0
- package/server.js.map +1 -0
- package/server.mjs +158 -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 +295 -0
- package/src/code-tool.ts +389 -0
- package/src/docs-search-tool.ts +138 -0
- package/src/http.ts +227 -0
- package/src/index.ts +67 -0
- package/src/instructions.ts +83 -0
- package/src/local-docs-search.ts +831 -0
- package/src/logger.ts +28 -0
- package/src/methods.ts +182 -0
- package/src/options.ts +185 -0
- package/src/server.ts +208 -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
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
|
|
2
|
+
|
|
3
|
+
import { Tool } from '@modelcontextprotocol/sdk/types.js';
|
|
4
|
+
import { Metadata, McpRequestContext, asTextContentResult } from './types';
|
|
5
|
+
import { getLogger } from './logger';
|
|
6
|
+
import type { LocalDocsSearch } from './local-docs-search';
|
|
7
|
+
|
|
8
|
+
export const metadata: Metadata = {
|
|
9
|
+
resource: 'all',
|
|
10
|
+
operation: 'read',
|
|
11
|
+
tags: [],
|
|
12
|
+
httpMethod: 'get',
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export const tool: Tool = {
|
|
16
|
+
name: 'search_docs',
|
|
17
|
+
description:
|
|
18
|
+
'Search SDK documentation to find methods, parameters, and usage examples for interacting with the API. Use this before writing code when you need to discover the right approach.',
|
|
19
|
+
inputSchema: {
|
|
20
|
+
type: 'object',
|
|
21
|
+
properties: {
|
|
22
|
+
query: {
|
|
23
|
+
type: 'string',
|
|
24
|
+
description: 'The query to search for.',
|
|
25
|
+
},
|
|
26
|
+
language: {
|
|
27
|
+
type: 'string',
|
|
28
|
+
description: 'The language for the SDK to search for.',
|
|
29
|
+
enum: ['http', 'python', 'go', 'typescript', 'javascript', 'terraform', 'ruby', 'java', 'kotlin'],
|
|
30
|
+
},
|
|
31
|
+
detail: {
|
|
32
|
+
type: 'string',
|
|
33
|
+
description: 'The amount of detail to return.',
|
|
34
|
+
enum: ['default', 'verbose'],
|
|
35
|
+
},
|
|
36
|
+
},
|
|
37
|
+
required: ['query', 'language'],
|
|
38
|
+
},
|
|
39
|
+
annotations: {
|
|
40
|
+
readOnlyHint: true,
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const docsSearchURL =
|
|
45
|
+
process.env['DOCS_SEARCH_URL'] || 'https://api.stainless.com/api/projects/anyformat/docs/search';
|
|
46
|
+
|
|
47
|
+
let _localSearch: LocalDocsSearch | undefined;
|
|
48
|
+
|
|
49
|
+
export function setLocalSearch(search: LocalDocsSearch): void {
|
|
50
|
+
_localSearch = search;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
async function searchLocal(args: Record<string, unknown>): Promise<unknown> {
|
|
54
|
+
if (!_localSearch) {
|
|
55
|
+
throw new Error('Local search not initialized');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const query = (args['query'] as string) ?? '';
|
|
59
|
+
const language = (args['language'] as string) ?? 'typescript';
|
|
60
|
+
const detail = (args['detail'] as string) ?? 'default';
|
|
61
|
+
|
|
62
|
+
return _localSearch.search({
|
|
63
|
+
query,
|
|
64
|
+
language,
|
|
65
|
+
detail,
|
|
66
|
+
maxResults: 10,
|
|
67
|
+
}).results;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function searchRemote(args: Record<string, unknown>, reqContext: McpRequestContext): Promise<unknown> {
|
|
71
|
+
const body = args as any;
|
|
72
|
+
const query = new URLSearchParams(body).toString();
|
|
73
|
+
|
|
74
|
+
const startTime = Date.now();
|
|
75
|
+
const result = await fetch(`${docsSearchURL}?${query}`, {
|
|
76
|
+
headers: {
|
|
77
|
+
...(reqContext.stainlessApiKey && { Authorization: reqContext.stainlessApiKey }),
|
|
78
|
+
...(reqContext.mcpSessionId && { 'x-stainless-mcp-session-id': reqContext.mcpSessionId }),
|
|
79
|
+
...(reqContext.mcpClientInfo && {
|
|
80
|
+
'x-stainless-mcp-client-info': JSON.stringify(reqContext.mcpClientInfo),
|
|
81
|
+
}),
|
|
82
|
+
},
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
const logger = getLogger();
|
|
86
|
+
|
|
87
|
+
if (!result.ok) {
|
|
88
|
+
const errorText = await result.text();
|
|
89
|
+
logger.warn(
|
|
90
|
+
{
|
|
91
|
+
durationMs: Date.now() - startTime,
|
|
92
|
+
query: body.query,
|
|
93
|
+
status: result.status,
|
|
94
|
+
statusText: result.statusText,
|
|
95
|
+
errorText,
|
|
96
|
+
},
|
|
97
|
+
'Got error response from docs search tool',
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
if (result.status === 404 && !reqContext.stainlessApiKey) {
|
|
101
|
+
throw new Error(
|
|
102
|
+
'Could not find docs for this project. You may need to provide a Stainless API key via the STAINLESS_API_KEY environment variable, the --stainless-api-key flag, or the x-stainless-api-key HTTP header.',
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
throw new Error(
|
|
107
|
+
`${result.status}: ${result.statusText} when using doc search tool. Details: ${errorText}`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const resultBody = await result.json();
|
|
112
|
+
logger.info(
|
|
113
|
+
{
|
|
114
|
+
durationMs: Date.now() - startTime,
|
|
115
|
+
query: body.query,
|
|
116
|
+
},
|
|
117
|
+
'Got docs search result',
|
|
118
|
+
);
|
|
119
|
+
return resultBody;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export const handler = async ({
|
|
123
|
+
reqContext,
|
|
124
|
+
args,
|
|
125
|
+
}: {
|
|
126
|
+
reqContext: McpRequestContext;
|
|
127
|
+
args: Record<string, unknown> | undefined;
|
|
128
|
+
}) => {
|
|
129
|
+
const body = args ?? {};
|
|
130
|
+
|
|
131
|
+
if (_localSearch) {
|
|
132
|
+
return asTextContentResult(await searchLocal(body));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
return asTextContentResult(await searchRemote(body, reqContext));
|
|
136
|
+
};
|
|
137
|
+
|
|
138
|
+
export default { metadata, tool, handler };
|
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 'anyformat-ai';
|
|
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,83 @@
|
|
|
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
|
+
import { readEnv } from './util';
|
|
6
|
+
|
|
7
|
+
const INSTRUCTIONS_CACHE_TTL_MS = 15 * 60 * 1000; // 15 minutes
|
|
8
|
+
|
|
9
|
+
interface InstructionsCacheEntry {
|
|
10
|
+
fetchedInstructions: string;
|
|
11
|
+
fetchedAt: number;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const instructionsCache = new Map<string, InstructionsCacheEntry>();
|
|
15
|
+
|
|
16
|
+
export async function getInstructions({
|
|
17
|
+
stainlessApiKey,
|
|
18
|
+
customInstructionsPath,
|
|
19
|
+
}: {
|
|
20
|
+
stainlessApiKey?: string | undefined;
|
|
21
|
+
customInstructionsPath?: string | undefined;
|
|
22
|
+
}): Promise<string> {
|
|
23
|
+
const now = Date.now();
|
|
24
|
+
const cacheKey = customInstructionsPath ?? stainlessApiKey ?? '';
|
|
25
|
+
const cached = instructionsCache.get(cacheKey);
|
|
26
|
+
|
|
27
|
+
if (cached && now - cached.fetchedAt <= INSTRUCTIONS_CACHE_TTL_MS) {
|
|
28
|
+
return cached.fetchedInstructions;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Evict stale entries so the cache doesn't grow unboundedly.
|
|
32
|
+
for (const [key, entry] of instructionsCache) {
|
|
33
|
+
if (now - entry.fetchedAt > INSTRUCTIONS_CACHE_TTL_MS) {
|
|
34
|
+
instructionsCache.delete(key);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
let fetchedInstructions: string;
|
|
39
|
+
|
|
40
|
+
if (customInstructionsPath) {
|
|
41
|
+
fetchedInstructions = await fetchLatestInstructionsFromFile(customInstructionsPath);
|
|
42
|
+
} else {
|
|
43
|
+
fetchedInstructions = await fetchLatestInstructionsFromApi(stainlessApiKey);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
instructionsCache.set(cacheKey, { fetchedInstructions, fetchedAt: now });
|
|
47
|
+
return fetchedInstructions;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function fetchLatestInstructionsFromFile(path: string): Promise<string> {
|
|
51
|
+
try {
|
|
52
|
+
return await fs.readFile(path, 'utf-8');
|
|
53
|
+
} catch (error) {
|
|
54
|
+
getLogger().error({ error, path }, 'Error fetching instructions from file');
|
|
55
|
+
throw error;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
async function fetchLatestInstructionsFromApi(stainlessApiKey: string | undefined): Promise<string> {
|
|
60
|
+
// Setting the stainless API key is optional, but may be required
|
|
61
|
+
// to authenticate requests to the Stainless API.
|
|
62
|
+
const response = await fetch(
|
|
63
|
+
readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/anyformat',
|
|
64
|
+
{
|
|
65
|
+
method: 'GET',
|
|
66
|
+
headers: { ...(stainlessApiKey && { Authorization: stainlessApiKey }) },
|
|
67
|
+
},
|
|
68
|
+
);
|
|
69
|
+
|
|
70
|
+
let instructions: string | undefined;
|
|
71
|
+
if (!response.ok) {
|
|
72
|
+
getLogger().warn(
|
|
73
|
+
'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...',
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
instructions =
|
|
77
|
+
'\n This is the anyformat 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 ';
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
instructions ??= ((await response.json()) as { instructions: string }).instructions;
|
|
81
|
+
|
|
82
|
+
return instructions;
|
|
83
|
+
}
|