Skip to main content
Glama
zxw94FE

Prompt Optimizer MCP Server

by zxw94FE

optimize_prompt

Analyzes and refines prompts to improve clarity, specificity, structure, and effectiveness for better AI interactions.

Instructions

优化和增强提示词以获得更好的 AI 交互效果。此工具分析提示词并应用各种优化策略来改善清晰度、具体性、结构和有效性。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
originalPromptYes要优化的原始提示词
contextNo优化过程中要考虑的额外上下文或背景信息
targetAudienceNo提示词的目标受众 (例如: '技术专家', '普通用户', '学生')
optimizationGoalsNo要专注的具体优化目标。可用选项: clarity(清晰度), specificity(具体性), structure(结构), context(上下文), actionable(可执行性), conciseness(简洁性), examples(示例), format(格式)
styleNo优化后提示词的期望风格 (例如: 'formal(正式)', 'casual(随意)', 'technical(技术性)', 'creative(创意性)')

Implementation Reference

  • index.ts:74-106 (handler)
    Core handler function in PromptOptimizer class that executes the optimize_prompt tool logic: analyzes input prompt, applies optimization goals, computes improvements and score.
    async optimizePrompt(request: OptimizationRequest): Promise<OptimizationResult> {
      const { originalPrompt, context, targetAudience, optimizationGoals, style } = request;
    
      // 分析原始提示词
      const analysis = this.analyzePrompt(originalPrompt);
    
      // 应用优化策略
      let optimizedPrompt = originalPrompt;
      const improvements: string[] = [];
    
      // 应用选定的优化目标或默认目标
      const goals = optimizationGoals || ['clarity', 'specificity', 'structure'];
    
      for (const goal of goals) {
        const result = this.applyOptimization(optimizedPrompt, goal, context, targetAudience, style);
        optimizedPrompt = result.prompt;
        if (result.improvement) {
          improvements.push(result.improvement);
        }
      }
    
      // 计算改进评分
      const score = this.calculateScore(originalPrompt, optimizedPrompt, improvements);
    
      return {
        optimizedPrompt,
        improvements,
        reasoning: this.generateReasoning(originalPrompt, optimizedPrompt, improvements),
        originalLength: originalPrompt.length,
        optimizedLength: optimizedPrompt.length,
        score
      };
    }
  • Input schema and metadata definition for the optimize_prompt tool, including parameters like originalPrompt, context, goals, etc.
    const OPTIMIZE_PROMPT_TOOL = {
      name: "optimize_prompt",
      description: "优化和增强提示词以获得更好的 AI 交互效果。此工具分析提示词并应用各种优化策略来改善清晰度、具体性、结构和有效性。",
      inputSchema: {
        type: "object",
        properties: {
          originalPrompt: {
            type: "string",
            description: "要优化的原始提示词"
          },
          context: {
            type: "string",
            description: "优化过程中要考虑的额外上下文或背景信息"
          },
          targetAudience: {
            type: "string",
            description: "提示词的目标受众 (例如: '技术专家', '普通用户', '学生')"
          },
          optimizationGoals: {
            type: "array",
            items: {
              type: "string",
              enum: ["clarity", "specificity", "structure", "context", "actionable", "conciseness", "examples", "format"]
            },
            description: "要专注的具体优化目标。可用选项: clarity(清晰度), specificity(具体性), structure(结构), context(上下文), actionable(可执行性), conciseness(简洁性), examples(示例), format(格式)"
          },
          style: {
            type: "string",
            description: "优化后提示词的期望风格 (例如: 'formal(正式)', 'casual(随意)', 'technical(技术性)', 'creative(创意性)')"
          }
        },
        required: ["originalPrompt"]
      }
    };
  • index.ts:385-387 (registration)
    Registers the optimize_prompt tool by including it in the response to ListToolsRequest.
    server.setRequestHandler(ListToolsRequestSchema, async () => ({
      tools: [OPTIMIZE_PROMPT_TOOL],
    }));
  • MCP CallToolRequest handler that dispatches calls to optimize_prompt, validates input, invokes PromptOptimizer, and formats response.
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      if (request.params.name === "optimize_prompt") {
        try {
          const args = request.params.arguments;
    
          if (!args || typeof args !== 'object' || !('originalPrompt' in args)) {
            throw new Error('缺少必需参数: originalPrompt');
          }
    
          const optimizationRequest: OptimizationRequest = {
            originalPrompt: args.originalPrompt as string,
            context: args.context as string | undefined,
            targetAudience: args.targetAudience as string | undefined,
            optimizationGoals: args.optimizationGoals as OptimizationGoal[] | undefined,
            style: args.style as string | undefined,
          };
    
          const result = await promptOptimizer.optimizePrompt(optimizationRequest);
    
          return {
            content: [{
              type: "text",
              text: JSON.stringify(result, null, 2)
            }]
          };
        } catch (error) {
          return {
            content: [{
              type: "text",
              text: `优化提示词时出错: ${error instanceof Error ? error.message : String(error)}`
            }],
            isError: true
          };
        }
      }
    
      return {
        content: [{
          type: "text",
          text: `未知工具: ${request.params.name}`
        }],
        isError: true
      };
    });
  • Helper method to analyze the original prompt's quality metrics like length, clarity, specificity, etc., used in optimization.
    private analyzePrompt(prompt: string): PromptAnalysis {
      return {
        length: prompt.length,
        hasContext: prompt.toLowerCase().includes('context') || prompt.toLowerCase().includes('background'),
        hasExamples: prompt.toLowerCase().includes('example') || prompt.toLowerCase().includes('for instance'),
        hasConstraints: prompt.toLowerCase().includes('must') || prompt.toLowerCase().includes('should') || prompt.toLowerCase().includes('requirement'),
        hasFormat: prompt.toLowerCase().includes('format') || prompt.toLowerCase().includes('structure'),
        clarity: this.assessClarity(prompt),
        specificity: this.assessSpecificity(prompt)
      };
    }
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. It states the tool analyzes prompts and applies optimization strategies, but it doesn't describe what the optimization entails (e.g., whether it modifies the prompt in-place, returns suggestions, or requires user confirmation), potential side effects, or any constraints like rate limits or authentication needs. This is a significant gap for a tool with no annotation coverage.

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

Conciseness4/5

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

The description is concise and front-loaded, stating the core purpose in the first sentence and elaborating briefly in the second. Both sentences earn their place by defining the tool's function and scope. It could be slightly more structured (e.g., by mentioning output), but it avoids redundancy and is appropriately sized.

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 (5 parameters, no annotations, no output schema), the description is incomplete. It doesn't explain what the tool returns (e.g., an optimized prompt, a list of suggestions, or a score), how optimizations are applied, or any behavioral traits. For a tool with no structured fields to rely on, this leaves too much ambiguity for effective agent use.

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?

The schema description coverage is 100%, so the schema already documents all 5 parameters thoroughly. The description adds no additional meaning beyond what the schema provides—it doesn't explain parameter interactions, default behaviors, or examples. With high schema coverage, the baseline score of 3 is appropriate, as the description doesn't compensate but also doesn't detract.

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

Purpose4/5

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

The description clearly states the tool's purpose: '优化和增强提示词以获得更好的 AI 交互效果' (optimize and enhance prompts for better AI interaction). It specifies the action (analyze prompts and apply optimization strategies) and the resource (prompts), though it doesn't differentiate from siblings since none exist. The purpose is clear but could be more specific about the output format.

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 on when to use this tool versus alternatives is provided. The description mentions analyzing prompts and applying optimization strategies, but it doesn't specify prerequisites, ideal scenarios, or limitations. Without sibling tools, this is less critical, but the lack of any usage context leaves a gap.

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

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