Skip to main content
Glama

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

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
reasoningYesThe reasoning behind the code
codeYesYour 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
tenantIdNoAzure Tenant ID
subscriptionIdNoAzure Subscription ID

Implementation Reference

  • 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"],
      },
    },
  • 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"
        );
      }
    }
  • 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"),
    });
  • Dispatch in handleCallTool switch statement: routes 'run-azure-code' calls to the handler.
    case "run-azure-code":
      result = await this.handleRunAzureCode(args);
      break;
  • 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"
        );
      }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. 'Run Azure code' implies execution but doesn't disclose critical traits: whether it's read-only or mutative, authentication needs, rate limits, error handling, or output format. The input schema hints at some behaviors (e.g., code rules), but the description itself adds minimal value beyond the name.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise with just two words, making it front-loaded and waste-free. However, this conciseness comes at the cost of under-specification, but per the dimension's focus on size and structure, it earns full marks for brevity.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity (code execution tool with 4 parameters, no annotations, and no output schema), the description is incomplete. It doesn't explain the tool's behavior, output, or integration context, leaving significant gaps. The input schema provides some context, but the description fails to compensate for the lack of annotations and output schema.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema fully documents all four parameters. The description adds no additional meaning about parameters beyond what's in the schema. According to the rules, with high schema coverage, the baseline score is 3 when no param info is in the description, which applies here.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose2/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description 'Run Azure code' is essentially a tautology that restates the tool name 'run-azure-code'. It doesn't specify what kind of Azure code (e.g., SDK operations, queries, management tasks) or what resources it acts upon. While it distinguishes from siblings by focusing on code execution rather than specific resource operations, it remains too vague about the actual purpose.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No explicit guidance is provided on when to use this tool versus alternatives. The description doesn't mention prerequisites, context (e.g., vs. direct SDK calls or other tools), or exclusions. Without this, users must infer usage from the input schema, which is insufficient for clear decision-making.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/kalivaraprasad-gonapa/azure-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server