-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathindex.ts
339 lines (308 loc) · 10.9 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
import { Project, SyntaxKind } from "ts-morph";
import { createContext, runInContext } from "node:vm";
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { z } from "zod";
import * as AWS from "aws-sdk";
import open from "open";
import { fromNodeProviderChain } from "@aws-sdk/credential-providers";
const codePrompt = `Your job is to answer questions about AWS environment by writing Javascript code using AWS SDK V2. The code must be adhering to a few rules:
- Must be preferring promises over callbacks
- Think step-by-step before writing the code, approach it logically
- MUST written in Javascript (NodeJS) using AWS-SDK V2
- Avoid hardcoded values like ARNs
- Code written should be as parallel as possible enabling the fastest and the most optimal execution
- Code should be handling errors gracefully, especially when doing multiple SDK calls (e.g. when mapping over an array). Each error should be handled and logged with a reason, script should continue to run despite errors
- DO NOT require or import "aws-sdk", it is already available as "AWS" variable
- Access to 3rd party libraries apart from "aws-sdk" is not allowed or possible
- Data returned from AWS-SDK must be returned as JSON containing only the minimal amount of data that is needed to answer the question. All extra data must be filtered out
- Code MUST "return" a value: string, number, boolean or JSON object. If code does not return anything, it will be considered as FAILED
- Whenever tool/function call fails, retry it 3 times before giving up with an improved version of the code based on the returned feedback
- When listing resources, ensure pagination is handled correctly so that all resources are returned
- Do not include any comments in the code
- When doing reduce, don't forget to provide an initial value
- Try to write code that returns as few data as possible to answer without any additional processing required after the code is run
- This tool can ONLY write code that interacts with AWS. It CANNOT generate charts, tables, graphs, etc. Please use artifacts for that instead
Be concise, professional and to the point. Do not give generic advice, always reply with detailed & contextual data sourced from the current AWS environment. Assume user always wants to proceed, do not ask for confirmation. I'll tip you $200 if you do this right.`;
const server = new Server(
{
name: "aws-mcp",
version: "1.0.0",
},
{
capabilities: {
tools: {},
},
}
);
let selectedProfile: string | null = null;
let selectedProfileCredentials: AWS.Credentials | AWS.SSO.RoleCredentials | any;
let selectedProfileRegion: string = "us-east-1";
server.setRequestHandler(ListToolsRequestSchema, async () => {
return {
tools: [
{
name: "run-aws-code",
description: "Run AWS code",
inputSchema: {
type: "object",
properties: {
reasoning: {
type: "string",
description: "The reasoning behind the code",
},
code: {
type: "string",
description: codePrompt,
},
profileName: {
type: "string",
description: "Name of the AWS profile to use",
},
region: {
type: "string",
description: "Region to use (if not provided, us-east-1 is used)",
},
},
required: ["reasoning", "code"],
},
},
{
name: "list-credentials",
description:
"List all AWS credentials/configs/profiles that are configured/usable on this machine",
inputSchema: {
type: "object",
properties: {},
required: [],
},
},
{
name: "select-profile",
description:
"Selects AWS profile to use for subsequent interactions. If needed, does SSO authentication",
inputSchema: {
type: "object",
properties: {
profile: {
type: "string",
description: "Name of the AWS profile to select",
},
region: {
type: "string",
description: "Region to use (if not provided, us-east-1 is used)",
},
},
required: ["profile"],
},
},
],
};
});
const RunAwsCodeSchema = z.object({
reasoning: z.string(),
code: z.string(),
profileName: z.string().optional(),
region: z.string().optional(),
});
const SelectProfileSchema = z.object({
profile: z.string(),
region: z.string().optional(),
});
// Handle tool execution
server.setRequestHandler(CallToolRequestSchema, async (request, c) => {
const { name, arguments: args } = request.params;
try {
const { profiles, error } = await listCredentials();
if (name === "run-aws-code") {
const { reasoning, code, profileName, region } =
RunAwsCodeSchema.parse(args);
if (!selectedProfile && !profileName) {
return createTextResponse(
`Please select a profile first using the 'select-profile' tool! Available profiles: ${Object.keys(
profiles
).join(", ")}`
);
}
if (profileName) {
selectedProfileCredentials = await getCredentials(
profiles[profileName],
profileName
);
selectedProfile = profileName;
selectedProfileRegion = region || "us-east-1";
}
AWS.config.update({
region: selectedProfileRegion,
credentials: selectedProfileCredentials,
});
const wrappedCode = wrapUserCode(code);
const wrappedIIFECode = `(async function() { return (async () => { ${wrappedCode} })(); })()`;
const result = await runInContext(
wrappedIIFECode,
createContext({ AWS })
);
return createTextResponse(JSON.stringify(result));
} else if (name === "list-credentials") {
return createTextResponse(
JSON.stringify({ profiles: Object.keys(profiles), error })
);
} else if (name === "select-profile") {
const { profile, region } = SelectProfileSchema.parse(args);
const credentials = await getCredentials(profiles[profile], profile);
selectedProfile = profile;
selectedProfileCredentials = credentials;
selectedProfileRegion = region || "us-east-1";
return createTextResponse("Authenticated!");
} else {
throw new Error(`Unknown tool: ${name}`);
}
} catch (error) {
if (error instanceof z.ZodError) {
throw new Error(
`Invalid arguments: ${error.errors
.map((e) => `${e.path.join(".")}: ${e.message}`)
.join(", ")}`
);
}
throw error;
}
});
function wrapUserCode(userCode: string) {
const project = new Project({
useInMemoryFileSystem: true,
});
const sourceFile = project.createSourceFile("userCode.ts", userCode);
const lastStatement = sourceFile.getStatements().pop();
if (
lastStatement &&
lastStatement.getKind() === SyntaxKind.ExpressionStatement
) {
const returnStatement = lastStatement.asKind(
SyntaxKind.ExpressionStatement
);
if (returnStatement) {
const expression = returnStatement.getExpression();
sourceFile.addStatements(`return ${expression.getText()};`);
returnStatement.remove();
}
}
return sourceFile.getFullText();
}
async function listCredentials() {
let credentials: any;
let configs: any;
let error: any;
try {
credentials = new AWS.IniLoader().loadFrom({});
} catch (error) {
error = `Failed to load credentials: ${error}`;
}
try {
configs = new AWS.IniLoader().loadFrom({ isConfig: true });
} catch (error) {
error = `Failed to load configs: ${error}`;
}
const profiles = { ...(credentials || {}), ...(configs || {}) };
return { profiles, error };
}
async function getCredentials(
creds: any,
profileName: string
): Promise<AWS.Credentials | AWS.SSO.RoleCredentials | any> {
if (creds.sso_start_url) {
const region = creds.region || "us-east-1";
const ssoStartUrl = creds.sso_start_url;
const oidc = new AWS.SSOOIDC({ region });
const registration = await oidc
.registerClient({ clientName: "chatwithcloud", clientType: "public" })
.promise();
const auth = await oidc
.startDeviceAuthorization({
clientId: registration.clientId!,
clientSecret: registration.clientSecret!,
startUrl: ssoStartUrl,
})
.promise();
// open this in URL browser
if (auth.verificationUriComplete) {
open(auth.verificationUriComplete);
}
let handleId: NodeJS.Timeout;
return new Promise((resolve) => {
handleId = setInterval(async () => {
try {
const createTokenReponse = await oidc
.createToken({
clientId: registration.clientId!,
clientSecret: registration.clientSecret!,
grantType: "urn:ietf:params:oauth:grant-type:device_code",
deviceCode: auth.deviceCode,
})
.promise();
const sso = new AWS.SSO({ region });
const credentials = await sso
.getRoleCredentials({
accessToken: createTokenReponse.accessToken!,
accountId: creds.sso_account_id,
roleName: creds.sso_role_name,
})
.promise();
clearInterval(handleId);
return resolve(credentials.roleCredentials!);
} catch (error) {
if ((error as Error).message !== null) {
// terminal.error(error);
}
}
}, 2500);
});
} else {
return useAWSCredentialsProvider(profileName);
}
}
export const useAWSCredentialsProvider = (
profileName: string,
region: string = "us-east-1",
roleArn?: string
) => {
const provider = fromNodeProviderChain({
clientConfig: { region: region },
profile: profileName,
roleArn,
// TODO: use a better MFA provider that works with Claude
mfaCodeProvider: async (serialArn: string) => {
const readline = await import("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise<string>((resolve) => {
const prompt = () =>
rl.question(`Enter MFA code for ${serialArn}: `, async (input) => {
if (input.trim() !== "") {
resolve(input.trim());
rl.close();
} else {
// prompt again if no input
prompt();
}
});
prompt();
});
},
});
return provider();
};
// Start the server
const transport = new StdioServerTransport();
server.connect(transport).then(() => {
console.error("Local Machine MCP Server running on stdio");
});
const createTextResponse = (text: string) => ({
content: [{ type: "text", text }],
});