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