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.
Files changed (153) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +101 -0
  3. package/auth.d.mts +6 -0
  4. package/auth.d.mts.map +1 -0
  5. package/auth.d.ts +6 -0
  6. package/auth.d.ts.map +1 -0
  7. package/auth.js +37 -0
  8. package/auth.js.map +1 -0
  9. package/auth.mjs +32 -0
  10. package/auth.mjs.map +1 -0
  11. package/code-tool-paths.cjs +8 -0
  12. package/code-tool-paths.cjs.map +1 -0
  13. package/code-tool-paths.d.cts +2 -0
  14. package/code-tool-paths.d.cts.map +1 -0
  15. package/code-tool-types.d.mts +14 -0
  16. package/code-tool-types.d.mts.map +1 -0
  17. package/code-tool-types.d.ts +14 -0
  18. package/code-tool-types.d.ts.map +1 -0
  19. package/code-tool-types.js +4 -0
  20. package/code-tool-types.js.map +1 -0
  21. package/code-tool-types.mjs +3 -0
  22. package/code-tool-types.mjs.map +1 -0
  23. package/code-tool-worker.d.mts +5 -0
  24. package/code-tool-worker.d.mts.map +1 -0
  25. package/code-tool-worker.d.ts +5 -0
  26. package/code-tool-worker.d.ts.map +1 -0
  27. package/code-tool-worker.js +282 -0
  28. package/code-tool-worker.js.map +1 -0
  29. package/code-tool-worker.mjs +244 -0
  30. package/code-tool-worker.mjs.map +1 -0
  31. package/code-tool.d.mts +21 -0
  32. package/code-tool.d.mts.map +1 -0
  33. package/code-tool.d.ts +21 -0
  34. package/code-tool.d.ts.map +1 -0
  35. package/code-tool.js +335 -0
  36. package/code-tool.js.map +1 -0
  37. package/code-tool.mjs +299 -0
  38. package/code-tool.mjs.map +1 -0
  39. package/docs-search-tool.d.mts +59 -0
  40. package/docs-search-tool.d.mts.map +1 -0
  41. package/docs-search-tool.d.ts +59 -0
  42. package/docs-search-tool.d.ts.map +1 -0
  43. package/docs-search-tool.js +104 -0
  44. package/docs-search-tool.js.map +1 -0
  45. package/docs-search-tool.mjs +99 -0
  46. package/docs-search-tool.mjs.map +1 -0
  47. package/http.d.mts +12 -0
  48. package/http.d.mts.map +1 -0
  49. package/http.d.ts +12 -0
  50. package/http.d.ts.map +1 -0
  51. package/http.js +190 -0
  52. package/http.js.map +1 -0
  53. package/http.mjs +182 -0
  54. package/http.mjs.map +1 -0
  55. package/index.d.mts +3 -0
  56. package/index.d.mts.map +1 -0
  57. package/index.d.ts +3 -0
  58. package/index.d.ts.map +1 -0
  59. package/index.js +60 -0
  60. package/index.js.map +1 -0
  61. package/index.mjs +58 -0
  62. package/index.mjs.map +1 -0
  63. package/instructions.d.mts +5 -0
  64. package/instructions.d.mts.map +1 -0
  65. package/instructions.d.ts +5 -0
  66. package/instructions.d.ts.map +1 -0
  67. package/instructions.js +61 -0
  68. package/instructions.js.map +1 -0
  69. package/instructions.mjs +55 -0
  70. package/instructions.mjs.map +1 -0
  71. package/local-docs-search.d.mts +28 -0
  72. package/local-docs-search.d.mts.map +1 -0
  73. package/local-docs-search.d.ts +28 -0
  74. package/local-docs-search.d.ts.map +1 -0
  75. package/local-docs-search.js +731 -0
  76. package/local-docs-search.js.map +1 -0
  77. package/local-docs-search.mjs +691 -0
  78. package/local-docs-search.mjs.map +1 -0
  79. package/logger.d.mts +7 -0
  80. package/logger.d.mts.map +1 -0
  81. package/logger.d.ts +7 -0
  82. package/logger.d.ts.map +1 -0
  83. package/logger.js +29 -0
  84. package/logger.js.map +1 -0
  85. package/logger.mjs +22 -0
  86. package/logger.mjs.map +1 -0
  87. package/methods.d.mts +10 -0
  88. package/methods.d.mts.map +1 -0
  89. package/methods.d.ts +10 -0
  90. package/methods.d.ts.map +1 -0
  91. package/methods.js +161 -0
  92. package/methods.js.map +1 -0
  93. package/methods.mjs +157 -0
  94. package/methods.mjs.map +1 -0
  95. package/options.d.mts +23 -0
  96. package/options.d.mts.map +1 -0
  97. package/options.d.ts +23 -0
  98. package/options.d.ts.map +1 -0
  99. package/options.js +141 -0
  100. package/options.js.map +1 -0
  101. package/options.mjs +134 -0
  102. package/options.mjs.map +1 -0
  103. package/package.json +235 -0
  104. package/server.d.mts +38 -0
  105. package/server.d.mts.map +1 -0
  106. package/server.d.ts +38 -0
  107. package/server.d.ts.map +1 -0
  108. package/server.js +168 -0
  109. package/server.js.map +1 -0
  110. package/server.mjs +158 -0
  111. package/server.mjs.map +1 -0
  112. package/src/auth.ts +42 -0
  113. package/src/code-tool-paths.cts +5 -0
  114. package/src/code-tool-types.ts +17 -0
  115. package/src/code-tool-worker.ts +295 -0
  116. package/src/code-tool.ts +389 -0
  117. package/src/docs-search-tool.ts +138 -0
  118. package/src/http.ts +227 -0
  119. package/src/index.ts +67 -0
  120. package/src/instructions.ts +83 -0
  121. package/src/local-docs-search.ts +831 -0
  122. package/src/logger.ts +28 -0
  123. package/src/methods.ts +182 -0
  124. package/src/options.ts +185 -0
  125. package/src/server.ts +208 -0
  126. package/src/stdio.ts +17 -0
  127. package/src/tsconfig.json +11 -0
  128. package/src/types.ts +126 -0
  129. package/src/util.ts +25 -0
  130. package/stdio.d.mts +3 -0
  131. package/stdio.d.mts.map +1 -0
  132. package/stdio.d.ts +3 -0
  133. package/stdio.d.ts.map +1 -0
  134. package/stdio.js +18 -0
  135. package/stdio.js.map +1 -0
  136. package/stdio.mjs +14 -0
  137. package/stdio.mjs.map +1 -0
  138. package/types.d.mts +65 -0
  139. package/types.d.mts.map +1 -0
  140. package/types.d.ts +65 -0
  141. package/types.d.ts.map +1 -0
  142. package/types.js +58 -0
  143. package/types.js.map +1 -0
  144. package/types.mjs +53 -0
  145. package/types.mjs.map +1 -0
  146. package/util.d.mts +4 -0
  147. package/util.d.mts.map +1 -0
  148. package/util.d.ts +4 -0
  149. package/util.d.ts.map +1 -0
  150. package/util.js +30 -0
  151. package/util.js.map +1 -0
  152. package/util.mjs +24 -0
  153. package/util.mjs.map +1 -0
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
+ }
package/src/methods.ts ADDED
@@ -0,0 +1,182 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import { McpOptions } from './options';
4
+
5
+ export type SdkMethod = {
6
+ clientCallName: string;
7
+ fullyQualifiedName: string;
8
+ httpMethod?: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'query';
9
+ httpPath?: string;
10
+ };
11
+
12
+ export const sdkMethods: SdkMethod[] = [
13
+ {
14
+ clientCallName: 'client.health.check',
15
+ fullyQualifiedName: 'health.check',
16
+ httpMethod: 'get',
17
+ httpPath: '/health/',
18
+ },
19
+ {
20
+ clientCallName: 'client.webhooks.create',
21
+ fullyQualifiedName: 'webhooks.create',
22
+ httpMethod: 'post',
23
+ httpPath: '/v2/webhooks/',
24
+ },
25
+ {
26
+ clientCallName: 'client.webhooks.list',
27
+ fullyQualifiedName: 'webhooks.list',
28
+ httpMethod: 'get',
29
+ httpPath: '/v2/webhooks/',
30
+ },
31
+ {
32
+ clientCallName: 'client.webhooks.delete',
33
+ fullyQualifiedName: 'webhooks.delete',
34
+ httpMethod: 'delete',
35
+ httpPath: '/v2/webhooks/{webhook_id}/',
36
+ },
37
+ {
38
+ clientCallName: 'client.files.create',
39
+ fullyQualifiedName: 'files.create',
40
+ httpMethod: 'post',
41
+ httpPath: '/v2/files/',
42
+ },
43
+ {
44
+ clientCallName: 'client.files.list',
45
+ fullyQualifiedName: 'files.list',
46
+ httpMethod: 'get',
47
+ httpPath: '/v2/files/',
48
+ },
49
+ {
50
+ clientCallName: 'client.files.delete',
51
+ fullyQualifiedName: 'files.delete',
52
+ httpMethod: 'delete',
53
+ httpPath: '/v2/files/{collection_id}/',
54
+ },
55
+ {
56
+ clientCallName: 'client.files.getExtractionResults',
57
+ fullyQualifiedName: 'files.getExtractionResults',
58
+ httpMethod: 'get',
59
+ httpPath: '/v2/files/{collection_id}/extraction/',
60
+ },
61
+ {
62
+ clientCallName: 'client.workflows.create',
63
+ fullyQualifiedName: 'workflows.create',
64
+ httpMethod: 'post',
65
+ httpPath: '/v2/workflows/',
66
+ },
67
+ {
68
+ clientCallName: 'client.workflows.retrieve',
69
+ fullyQualifiedName: 'workflows.retrieve',
70
+ httpMethod: 'get',
71
+ httpPath: '/v2/workflows/{workflow_id}/',
72
+ },
73
+ {
74
+ clientCallName: 'client.workflows.list',
75
+ fullyQualifiedName: 'workflows.list',
76
+ httpMethod: 'get',
77
+ httpPath: '/v2/workflows/',
78
+ },
79
+ {
80
+ clientCallName: 'client.workflows.delete',
81
+ fullyQualifiedName: 'workflows.delete',
82
+ httpMethod: 'delete',
83
+ httpPath: '/v2/workflows/{workflow_id}/',
84
+ },
85
+ {
86
+ clientCallName: 'client.workflows.listRuns',
87
+ fullyQualifiedName: 'workflows.listRuns',
88
+ httpMethod: 'get',
89
+ httpPath: '/v2/workflows/{workflow_id}/runs/',
90
+ },
91
+ {
92
+ clientCallName: 'client.workflows.results',
93
+ fullyQualifiedName: 'workflows.results',
94
+ httpMethod: 'get',
95
+ httpPath: '/v2/workflows/{workflow_id}/results/',
96
+ },
97
+ {
98
+ clientCallName: 'client.workflows.run',
99
+ fullyQualifiedName: 'workflows.run',
100
+ httpMethod: 'post',
101
+ httpPath: '/v2/workflows/{workflow_id}/run/',
102
+ },
103
+ {
104
+ clientCallName: 'client.workflows.upload',
105
+ fullyQualifiedName: 'workflows.upload',
106
+ httpMethod: 'post',
107
+ httpPath: '/v2/workflows/{workflow_id}/upload/',
108
+ },
109
+ ];
110
+
111
+ function allowedMethodsForCodeTool(options: McpOptions | undefined): SdkMethod[] | undefined {
112
+ if (!options) {
113
+ return undefined;
114
+ }
115
+
116
+ let allowedMethods: SdkMethod[];
117
+
118
+ if (options.codeAllowHttpGets || options.codeAllowedMethods) {
119
+ // Start with nothing allowed and then add into it from options
120
+ let allowedMethodsSet = new Set<SdkMethod>();
121
+
122
+ if (options.codeAllowHttpGets) {
123
+ // Add all methods that map to an HTTP GET
124
+ sdkMethods
125
+ .filter((method) => method.httpMethod === 'get')
126
+ .forEach((method) => allowedMethodsSet.add(method));
127
+ }
128
+
129
+ if (options.codeAllowedMethods) {
130
+ // Add all methods that match any of the allowed regexps
131
+ const allowedRegexps = options.codeAllowedMethods.map((pattern) => {
132
+ try {
133
+ return new RegExp(pattern);
134
+ } catch (e) {
135
+ throw new Error(
136
+ `Invalid regex pattern for allowed method: "${pattern}": ${e instanceof Error ? e.message : e}`,
137
+ );
138
+ }
139
+ });
140
+
141
+ sdkMethods
142
+ .filter((method) => allowedRegexps.some((regexp) => regexp.test(method.fullyQualifiedName)))
143
+ .forEach((method) => allowedMethodsSet.add(method));
144
+ }
145
+
146
+ allowedMethods = Array.from(allowedMethodsSet);
147
+ } else {
148
+ // Start with everything allowed
149
+ allowedMethods = [...sdkMethods];
150
+ }
151
+
152
+ if (options.codeBlockedMethods) {
153
+ // Filter down based on blocked regexps
154
+ const blockedRegexps = options.codeBlockedMethods.map((pattern) => {
155
+ try {
156
+ return new RegExp(pattern);
157
+ } catch (e) {
158
+ throw new Error(
159
+ `Invalid regex pattern for blocked method: "${pattern}": ${e instanceof Error ? e.message : e}`,
160
+ );
161
+ }
162
+ });
163
+
164
+ allowedMethods = allowedMethods.filter(
165
+ (method) => !blockedRegexps.some((regexp) => regexp.test(method.fullyQualifiedName)),
166
+ );
167
+ }
168
+
169
+ return allowedMethods;
170
+ }
171
+
172
+ export function blockedMethodsForCodeTool(options: McpOptions | undefined): SdkMethod[] | undefined {
173
+ const allowedMethods = allowedMethodsForCodeTool(options);
174
+ if (!allowedMethods) {
175
+ return undefined;
176
+ }
177
+
178
+ const allowedSet = new Set(allowedMethods.map((method) => method.fullyQualifiedName));
179
+
180
+ // Return any methods that are not explicitly allowed
181
+ return sdkMethods.filter((method) => !allowedSet.has(method.fullyQualifiedName));
182
+ }
package/src/options.ts ADDED
@@ -0,0 +1,185 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import qs from 'qs';
4
+ import yargs from 'yargs';
5
+ import { hideBin } from 'yargs/helpers';
6
+ import z from 'zod';
7
+ import { readEnv } from './util';
8
+
9
+ export type CLIOptions = McpOptions & {
10
+ debug: boolean;
11
+ logFormat: 'json' | 'pretty';
12
+ transport: 'stdio' | 'http';
13
+ port: number | undefined;
14
+ socket: string | undefined;
15
+ };
16
+
17
+ export type McpOptions = {
18
+ includeCodeTool?: boolean | undefined;
19
+ includeDocsTools?: boolean | undefined;
20
+ stainlessApiKey?: string | undefined;
21
+ docsSearchMode?: 'stainless-api' | 'local' | undefined;
22
+ docsDir?: string | undefined;
23
+ codeAllowHttpGets?: boolean | undefined;
24
+ codeAllowedMethods?: string[] | undefined;
25
+ codeBlockedMethods?: string[] | undefined;
26
+ codeExecutionMode: McpCodeExecutionMode;
27
+ customInstructionsPath?: string | undefined;
28
+ };
29
+
30
+ export type McpCodeExecutionMode = 'stainless-sandbox' | 'local';
31
+
32
+ export function parseCLIOptions(): CLIOptions {
33
+ const opts = yargs(hideBin(process.argv))
34
+ .option('code-allow-http-gets', {
35
+ type: 'boolean',
36
+ description:
37
+ 'Allow all code tool methods that map to HTTP GET operations. If all code-allow-* flags are unset, then everything is allowed.',
38
+ })
39
+ .option('code-allowed-methods', {
40
+ type: 'string',
41
+ array: true,
42
+ description:
43
+ 'Methods to explicitly allow for code tool. Evaluated as regular expressions against method fully qualified names. If all code-allow-* flags are unset, then everything is allowed.',
44
+ })
45
+ .option('code-blocked-methods', {
46
+ type: 'string',
47
+ array: true,
48
+ description:
49
+ 'Methods to explicitly block for code tool. Evaluated as regular expressions against method fully qualified names. If all code-allow-* flags are unset, then everything is allowed.',
50
+ })
51
+ .option('code-execution-mode', {
52
+ type: 'string',
53
+ choices: ['stainless-sandbox', 'local'],
54
+ default: 'stainless-sandbox',
55
+ description:
56
+ "Where to run code execution in code tool; 'stainless-sandbox' will execute code in Stainless-hosted sandboxes whereas 'local' will execute code locally on the MCP server machine.",
57
+ })
58
+ .option('custom-instructions-path', {
59
+ type: 'string',
60
+ description: 'Path to custom instructions for the MCP server',
61
+ })
62
+ .option('debug', { type: 'boolean', description: 'Enable debug logging' })
63
+ .option('docs-dir', {
64
+ type: 'string',
65
+ description:
66
+ 'Path to a directory of local documentation files (markdown/JSON) to include in local docs search.',
67
+ })
68
+ .option('docs-search-mode', {
69
+ type: 'string',
70
+ choices: ['stainless-api', 'local'],
71
+ default: 'stainless-api',
72
+ description:
73
+ "Where to search documentation; 'stainless-api' uses the Stainless-hosted search API whereas 'local' uses an in-memory search index built from embedded SDK method data and optional local docs files.",
74
+ })
75
+ .option('log-format', {
76
+ type: 'string',
77
+ choices: ['json', 'pretty'],
78
+ description: 'Format for log output; defaults to json unless tty is detected',
79
+ })
80
+ .option('no-tools', {
81
+ type: 'string',
82
+ array: true,
83
+ choices: ['code', 'docs'],
84
+ description: 'Tools to explicitly disable',
85
+ })
86
+ .option('port', {
87
+ type: 'number',
88
+ default: 3000,
89
+ description: 'Port to serve on if using http transport',
90
+ })
91
+ .option('socket', { type: 'string', description: 'Unix socket to serve on if using http transport' })
92
+ .option('stainless-api-key', {
93
+ type: 'string',
94
+ default: readEnv('STAINLESS_API_KEY'),
95
+ description:
96
+ 'API key for Stainless. Used to authenticate requests to Stainless-hosted tools endpoints.',
97
+ })
98
+ .option('tools', {
99
+ type: 'string',
100
+ array: true,
101
+ choices: ['code', 'docs'],
102
+ description: 'Tools to explicitly enable',
103
+ })
104
+ .option('transport', {
105
+ type: 'string',
106
+ choices: ['stdio', 'http'],
107
+ default: 'stdio',
108
+ description: 'What transport to use; stdio for local servers or http for remote servers',
109
+ })
110
+ .env('MCP_SERVER')
111
+ .version(true)
112
+ .help();
113
+
114
+ const argv = opts.parseSync();
115
+
116
+ const shouldIncludeToolType = (toolType: 'code' | 'docs') =>
117
+ argv.noTools?.includes(toolType) ? false
118
+ : argv.tools?.includes(toolType) ? true
119
+ : undefined;
120
+
121
+ const includeCodeTool = shouldIncludeToolType('code');
122
+ const includeDocsTools = shouldIncludeToolType('docs');
123
+
124
+ const transport = argv.transport as 'stdio' | 'http';
125
+ const logFormat =
126
+ argv.logFormat ? (argv.logFormat as 'json' | 'pretty')
127
+ : process.stderr.isTTY ? 'pretty'
128
+ : 'json';
129
+
130
+ return {
131
+ ...(includeCodeTool !== undefined && { includeCodeTool }),
132
+ ...(includeDocsTools !== undefined && { includeDocsTools }),
133
+ debug: !!argv.debug,
134
+ stainlessApiKey: argv.stainlessApiKey,
135
+ docsSearchMode: argv.docsSearchMode as 'stainless-api' | 'local' | undefined,
136
+ docsDir: argv.docsDir,
137
+ codeAllowHttpGets: argv.codeAllowHttpGets,
138
+ codeAllowedMethods: argv.codeAllowedMethods,
139
+ codeBlockedMethods: argv.codeBlockedMethods,
140
+ codeExecutionMode: argv.codeExecutionMode as McpCodeExecutionMode,
141
+ customInstructionsPath: argv.customInstructionsPath,
142
+ transport,
143
+ logFormat,
144
+ port: argv.port,
145
+ socket: argv.socket,
146
+ };
147
+ }
148
+
149
+ const coerceArray = <T extends z.ZodTypeAny>(zodType: T) =>
150
+ z.preprocess(
151
+ (val) =>
152
+ Array.isArray(val) ? val
153
+ : val ? [val]
154
+ : val,
155
+ z.array(zodType).optional(),
156
+ );
157
+
158
+ const QueryOptions = z.object({
159
+ tools: coerceArray(z.enum(['code', 'docs'])).describe('Specify which MCP tools to use'),
160
+ no_tools: coerceArray(z.enum(['code', 'docs'])).describe('Specify which MCP tools to not use.'),
161
+ tool: coerceArray(z.string()).describe('Include tools matching the specified names'),
162
+ });
163
+
164
+ export function parseQueryOptions(defaultOptions: McpOptions, query: unknown): McpOptions {
165
+ const queryObject = typeof query === 'string' ? qs.parse(query) : query;
166
+ const queryOptions = QueryOptions.parse(queryObject);
167
+
168
+ let codeTool: boolean | undefined =
169
+ queryOptions.no_tools && queryOptions.no_tools?.includes('code') ? false
170
+ : queryOptions.tools?.includes('code') ? true
171
+ : defaultOptions.includeCodeTool;
172
+
173
+ let docsTools: boolean | undefined =
174
+ queryOptions.no_tools && queryOptions.no_tools?.includes('docs') ? false
175
+ : queryOptions.tools?.includes('docs') ? true
176
+ : defaultOptions.includeDocsTools;
177
+
178
+ return {
179
+ ...(codeTool !== undefined && { includeCodeTool: codeTool }),
180
+ ...(docsTools !== undefined && { includeDocsTools: docsTools }),
181
+ codeExecutionMode: defaultOptions.codeExecutionMode,
182
+ docsSearchMode: defaultOptions.docsSearchMode,
183
+ docsDir: defaultOptions.docsDir,
184
+ };
185
+ }
package/src/server.ts ADDED
@@ -0,0 +1,208 @@
1
+ // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import { Server } from '@modelcontextprotocol/sdk/server/index.js';
4
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
+ import {
6
+ CallToolRequestSchema,
7
+ ListToolsRequestSchema,
8
+ SetLevelRequestSchema,
9
+ } from '@modelcontextprotocol/sdk/types.js';
10
+ import { ClientOptions } from 'anyformat-ai';
11
+ import Anyformat from 'anyformat-ai';
12
+ import { codeTool } from './code-tool';
13
+ import docsSearchTool from './docs-search-tool';
14
+ import { setLocalSearch } from './docs-search-tool';
15
+ import { LocalDocsSearch } from './local-docs-search';
16
+ import { getInstructions } from './instructions';
17
+ import { McpOptions } from './options';
18
+ import { blockedMethodsForCodeTool } from './methods';
19
+ import { HandlerFunction, McpRequestContext, ToolCallResult, McpTool } from './types';
20
+
21
+ export const newMcpServer = async ({
22
+ stainlessApiKey,
23
+ customInstructionsPath,
24
+ }: {
25
+ stainlessApiKey?: string | undefined;
26
+ customInstructionsPath?: string | undefined;
27
+ }) =>
28
+ new McpServer(
29
+ {
30
+ name: 'anyformat_ai_api',
31
+ version: '0.1.3',
32
+ },
33
+ {
34
+ instructions: await getInstructions({ stainlessApiKey, customInstructionsPath }),
35
+ capabilities: { tools: {}, logging: {} },
36
+ },
37
+ );
38
+
39
+ /**
40
+ * Initializes the provided MCP Server with the given tools and handlers.
41
+ * If not provided, the default client, tools and handlers will be used.
42
+ */
43
+ export async function initMcpServer(params: {
44
+ server: Server | McpServer;
45
+ clientOptions?: ClientOptions;
46
+ mcpOptions?: McpOptions;
47
+ stainlessApiKey?: string | undefined;
48
+ upstreamClientEnvs?: Record<string, string> | undefined;
49
+ mcpSessionId?: string | undefined;
50
+ mcpClientInfo?: { name: string; version: string } | undefined;
51
+ }) {
52
+ const server = params.server instanceof McpServer ? params.server.server : params.server;
53
+
54
+ const logAtLevel =
55
+ (level: 'debug' | 'info' | 'warning' | 'error') =>
56
+ (message: string, ...rest: unknown[]) => {
57
+ void server.sendLoggingMessage({
58
+ level,
59
+ data: { message, rest },
60
+ });
61
+ };
62
+ const logger = {
63
+ debug: logAtLevel('debug'),
64
+ info: logAtLevel('info'),
65
+ warn: logAtLevel('warning'),
66
+ error: logAtLevel('error'),
67
+ };
68
+
69
+ if (params.mcpOptions?.docsSearchMode === 'local') {
70
+ const docsDir = params.mcpOptions?.docsDir;
71
+ const localSearch = await LocalDocsSearch.create(docsDir ? { docsDir } : undefined);
72
+ setLocalSearch(localSearch);
73
+ }
74
+
75
+ let _client: Anyformat | undefined;
76
+ let _clientError: Error | undefined;
77
+ let _logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off' | undefined;
78
+
79
+ const getClient = (): Anyformat => {
80
+ if (_clientError) throw _clientError;
81
+ if (!_client) {
82
+ try {
83
+ _client = new Anyformat({
84
+ logger,
85
+ ...params.clientOptions,
86
+ defaultHeaders: {
87
+ ...params.clientOptions?.defaultHeaders,
88
+ 'X-Stainless-MCP': 'true',
89
+ },
90
+ });
91
+ if (_logLevel) {
92
+ _client = _client.withOptions({ logLevel: _logLevel });
93
+ }
94
+ } catch (e) {
95
+ _clientError = e instanceof Error ? e : new Error(String(e));
96
+ throw _clientError;
97
+ }
98
+ }
99
+ return _client;
100
+ };
101
+
102
+ const providedTools = selectTools(params.mcpOptions);
103
+ const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool]));
104
+
105
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
106
+ return {
107
+ tools: providedTools.map((mcpTool) => mcpTool.tool),
108
+ };
109
+ });
110
+
111
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
112
+ const { name, arguments: args } = request.params;
113
+ const mcpTool = toolMap[name];
114
+ if (!mcpTool) {
115
+ throw new Error(`Unknown tool: ${name}`);
116
+ }
117
+
118
+ let client: Anyformat;
119
+ try {
120
+ client = getClient();
121
+ } catch (error) {
122
+ return {
123
+ content: [
124
+ {
125
+ type: 'text' as const,
126
+ text: `Failed to initialize client: ${error instanceof Error ? error.message : String(error)}`,
127
+ },
128
+ ],
129
+ isError: true,
130
+ };
131
+ }
132
+
133
+ return executeHandler({
134
+ handler: mcpTool.handler,
135
+ reqContext: {
136
+ client,
137
+ stainlessApiKey: params.stainlessApiKey ?? params.mcpOptions?.stainlessApiKey,
138
+ upstreamClientEnvs: params.upstreamClientEnvs,
139
+ mcpSessionId: params.mcpSessionId,
140
+ mcpClientInfo: params.mcpClientInfo,
141
+ },
142
+ args,
143
+ });
144
+ });
145
+
146
+ server.setRequestHandler(SetLevelRequestSchema, async (request) => {
147
+ const { level } = request.params;
148
+ let logLevel: 'debug' | 'info' | 'warn' | 'error' | 'off';
149
+ switch (level) {
150
+ case 'debug':
151
+ logLevel = 'debug';
152
+ break;
153
+ case 'info':
154
+ logLevel = 'info';
155
+ break;
156
+ case 'notice':
157
+ case 'warning':
158
+ logLevel = 'warn';
159
+ break;
160
+ case 'error':
161
+ logLevel = 'error';
162
+ break;
163
+ default:
164
+ logLevel = 'off';
165
+ break;
166
+ }
167
+ _logLevel = logLevel;
168
+ if (_client) {
169
+ _client = _client.withOptions({ logLevel });
170
+ }
171
+ return {};
172
+ });
173
+ }
174
+
175
+ /**
176
+ * Selects the tools to include in the MCP Server based on the provided options.
177
+ */
178
+ export function selectTools(options?: McpOptions): McpTool[] {
179
+ const includedTools = [];
180
+
181
+ if (options?.includeCodeTool ?? true) {
182
+ includedTools.push(
183
+ codeTool({
184
+ blockedMethods: blockedMethodsForCodeTool(options),
185
+ codeExecutionMode: options?.codeExecutionMode ?? 'stainless-sandbox',
186
+ }),
187
+ );
188
+ }
189
+ if (options?.includeDocsTools ?? true) {
190
+ includedTools.push(docsSearchTool);
191
+ }
192
+ return includedTools;
193
+ }
194
+
195
+ /**
196
+ * Runs the provided handler with the given client and arguments.
197
+ */
198
+ export async function executeHandler({
199
+ handler,
200
+ reqContext,
201
+ args,
202
+ }: {
203
+ handler: HandlerFunction;
204
+ reqContext: McpRequestContext;
205
+ args: Record<string, unknown> | undefined;
206
+ }): Promise<ToolCallResult> {
207
+ return await handler({ reqContext, args: args || {} });
208
+ }
package/src/stdio.ts ADDED
@@ -0,0 +1,17 @@
1
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
2
+ import { McpOptions } from './options';
3
+ import { initMcpServer, newMcpServer } from './server';
4
+ import { getLogger } from './logger';
5
+
6
+ export const launchStdioServer = async (mcpOptions: McpOptions) => {
7
+ const server = await newMcpServer({
8
+ stainlessApiKey: mcpOptions.stainlessApiKey,
9
+ customInstructionsPath: mcpOptions.customInstructionsPath,
10
+ });
11
+
12
+ await initMcpServer({ server, mcpOptions, stainlessApiKey: mcpOptions.stainlessApiKey });
13
+
14
+ const transport = new StdioServerTransport();
15
+ await server.connect(transport);
16
+ getLogger().info('MCP Server running on stdio');
17
+ };
@@ -0,0 +1,11 @@
1
+ {
2
+ // this config is included in the published src directory to prevent TS errors
3
+ // from appearing when users go to source, and VSCode opens the source .ts file
4
+ // via declaration maps
5
+ "include": ["index.ts"],
6
+ "compilerOptions": {
7
+ "target": "es2015",
8
+ "lib": ["DOM"],
9
+ "moduleResolution": "node"
10
+ }
11
+ }