Skip to main content
Glama
metrxbots

Metrx MCP Server

by metrxbots

Apply Optimization

metrx_apply_optimization
Idempotent

Apply one-click optimizations to agents, such as setting token limits or switching models, for validated recommendations only.

Instructions

Apply a one-click optimization recommendation to an agent. Only works for suggestions marked as "one_click: true". Common optimizations include setting max_tokens limits and switching models. Do NOT use for unvalidated changes — run create_model_experiment first if unsure about impact.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
agent_idYesThe agent to apply the optimization to
optimization_typeYesThe type of optimization to apply (e.g., "token_guardrails", "model_switch")
payloadNoOverride the default optimization payload (advanced)

Implementation Reference

  • The async handler function that executes the apply_optimization tool. It constructs a request body with optimization_type and optional payload, makes a POST request to /agents/{agent_id}/settings, and returns a success or error message to the user.
    async ({ agent_id, optimization_type, payload }) => {
      const body: Record<string, unknown> = {
        optimization_type,
        ...(payload || {}),
      };
    
      const result = await client.post<{ applied: boolean; message: string }>(
        `/agents/${agent_id}/settings`,
        body
      );
    
      if (result.error) {
        return {
          content: [{ type: 'text', text: `Error applying optimization: ${result.error}` }],
          isError: true,
        };
      }
    
      return {
        content: [
          {
            type: 'text',
            text: result.data?.applied
              ? `✅ Optimization "${optimization_type}" applied successfully to agent ${agent_id}. ${
                  result.data.message || ''
                }`
              : `⚠️ Optimization could not be applied: ${result.data?.message || 'Unknown reason'}`,
          },
        ],
      };
    }
  • Zod input schema validation for apply_optimization tool. Defines three parameters: agent_id (required UUID), optimization_type (required string), and payload (optional record for advanced override).
    inputSchema: {
      agent_id: z.string().uuid().describe('The agent to apply the optimization to'),
      optimization_type: z
        .string()
        .describe('The type of optimization to apply (e.g., "token_guardrails", "model_switch")'),
      payload: z
        .record(z.unknown())
        .optional()
        .describe('Override the default optimization payload (advanced)'),
    },
  • Tool registration for apply_optimization. Includes tool metadata (title, description), input schema, annotations, and the handler function. The tool is registered as 'apply_optimization' and gets prefixed with 'metrx_' in index.ts.
    server.registerTool(
      'apply_optimization',
      {
        title: 'Apply Optimization',
        description:
          'Apply a one-click optimization recommendation to an agent. ' +
          'Only works for suggestions marked as "one_click: true". ' +
          'Common optimizations include setting max_tokens limits and switching models. ' +
          'Do NOT use for unvalidated changes — run create_model_experiment first if unsure about impact.',
        inputSchema: {
          agent_id: z.string().uuid().describe('The agent to apply the optimization to'),
          optimization_type: z
            .string()
            .describe('The type of optimization to apply (e.g., "token_guardrails", "model_switch")'),
          payload: z
            .record(z.unknown())
            .optional()
            .describe('Override the default optimization payload (advanced)'),
        },
        annotations: {
          readOnlyHint: false,
          destructiveHint: false,
          idempotentHint: true,
          openWorldHint: false,
        },
      },
      async ({ agent_id, optimization_type, payload }) => {
        const body: Record<string, unknown> = {
          optimization_type,
          ...(payload || {}),
        };
    
        const result = await client.post<{ applied: boolean; message: string }>(
          `/agents/${agent_id}/settings`,
          body
        );
    
        if (result.error) {
          return {
            content: [{ type: 'text', text: `Error applying optimization: ${result.error}` }],
            isError: true,
          };
        }
    
        return {
          content: [
            {
              type: 'text',
              text: result.data?.applied
                ? `✅ Optimization "${optimization_type}" applied successfully to agent ${agent_id}. ${
                    result.data.message || ''
                  }`
                : `⚠️ Optimization could not be applied: ${result.data?.message || 'Unknown reason'}`,
            },
          ],
        };
      }
    );
  • The monkey-patched registerTool function that adds the 'metrx_' prefix to all tool names. This is where 'apply_optimization' becomes 'metrx_apply_optimization'. Also wraps handlers with rate limiting middleware.
    const METRX_PREFIX = 'metrx_';
    const originalRegisterTool = server.registerTool.bind(server);
    (server as any).registerTool = function (
      name: string,
      config: any,
      handler: (...handlerArgs: any[]) => Promise<any>
    ) {
      const wrappedHandler = async (...handlerArgs: any[]) => {
        if (!rateLimiter.isAllowed(name)) {
          return {
            content: [
              {
                type: 'text' as const,
                text: `Rate limit exceeded for tool '${name}'. Maximum 60 requests per minute allowed.`,
              },
            ],
            isError: true,
          };
        }
        return handler(...handlerArgs);
      };
    
      // Register with metrx_ prefix (only — no deprecated aliases)
      const prefixedName = name.startsWith(METRX_PREFIX) ? name : `${METRX_PREFIX}${name}`;
      originalRegisterTool(prefixedName, config, wrappedHandler);
    };
Behavior4/5

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

Annotations already indicate this is a non-destructive, idempotent mutation (readOnlyHint: false, destructiveHint: false, idempotentHint: true). The description adds valuable context beyond annotations by specifying the precondition ('only works for suggestions marked as "one_click: true"') and common use cases ('Common optimizations include setting max_tokens limits and switching models'), though it doesn't mention rate limits or auth needs.

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?

Three sentences with zero waste: first states purpose and precondition, second gives examples, third provides critical usage warning. Each sentence earns its place by adding distinct value, and the structure is front-loaded with essential information.

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

Completeness4/5

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

For a mutation tool with good annotations (non-destructive, idempotent) and no output schema, the description is largely complete: it covers purpose, preconditions, examples, and usage warnings. However, it doesn't describe the return value or error cases, which would be helpful given the absence of an 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 three parameters. The description doesn't add any parameter-specific details beyond what the schema provides (e.g., it doesn't explain 'optimization_type' values like 'token_guardrails' or 'payload' usage). Baseline 3 is appropriate when the schema handles parameter documentation.

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

Purpose5/5

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

The description clearly states the specific action ('apply a one-click optimization recommendation') and the target resource ('to an agent'), distinguishing it from siblings like 'metrx_get_optimization_recommendations' (which retrieves suggestions) and 'metrx_create_model_experiment' (for unvalidated changes). It specifies the exact scope ('only works for suggestions marked as "one_click: true"').

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

Usage Guidelines5/5

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

Explicit guidance is provided on when to use ('Only works for suggestions marked as "one_click: true"') and when not to use ('Do NOT use for unvalidated changes'), with a clear alternative named ('run create_model_experiment first if unsure about impact'). This directly addresses sibling tool differentiation.

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/metrxbots/metrx-mcp-server'

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