Skip to main content
Glama
metrxbots

Metrx MCP Server

by metrxbots

metrx_apply_optimization

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);
    };

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