run-azure-code
Execute JavaScript code with Azure SDK to manage resources, handle subscriptions, and query Azure environments directly through natural language interactions.
Instructions
Run Azure code
Tool call template
Replace each placeholder with a value matching the input schema. Only required parameters are included; add optional parameters as needed.
{
"id": 1,
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"arguments": {
"reasoning": "<reasoning>",
"code": "<code>"
},
"name": "run-azure-code"
}
}Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| reasoning | Yes | The reasoning behind the code | |
| code | Yes | Your job is to answer questions about Azure environment by writing Javascript code using Azure SDK. The code must adhere to a few rules: - Use the provided client instances: 'resourceClient' for ResourceManagementClient, 'subscriptionClient' for SubscriptionClient, and 'authorizationClient' for AuthorizationManagementClient - DO NOT create new client instances or import Azure SDK packages - Use async/await and promises - Think step-by-step before writing the code - Avoid hardcoded values like Resource IDs - Handle errors gracefully - Handle pagination correctly using for-await-of loops - Data returned must be JSON containing only the minimal amount of data needed - Code MUST "return" a value: string, number, boolean or JSON object | |
| tenantId | No | Azure Tenant ID | |
| subscriptionId | No | Azure Subscription ID |
Implementation Reference
- src/AzureServer.ts:299-324 (registration)Tool registration in handleListTools(): defines name, description, and input schema for 'run-azure-code' tool.
{ name: "run-azure-code", description: "Run Azure code", inputSchema: { type: "object", properties: { reasoning: { type: "string", description: "The reasoning behind the code", }, code: { type: "string", description: codePrompt, }, tenantId: { type: "string", description: "Azure Tenant ID", }, subscriptionId: { type: "string", description: "Azure Subscription ID", }, }, required: ["reasoning", "code"], }, }, - src/AzureServer.ts:493-528 (handler)Main handler function: parses args with schema, initializes clients if needed, wraps and executes user-provided Azure code in a vm sandbox with Azure clients in context.
private async handleRunAzureCode(args: any) { const { code, tenantId, subscriptionId } = RunAzureCodeSchema.parse(args); if (!this.context.selectedTenant && !tenantId) { throw new AzureMCPError( "Please select a tenant first using the 'select-tenant' tool!", "NO_TENANT" ); } if (tenantId && subscriptionId) { await this.initializeClients(tenantId, subscriptionId); } if (!this.context.resourceClient || !this.context.subscriptionClient) { throw new AzureMCPError("Clients not initialized", "NO_CLIENTS"); } const wrappedCode = this.wrapUserCode(code); const wrappedIIFECode = `(async function() { return (async () => { ${wrappedCode} })(); })()`; try { const result = await this.executeWithRetry(() => runInContext(wrappedIIFECode, createContext(this.context)) ); return this.createTextResponse(JSON.stringify(result)); } catch (error) { this.logWithContext("error", `Error executing user code: ${error}`, { error, }); throw new AzureMCPError( `Failed to execute code: ${error}`, "CODE_EXECUTION_FAILED" ); } } - src/AzureServer.ts:1097-1105 (schema)Zod schema for validating run-azure-code tool arguments, used in handleRunAzureCode.
const RunAzureCodeSchema = z.object({ reasoning: z .string() .min(1, "Reasoning cannot be empty") .describe("The reasoning behind the code"), code: z.string().min(1, "Code cannot be empty").describe(codePrompt), tenantId: z.string().optional().describe("Azure Tenant ID"), subscriptionId: z.string().optional().describe("Azure Subscription ID"), }); - src/AzureServer.ts:435-437 (registration)Dispatch in handleCallTool switch statement: routes 'run-azure-code' calls to the handler.
case "run-azure-code": result = await this.handleRunAzureCode(args); break; - src/AzureServer.ts:861-898 (helper)Helper function to sanitize, parse, and wrap user code for safe execution, ensuring it returns a value.
private wrapUserCode(userCode: string): string { try { // Sanitize user code to prevent certain patterns const sanitizedCode = userCode .replace(/process\.env/g, "/* process.env access blocked */") .replace(/require\s*\(/g, "/* require blocked */") .replace(/import\s+.*\s+from/g, "/* import blocked */"); const project = new Project({ useInMemoryFileSystem: true, }); const sourceFile = project.createSourceFile("userCode.ts", sanitizedCode); 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(); } catch (error) { this.logWithContext("error", `Error wrapping user code: ${error}`, { error, }); throw new AzureMCPError( "Failed to process user code", "CODE_WRAP_FAILED" ); } }