@lightsparkdev/grid-mcp 0.3.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.
Files changed (103) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +107 -0
  3. package/code-tool-types.d.mts +14 -0
  4. package/code-tool-types.d.mts.map +1 -0
  5. package/code-tool-types.d.ts +14 -0
  6. package/code-tool-types.d.ts.map +1 -0
  7. package/code-tool-types.js +4 -0
  8. package/code-tool-types.js.map +1 -0
  9. package/code-tool-types.mjs +3 -0
  10. package/code-tool-types.mjs.map +1 -0
  11. package/code-tool.d.mts +15 -0
  12. package/code-tool.d.mts.map +1 -0
  13. package/code-tool.d.ts +15 -0
  14. package/code-tool.d.ts.map +1 -0
  15. package/code-tool.js +116 -0
  16. package/code-tool.js.map +1 -0
  17. package/code-tool.mjs +113 -0
  18. package/code-tool.mjs.map +1 -0
  19. package/docs-search-tool.d.mts +51 -0
  20. package/docs-search-tool.d.mts.map +1 -0
  21. package/docs-search-tool.d.ts +51 -0
  22. package/docs-search-tool.d.ts.map +1 -0
  23. package/docs-search-tool.js +51 -0
  24. package/docs-search-tool.js.map +1 -0
  25. package/docs-search-tool.mjs +47 -0
  26. package/docs-search-tool.mjs.map +1 -0
  27. package/headers.d.mts +4 -0
  28. package/headers.d.mts.map +1 -0
  29. package/headers.d.ts +4 -0
  30. package/headers.d.ts.map +1 -0
  31. package/headers.js +35 -0
  32. package/headers.js.map +1 -0
  33. package/headers.mjs +31 -0
  34. package/headers.mjs.map +1 -0
  35. package/http.d.mts +14 -0
  36. package/http.d.mts.map +1 -0
  37. package/http.d.ts +14 -0
  38. package/http.d.ts.map +1 -0
  39. package/http.js +105 -0
  40. package/http.js.map +1 -0
  41. package/http.mjs +97 -0
  42. package/http.mjs.map +1 -0
  43. package/index.d.mts +3 -0
  44. package/index.d.mts.map +1 -0
  45. package/index.d.ts +3 -0
  46. package/index.d.ts.map +1 -0
  47. package/index.js +59 -0
  48. package/index.js.map +1 -0
  49. package/index.mjs +57 -0
  50. package/index.mjs.map +1 -0
  51. package/methods.d.mts +10 -0
  52. package/methods.d.mts.map +1 -0
  53. package/methods.d.ts +10 -0
  54. package/methods.d.ts.map +1 -0
  55. package/methods.js +328 -0
  56. package/methods.js.map +1 -0
  57. package/methods.mjs +324 -0
  58. package/methods.mjs.map +1 -0
  59. package/options.d.mts +15 -0
  60. package/options.d.mts.map +1 -0
  61. package/options.d.ts +15 -0
  62. package/options.d.ts.map +1 -0
  63. package/options.js +91 -0
  64. package/options.js.map +1 -0
  65. package/options.mjs +84 -0
  66. package/options.mjs.map +1 -0
  67. package/package.json +174 -0
  68. package/server.d.mts +30 -0
  69. package/server.d.mts.map +1 -0
  70. package/server.d.ts +30 -0
  71. package/server.d.ts.map +1 -0
  72. package/server.js +160 -0
  73. package/server.js.map +1 -0
  74. package/server.mjs +147 -0
  75. package/server.mjs.map +1 -0
  76. package/src/code-tool-types.ts +16 -0
  77. package/src/code-tool.ts +140 -0
  78. package/src/docs-search-tool.ts +59 -0
  79. package/src/headers.ts +39 -0
  80. package/src/http.ts +130 -0
  81. package/src/index.ts +65 -0
  82. package/src/methods.ts +348 -0
  83. package/src/options.ts +118 -0
  84. package/src/server.ts +195 -0
  85. package/src/stdio.ts +13 -0
  86. package/src/tsconfig.json +11 -0
  87. package/src/types.ts +115 -0
  88. package/stdio.d.mts +3 -0
  89. package/stdio.d.mts.map +1 -0
  90. package/stdio.d.ts +3 -0
  91. package/stdio.d.ts.map +1 -0
  92. package/stdio.js +14 -0
  93. package/stdio.js.map +1 -0
  94. package/stdio.mjs +10 -0
  95. package/stdio.mjs.map +1 -0
  96. package/types.d.mts +52 -0
  97. package/types.d.mts.map +1 -0
  98. package/types.d.ts +52 -0
  99. package/types.d.ts.map +1 -0
  100. package/types.js +58 -0
  101. package/types.js.map +1 -0
  102. package/types.mjs +53 -0
  103. package/types.mjs.map +1 -0
package/src/methods.ts ADDED
@@ -0,0 +1,348 @@
1
+ import { McpOptions } from './options';
2
+
3
+ export type SdkMethod = {
4
+ clientCallName: string;
5
+ fullyQualifiedName: string;
6
+ httpMethod?: 'get' | 'post' | 'put' | 'patch' | 'delete' | 'query';
7
+ httpPath?: string;
8
+ };
9
+
10
+ export const sdkMethods: SdkMethod[] = [
11
+ {
12
+ clientCallName: 'client.config.retrieve',
13
+ fullyQualifiedName: 'config.retrieve',
14
+ httpMethod: 'get',
15
+ httpPath: '/config',
16
+ },
17
+ {
18
+ clientCallName: 'client.config.update',
19
+ fullyQualifiedName: 'config.update',
20
+ httpMethod: 'patch',
21
+ httpPath: '/config',
22
+ },
23
+ {
24
+ clientCallName: 'client.customers.create',
25
+ fullyQualifiedName: 'customers.create',
26
+ httpMethod: 'post',
27
+ httpPath: '/customers',
28
+ },
29
+ {
30
+ clientCallName: 'client.customers.retrieve',
31
+ fullyQualifiedName: 'customers.retrieve',
32
+ httpMethod: 'get',
33
+ httpPath: '/customers/{customerId}',
34
+ },
35
+ {
36
+ clientCallName: 'client.customers.update',
37
+ fullyQualifiedName: 'customers.update',
38
+ httpMethod: 'patch',
39
+ httpPath: '/customers/{customerId}',
40
+ },
41
+ {
42
+ clientCallName: 'client.customers.list',
43
+ fullyQualifiedName: 'customers.list',
44
+ httpMethod: 'get',
45
+ httpPath: '/customers',
46
+ },
47
+ {
48
+ clientCallName: 'client.customers.delete',
49
+ fullyQualifiedName: 'customers.delete',
50
+ httpMethod: 'delete',
51
+ httpPath: '/customers/{customerId}',
52
+ },
53
+ {
54
+ clientCallName: 'client.customers.getKYCLink',
55
+ fullyQualifiedName: 'customers.getKYCLink',
56
+ httpMethod: 'get',
57
+ httpPath: '/customers/kyc-link',
58
+ },
59
+ {
60
+ clientCallName: 'client.customers.listInternalAccounts',
61
+ fullyQualifiedName: 'customers.listInternalAccounts',
62
+ httpMethod: 'get',
63
+ httpPath: '/customers/internal-accounts',
64
+ },
65
+ {
66
+ clientCallName: 'client.customers.externalAccounts.create',
67
+ fullyQualifiedName: 'customers.externalAccounts.create',
68
+ httpMethod: 'post',
69
+ httpPath: '/customers/external-accounts',
70
+ },
71
+ {
72
+ clientCallName: 'client.customers.externalAccounts.list',
73
+ fullyQualifiedName: 'customers.externalAccounts.list',
74
+ httpMethod: 'get',
75
+ httpPath: '/customers/external-accounts',
76
+ },
77
+ {
78
+ clientCallName: 'client.customers.bulk.getJobStatus',
79
+ fullyQualifiedName: 'customers.bulk.getJobStatus',
80
+ httpMethod: 'get',
81
+ httpPath: '/customers/bulk/jobs/{jobId}',
82
+ },
83
+ {
84
+ clientCallName: 'client.customers.bulk.uploadCsv',
85
+ fullyQualifiedName: 'customers.bulk.uploadCsv',
86
+ httpMethod: 'post',
87
+ httpPath: '/customers/bulk/csv',
88
+ },
89
+ {
90
+ clientCallName: 'client.platform.listInternalAccounts',
91
+ fullyQualifiedName: 'platform.listInternalAccounts',
92
+ httpMethod: 'get',
93
+ httpPath: '/platform/internal-accounts',
94
+ },
95
+ {
96
+ clientCallName: 'client.platform.externalAccounts.create',
97
+ fullyQualifiedName: 'platform.externalAccounts.create',
98
+ httpMethod: 'post',
99
+ httpPath: '/platform/external-accounts',
100
+ },
101
+ {
102
+ clientCallName: 'client.platform.externalAccounts.list',
103
+ fullyQualifiedName: 'platform.externalAccounts.list',
104
+ httpMethod: 'get',
105
+ httpPath: '/platform/external-accounts',
106
+ },
107
+ {
108
+ clientCallName: 'client.plaid.createLinkToken',
109
+ fullyQualifiedName: 'plaid.createLinkToken',
110
+ httpMethod: 'post',
111
+ httpPath: '/plaid/link-tokens',
112
+ },
113
+ {
114
+ clientCallName: 'client.plaid.submitPublicToken',
115
+ fullyQualifiedName: 'plaid.submitPublicToken',
116
+ httpMethod: 'post',
117
+ httpPath: '/plaid/callback/{plaid_link_token}',
118
+ },
119
+ {
120
+ clientCallName: 'client.transferIn.create',
121
+ fullyQualifiedName: 'transferIn.create',
122
+ httpMethod: 'post',
123
+ httpPath: '/transfer-in',
124
+ },
125
+ {
126
+ clientCallName: 'client.transferOut.create',
127
+ fullyQualifiedName: 'transferOut.create',
128
+ httpMethod: 'post',
129
+ httpPath: '/transfer-out',
130
+ },
131
+ {
132
+ clientCallName: 'client.receiver.lookupExternalAccount',
133
+ fullyQualifiedName: 'receiver.lookupExternalAccount',
134
+ httpMethod: 'get',
135
+ httpPath: '/receiver/external-account/{accountId}',
136
+ },
137
+ {
138
+ clientCallName: 'client.receiver.lookupUma',
139
+ fullyQualifiedName: 'receiver.lookupUma',
140
+ httpMethod: 'get',
141
+ httpPath: '/receiver/uma/{receiverUmaAddress}',
142
+ },
143
+ {
144
+ clientCallName: 'client.quotes.create',
145
+ fullyQualifiedName: 'quotes.create',
146
+ httpMethod: 'post',
147
+ httpPath: '/quotes',
148
+ },
149
+ {
150
+ clientCallName: 'client.quotes.retrieve',
151
+ fullyQualifiedName: 'quotes.retrieve',
152
+ httpMethod: 'get',
153
+ httpPath: '/quotes/{quoteId}',
154
+ },
155
+ {
156
+ clientCallName: 'client.quotes.list',
157
+ fullyQualifiedName: 'quotes.list',
158
+ httpMethod: 'get',
159
+ httpPath: '/quotes',
160
+ },
161
+ {
162
+ clientCallName: 'client.quotes.execute',
163
+ fullyQualifiedName: 'quotes.execute',
164
+ httpMethod: 'post',
165
+ httpPath: '/quotes/{quoteId}/execute',
166
+ },
167
+ {
168
+ clientCallName: 'client.transactions.retrieve',
169
+ fullyQualifiedName: 'transactions.retrieve',
170
+ httpMethod: 'get',
171
+ httpPath: '/transactions/{transactionId}',
172
+ },
173
+ {
174
+ clientCallName: 'client.transactions.list',
175
+ fullyQualifiedName: 'transactions.list',
176
+ httpMethod: 'get',
177
+ httpPath: '/transactions',
178
+ },
179
+ {
180
+ clientCallName: 'client.transactions.approve',
181
+ fullyQualifiedName: 'transactions.approve',
182
+ httpMethod: 'post',
183
+ httpPath: '/transactions/{transactionId}/approve',
184
+ },
185
+ {
186
+ clientCallName: 'client.transactions.reject',
187
+ fullyQualifiedName: 'transactions.reject',
188
+ httpMethod: 'post',
189
+ httpPath: '/transactions/{transactionId}/reject',
190
+ },
191
+ {
192
+ clientCallName: 'client.webhooks.sendTest',
193
+ fullyQualifiedName: 'webhooks.sendTest',
194
+ httpMethod: 'post',
195
+ httpPath: '/webhooks/test',
196
+ },
197
+ {
198
+ clientCallName: 'client.invitations.create',
199
+ fullyQualifiedName: 'invitations.create',
200
+ httpMethod: 'post',
201
+ httpPath: '/invitations',
202
+ },
203
+ {
204
+ clientCallName: 'client.invitations.retrieve',
205
+ fullyQualifiedName: 'invitations.retrieve',
206
+ httpMethod: 'get',
207
+ httpPath: '/invitations/{invitationCode}',
208
+ },
209
+ {
210
+ clientCallName: 'client.invitations.cancel',
211
+ fullyQualifiedName: 'invitations.cancel',
212
+ httpMethod: 'post',
213
+ httpPath: '/invitations/{invitationCode}/cancel',
214
+ },
215
+ {
216
+ clientCallName: 'client.invitations.claim',
217
+ fullyQualifiedName: 'invitations.claim',
218
+ httpMethod: 'post',
219
+ httpPath: '/invitations/{invitationCode}/claim',
220
+ },
221
+ {
222
+ clientCallName: 'client.sandbox.sendFunds',
223
+ fullyQualifiedName: 'sandbox.sendFunds',
224
+ httpMethod: 'post',
225
+ httpPath: '/sandbox/send',
226
+ },
227
+ {
228
+ clientCallName: 'client.sandbox.uma.receivePayment',
229
+ fullyQualifiedName: 'sandbox.uma.receivePayment',
230
+ httpMethod: 'post',
231
+ httpPath: '/sandbox/uma/receive',
232
+ },
233
+ {
234
+ clientCallName: 'client.sandbox.internalAccounts.fund',
235
+ fullyQualifiedName: 'sandbox.internalAccounts.fund',
236
+ httpMethod: 'post',
237
+ httpPath: '/sandbox/internal-accounts/{accountId}/fund',
238
+ },
239
+ {
240
+ clientCallName: 'client.umaProviders.list',
241
+ fullyQualifiedName: 'umaProviders.list',
242
+ httpMethod: 'get',
243
+ httpPath: '/uma-providers',
244
+ },
245
+ {
246
+ clientCallName: 'client.tokens.create',
247
+ fullyQualifiedName: 'tokens.create',
248
+ httpMethod: 'post',
249
+ httpPath: '/tokens',
250
+ },
251
+ {
252
+ clientCallName: 'client.tokens.retrieve',
253
+ fullyQualifiedName: 'tokens.retrieve',
254
+ httpMethod: 'get',
255
+ httpPath: '/tokens/{tokenId}',
256
+ },
257
+ {
258
+ clientCallName: 'client.tokens.list',
259
+ fullyQualifiedName: 'tokens.list',
260
+ httpMethod: 'get',
261
+ httpPath: '/tokens',
262
+ },
263
+ {
264
+ clientCallName: 'client.tokens.delete',
265
+ fullyQualifiedName: 'tokens.delete',
266
+ httpMethod: 'delete',
267
+ httpPath: '/tokens/{tokenId}',
268
+ },
269
+ {
270
+ clientCallName: 'client.exchangeRates.list',
271
+ fullyQualifiedName: 'exchangeRates.list',
272
+ httpMethod: 'get',
273
+ httpPath: '/exchange-rates',
274
+ },
275
+ ];
276
+
277
+ function allowedMethodsForCodeTool(options: McpOptions | undefined): SdkMethod[] | undefined {
278
+ if (!options) {
279
+ return undefined;
280
+ }
281
+
282
+ let allowedMethods: SdkMethod[];
283
+
284
+ if (options.codeAllowHttpGets || options.codeAllowedMethods) {
285
+ // Start with nothing allowed and then add into it from options
286
+ let allowedMethodsSet = new Set<SdkMethod>();
287
+
288
+ if (options.codeAllowHttpGets) {
289
+ // Add all methods that map to an HTTP GET
290
+ sdkMethods
291
+ .filter((method) => method.httpMethod === 'get')
292
+ .forEach((method) => allowedMethodsSet.add(method));
293
+ }
294
+
295
+ if (options.codeAllowedMethods) {
296
+ // Add all methods that match any of the allowed regexps
297
+ const allowedRegexps = options.codeAllowedMethods.map((pattern) => {
298
+ try {
299
+ return new RegExp(pattern);
300
+ } catch (e) {
301
+ throw new Error(
302
+ `Invalid regex pattern for allowed method: "${pattern}": ${e instanceof Error ? e.message : e}`,
303
+ );
304
+ }
305
+ });
306
+
307
+ sdkMethods
308
+ .filter((method) => allowedRegexps.some((regexp) => regexp.test(method.fullyQualifiedName)))
309
+ .forEach((method) => allowedMethodsSet.add(method));
310
+ }
311
+
312
+ allowedMethods = Array.from(allowedMethodsSet);
313
+ } else {
314
+ // Start with everything allowed
315
+ allowedMethods = [...sdkMethods];
316
+ }
317
+
318
+ if (options.codeBlockedMethods) {
319
+ // Filter down based on blocked regexps
320
+ const blockedRegexps = options.codeBlockedMethods.map((pattern) => {
321
+ try {
322
+ return new RegExp(pattern);
323
+ } catch (e) {
324
+ throw new Error(
325
+ `Invalid regex pattern for blocked method: "${pattern}": ${e instanceof Error ? e.message : e}`,
326
+ );
327
+ }
328
+ });
329
+
330
+ allowedMethods = allowedMethods.filter(
331
+ (method) => !blockedRegexps.some((regexp) => regexp.test(method.fullyQualifiedName)),
332
+ );
333
+ }
334
+
335
+ return allowedMethods;
336
+ }
337
+
338
+ export function blockedMethodsForCodeTool(options: McpOptions | undefined): SdkMethod[] | undefined {
339
+ const allowedMethods = allowedMethodsForCodeTool(options);
340
+ if (!allowedMethods) {
341
+ return undefined;
342
+ }
343
+
344
+ const allowedSet = new Set(allowedMethods.map((method) => method.fullyQualifiedName));
345
+
346
+ // Return any methods that are not explicitly allowed
347
+ return sdkMethods.filter((method) => !allowedSet.has(method.fullyQualifiedName));
348
+ }
package/src/options.ts ADDED
@@ -0,0 +1,118 @@
1
+ import qs from 'qs';
2
+ import yargs from 'yargs';
3
+ import { hideBin } from 'yargs/helpers';
4
+ import z from 'zod';
5
+
6
+ export type CLIOptions = McpOptions & {
7
+ debug: boolean;
8
+ transport: 'stdio' | 'http';
9
+ port: number | undefined;
10
+ socket: string | undefined;
11
+ };
12
+
13
+ export type McpOptions = {
14
+ includeDocsTools?: boolean | undefined;
15
+ codeAllowHttpGets?: boolean | undefined;
16
+ codeAllowedMethods?: string[] | undefined;
17
+ codeBlockedMethods?: string[] | undefined;
18
+ };
19
+
20
+ export function parseCLIOptions(): CLIOptions {
21
+ const opts = yargs(hideBin(process.argv))
22
+ .option('code-allow-http-gets', {
23
+ type: 'boolean',
24
+ description:
25
+ 'Allow all code tool methods that map to HTTP GET operations. If all code-allow-* flags are unset, then everything is allowed.',
26
+ })
27
+ .option('code-allowed-methods', {
28
+ type: 'string',
29
+ array: true,
30
+ description:
31
+ '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.',
32
+ })
33
+ .option('code-blocked-methods', {
34
+ type: 'string',
35
+ array: true,
36
+ description:
37
+ '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.',
38
+ })
39
+ .option('debug', { type: 'boolean', description: 'Enable debug logging' })
40
+ .option('no-tools', {
41
+ type: 'string',
42
+ array: true,
43
+ choices: ['code', 'docs'],
44
+ description: 'Tools to explicitly disable',
45
+ })
46
+ .option('port', {
47
+ type: 'number',
48
+ default: 3000,
49
+ description: 'Port to serve on if using http transport',
50
+ })
51
+ .option('socket', { type: 'string', description: 'Unix socket to serve on if using http transport' })
52
+ .option('tools', {
53
+ type: 'string',
54
+ array: true,
55
+ choices: ['code', 'docs'],
56
+ description: 'Tools to explicitly enable',
57
+ })
58
+ .option('transport', {
59
+ type: 'string',
60
+ choices: ['stdio', 'http'],
61
+ default: 'stdio',
62
+ description: 'What transport to use; stdio for local servers or http for remote servers',
63
+ })
64
+ .env('MCP_SERVER')
65
+ .version(true)
66
+ .help();
67
+
68
+ const argv = opts.parseSync();
69
+
70
+ const shouldIncludeToolType = (toolType: 'code' | 'docs') =>
71
+ argv.noTools?.includes(toolType) ? false
72
+ : argv.tools?.includes(toolType) ? true
73
+ : undefined;
74
+
75
+ const includeDocsTools = shouldIncludeToolType('docs');
76
+
77
+ const transport = argv.transport as 'stdio' | 'http';
78
+
79
+ return {
80
+ ...(includeDocsTools !== undefined && { includeDocsTools }),
81
+ debug: !!argv.debug,
82
+ codeAllowHttpGets: argv.codeAllowHttpGets,
83
+ codeAllowedMethods: argv.codeAllowedMethods,
84
+ codeBlockedMethods: argv.codeBlockedMethods,
85
+ transport,
86
+ port: argv.port,
87
+ socket: argv.socket,
88
+ };
89
+ }
90
+
91
+ const coerceArray = <T extends z.ZodTypeAny>(zodType: T) =>
92
+ z.preprocess(
93
+ (val) =>
94
+ Array.isArray(val) ? val
95
+ : val ? [val]
96
+ : val,
97
+ z.array(zodType).optional(),
98
+ );
99
+
100
+ const QueryOptions = z.object({
101
+ tools: coerceArray(z.enum(['code', 'docs'])).describe('Specify which MCP tools to use'),
102
+ no_tools: coerceArray(z.enum(['code', 'docs'])).describe('Specify which MCP tools to not use.'),
103
+ tool: coerceArray(z.string()).describe('Include tools matching the specified names'),
104
+ });
105
+
106
+ export function parseQueryOptions(defaultOptions: McpOptions, query: unknown): McpOptions {
107
+ const queryObject = typeof query === 'string' ? qs.parse(query) : query;
108
+ const queryOptions = QueryOptions.parse(queryObject);
109
+
110
+ let docsTools: boolean | undefined =
111
+ queryOptions.no_tools && queryOptions.no_tools?.includes('docs') ? false
112
+ : queryOptions.tools?.includes('docs') ? true
113
+ : defaultOptions.includeDocsTools;
114
+
115
+ return {
116
+ ...(docsTools !== undefined && { includeDocsTools: docsTools }),
117
+ };
118
+ }
package/src/server.ts ADDED
@@ -0,0 +1,195 @@
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 '@lightsparkdev/grid';
11
+ import LightsparkGrid from '@lightsparkdev/grid';
12
+ import { codeTool } from './code-tool';
13
+ import docsSearchTool from './docs-search-tool';
14
+ import { McpOptions } from './options';
15
+ import { blockedMethodsForCodeTool } from './methods';
16
+ import { HandlerFunction, McpTool } from './types';
17
+
18
+ export { McpOptions } from './options';
19
+ export { ClientOptions } from '@lightsparkdev/grid';
20
+
21
+ async function getInstructions() {
22
+ // This API key is optional; providing it allows the server to fetch instructions for unreleased versions.
23
+ const stainlessAPIKey = readEnv('STAINLESS_API_KEY');
24
+ const response = await fetch(
25
+ readEnv('CODE_MODE_INSTRUCTIONS_URL') ?? 'https://api.stainless.com/api/ai/instructions/grid',
26
+ {
27
+ method: 'GET',
28
+ headers: { ...(stainlessAPIKey && { Authorization: stainlessAPIKey }) },
29
+ },
30
+ );
31
+
32
+ let instructions: string | undefined;
33
+ if (!response.ok) {
34
+ console.warn(
35
+ 'Warning: failed to retrieve MCP server instructions. Proceeding with default instructions...',
36
+ );
37
+
38
+ instructions = `
39
+ This is the grid MCP server. You will use Code Mode to help the user perform
40
+ actions. You can use search_docs tool to learn about how to take action with this server. Then,
41
+ you will write TypeScript code using the execute tool take action. It is CRITICAL that you be
42
+ thoughtful and deliberate when executing code. Always try to entirely solve the problem in code
43
+ block: it can be as long as you need to get the job done!
44
+ `;
45
+ }
46
+
47
+ instructions ??= ((await response.json()) as { instructions: string }).instructions;
48
+ instructions = `
49
+ The current time in Unix timestamps is ${Date.now()}.
50
+
51
+ ${instructions}
52
+ `;
53
+
54
+ return instructions;
55
+ }
56
+
57
+ export const newMcpServer = async () =>
58
+ new McpServer(
59
+ {
60
+ name: 'lightsparkdev_grid_api',
61
+ version: '0.3.0',
62
+ },
63
+ {
64
+ instructions: await getInstructions(),
65
+ capabilities: { tools: {}, logging: {} },
66
+ },
67
+ );
68
+
69
+ /**
70
+ * Initializes the provided MCP Server with the given tools and handlers.
71
+ * If not provided, the default client, tools and handlers will be used.
72
+ */
73
+ export async function initMcpServer(params: {
74
+ server: Server | McpServer;
75
+ clientOptions?: ClientOptions;
76
+ mcpOptions?: McpOptions;
77
+ }) {
78
+ const server = params.server instanceof McpServer ? params.server.server : params.server;
79
+
80
+ const logAtLevel =
81
+ (level: 'debug' | 'info' | 'warning' | 'error') =>
82
+ (message: string, ...rest: unknown[]) => {
83
+ void server.sendLoggingMessage({
84
+ level,
85
+ data: { message, rest },
86
+ });
87
+ };
88
+ const logger = {
89
+ debug: logAtLevel('debug'),
90
+ info: logAtLevel('info'),
91
+ warn: logAtLevel('warning'),
92
+ error: logAtLevel('error'),
93
+ };
94
+
95
+ let client = new LightsparkGrid({
96
+ logger,
97
+ ...params.clientOptions,
98
+ defaultHeaders: {
99
+ ...params.clientOptions?.defaultHeaders,
100
+ 'X-Stainless-MCP': 'true',
101
+ },
102
+ });
103
+
104
+ const providedTools = selectTools(params.mcpOptions);
105
+ const toolMap = Object.fromEntries(providedTools.map((mcpTool) => [mcpTool.tool.name, mcpTool]));
106
+
107
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
108
+ return {
109
+ tools: providedTools.map((mcpTool) => mcpTool.tool),
110
+ };
111
+ });
112
+
113
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
114
+ const { name, arguments: args } = request.params;
115
+ const mcpTool = toolMap[name];
116
+ if (!mcpTool) {
117
+ throw new Error(`Unknown tool: ${name}`);
118
+ }
119
+
120
+ return executeHandler(mcpTool.handler, client, args);
121
+ });
122
+
123
+ server.setRequestHandler(SetLevelRequestSchema, async (request) => {
124
+ const { level } = request.params;
125
+ switch (level) {
126
+ case 'debug':
127
+ client = client.withOptions({ logLevel: 'debug' });
128
+ break;
129
+ case 'info':
130
+ client = client.withOptions({ logLevel: 'info' });
131
+ break;
132
+ case 'notice':
133
+ case 'warning':
134
+ client = client.withOptions({ logLevel: 'warn' });
135
+ break;
136
+ case 'error':
137
+ client = client.withOptions({ logLevel: 'error' });
138
+ break;
139
+ default:
140
+ client = client.withOptions({ logLevel: 'off' });
141
+ break;
142
+ }
143
+ return {};
144
+ });
145
+ }
146
+
147
+ /**
148
+ * Selects the tools to include in the MCP Server based on the provided options.
149
+ */
150
+ export function selectTools(options?: McpOptions): McpTool[] {
151
+ const includedTools = [
152
+ codeTool({
153
+ blockedMethods: blockedMethodsForCodeTool(options),
154
+ }),
155
+ ];
156
+ if (options?.includeDocsTools ?? true) {
157
+ includedTools.push(docsSearchTool);
158
+ }
159
+ return includedTools;
160
+ }
161
+
162
+ /**
163
+ * Runs the provided handler with the given client and arguments.
164
+ */
165
+ export async function executeHandler(
166
+ handler: HandlerFunction,
167
+ client: LightsparkGrid,
168
+ args: Record<string, unknown> | undefined,
169
+ ) {
170
+ return await handler(client, args || {});
171
+ }
172
+
173
+ export const readEnv = (env: string): string | undefined => {
174
+ if (typeof (globalThis as any).process !== 'undefined') {
175
+ return (globalThis as any).process.env?.[env]?.trim();
176
+ } else if (typeof (globalThis as any).Deno !== 'undefined') {
177
+ return (globalThis as any).Deno.env?.get?.(env)?.trim();
178
+ }
179
+ return;
180
+ };
181
+
182
+ export const readEnvOrError = (env: string): string => {
183
+ let envValue = readEnv(env);
184
+ if (envValue === undefined) {
185
+ throw new Error(`Environment variable ${env} is not set`);
186
+ }
187
+ return envValue;
188
+ };
189
+
190
+ export const requireValue = <T>(value: T | undefined, description: string): T => {
191
+ if (value === undefined) {
192
+ throw new Error(`Missing required value: ${description}`);
193
+ }
194
+ return value;
195
+ };
package/src/stdio.ts ADDED
@@ -0,0 +1,13 @@
1
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
2
+ import { McpOptions } from './options';
3
+ import { initMcpServer, newMcpServer } from './server';
4
+
5
+ export const launchStdioServer = async (mcpOptions: McpOptions) => {
6
+ const server = await newMcpServer();
7
+
8
+ await initMcpServer({ server, mcpOptions });
9
+
10
+ const transport = new StdioServerTransport();
11
+ await server.connect(transport);
12
+ console.error('MCP Server running on stdio');
13
+ };
@@ -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
+ }