Skip to main content
Glama
gurveeer

MCP Server Gemini

by gurveeer

generate_text

Generate text content using Google Gemini AI models with options for structured JSON output, conversation context, and search grounding.

Instructions

Generate text using Google Gemini with advanced features

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
promptYesThe prompt to send to Gemini
modelNoSpecific Gemini model to usegemini-2.5-flash
systemInstructionNoSystem instruction to guide model behavior
temperatureNoTemperature for generation (0-2)
maxTokensNoMaximum tokens to generate
topKNoTop-k sampling parameter
topPNoTop-p (nucleus) sampling parameter
jsonModeNoEnable JSON mode for structured output
jsonSchemaNoJSON schema as a string for structured output (when jsonMode is true)
groundingNoEnable Google Search grounding for up-to-date information
safetySettingsNoSafety settings as JSON string for content filtering
conversationIdNoID for maintaining conversation context

Implementation Reference

  • The handler function that executes the generate_text tool. It validates inputs using the schema, configures the Gemini API request with optional features like system instructions, JSON mode, grounding, and conversation history, calls the API, and returns the response.
    private async generateText(id: any, args: any): Promise<MCPResponse> {
      try {
        // Validate parameters
        const validatedArgs = Validator.validateToolParams(ToolSchemas.generateText, args);
    
        const model = validatedArgs.model || 'gemini-2.5-flash';
        logger.api(`Generating text with model: ${model}`);
        const modelInfo = GEMINI_MODELS[model as keyof typeof GEMINI_MODELS];
    
        if (!modelInfo) {
          throw new Error(`Unknown model: ${model}`);
        }
    
        // Build generation config
        const generationConfig: any = {
          temperature: validatedArgs.temperature || 0.7,
          maxOutputTokens: validatedArgs.maxTokens || 2048,
          topK: validatedArgs.topK || 40,
          topP: validatedArgs.topP || 0.95
        };
    
        // Add JSON mode if requested
        if (validatedArgs.jsonMode) {
          generationConfig.responseMimeType = 'application/json';
          if (validatedArgs.jsonSchema) {
            try {
              generationConfig.responseSchema = Validator.validateJSON(validatedArgs.jsonSchema);
            } catch (error) {
              logger.error('Invalid JSON schema provided:', error);
              throw new ValidationError('Invalid JSON schema format');
            }
          }
        }
    
        // Build the request
        const requestBody: any = {
          model,
          contents: [
            {
              parts: [
                {
                  text: Validator.sanitizeString(validatedArgs.prompt)
                }
              ],
              role: 'user'
            }
          ],
          generationConfig
        };
    
        // Add system instruction if provided
        if (validatedArgs.systemInstruction) {
          requestBody.systemInstruction = {
            parts: [
              {
                text: Validator.sanitizeString(validatedArgs.systemInstruction)
              }
            ]
          };
        }
    
        // Add safety settings if provided
        if (args.safetySettings) {
          try {
            requestBody.safetySettings =
              typeof args.safetySettings === 'string'
                ? JSON.parse(args.safetySettings)
                : args.safetySettings;
          } catch (error) {
            console.error('Invalid safety settings JSON provided:', error);
          }
        }
    
        // Add grounding if requested and supported
        if (args.grounding && modelInfo.features.includes('grounding')) {
          requestBody.tools = [
            {
              googleSearch: {}
            }
          ];
        }
    
        // Handle conversation context
        if (args.conversationId) {
          const history = this.conversations.get(args.conversationId) || [];
          if (history.length > 0) {
            requestBody.contents = [...history, ...requestBody.contents];
          }
        }
    
        // Call the API using the new SDK format
        const result = await this.genAI.models.generateContent({
          model,
          ...requestBody
        });
        const text = result.text || '';
    
        // Update conversation history if needed
        if (args.conversationId) {
          const history = this.conversations.get(args.conversationId) || [];
          history.push(...requestBody.contents);
          history.push({
            parts: [
              {
                text
              }
            ],
            role: 'model'
          });
          this.conversations.set(args.conversationId, history);
        }
    
        return {
          jsonrpc: '2.0',
          id,
          result: {
            content: [
              {
                type: 'text',
                text
              }
            ],
            metadata: {
              model,
              tokensUsed: result.usageMetadata?.totalTokenCount,
              candidatesCount: result.candidates?.length || 1,
              finishReason: result.candidates?.[0]?.finishReason
            }
          }
        };
      } catch (error) {
        console.error('Error in generateText:', error);
        return {
          jsonrpc: '2.0',
          id,
          error: {
            code: -32603,
            message: error instanceof Error ? error.message : 'Internal error'
          }
        };
      }
    }
  • Zod schema for input validation of generate_text tool parameters, used by Validator.validateToolParams.
    generateText: z.object({
      prompt: z.string().min(1, 'Prompt is required'),
      model: CommonSchemas.geminiModel.optional(),
      systemInstruction: z.string().optional(),
      temperature: CommonSchemas.temperature.optional(),
      maxTokens: CommonSchemas.maxTokens.optional(),
      topK: CommonSchemas.topK.optional(),
      topP: CommonSchemas.topP.optional(),
      jsonMode: z.boolean().optional(),
      jsonSchema: CommonSchemas.jsonSchema.optional(),
      grounding: z.boolean().optional(),
      safetySettings: CommonSchemas.safetySettings.optional(),
      conversationId: CommonSchemas.conversationId.optional()
    }),
  • Tool definition/registration in getAvailableTools() method, returned for tools/list MCP call, including name, description, and input schema.
    {
      name: 'generate_text',
      description: 'Generate text using Google Gemini with advanced features',
      inputSchema: {
        type: 'object',
        properties: {
          prompt: {
            type: 'string',
            description: 'The prompt to send to Gemini'
          },
          model: {
            type: 'string',
            description: 'Specific Gemini model to use',
            enum: Object.keys(GEMINI_MODELS),
            default: 'gemini-2.5-flash'
          },
          systemInstruction: {
            type: 'string',
            description: 'System instruction to guide model behavior'
          },
          temperature: {
            type: 'number',
            description: 'Temperature for generation (0-2)',
            default: 0.7,
            minimum: 0,
            maximum: 2
          },
          maxTokens: {
            type: 'number',
            description: 'Maximum tokens to generate',
            default: 2048
          },
          topK: {
            type: 'number',
            description: 'Top-k sampling parameter',
            default: 40
          },
          topP: {
            type: 'number',
            description: 'Top-p (nucleus) sampling parameter',
            default: 0.95
          },
          jsonMode: {
            type: 'boolean',
            description: 'Enable JSON mode for structured output',
            default: false
          },
          jsonSchema: {
            type: 'string',
            description: 'JSON schema as a string for structured output (when jsonMode is true)'
          },
          grounding: {
            type: 'boolean',
            description: 'Enable Google Search grounding for up-to-date information',
            default: false
          },
          safetySettings: {
            type: 'string',
            description: 'Safety settings as JSON string for content filtering'
          },
          conversationId: {
            type: 'string',
            description: 'ID for maintaining conversation context'
          }
        },
        required: ['prompt']
      }
    },
  • Dispatch case in handleToolCall switch statement that routes 'generate_text' tool calls to the handler method.
    case 'generate_text':
      return await this.generateText(request.id, args);
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. While 'Generate text' implies a read-only operation, the description doesn't address important behavioral aspects like rate limits, authentication requirements, cost implications, error handling, or what constitutes 'advanced features.' The mention of 'Google Gemini' hints at external API usage but lacks specifics.

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 a single, efficient sentence that gets straight to the point without unnecessary words. While it could be more informative, it's appropriately concise and front-loaded with the core functionality. Every word earns its place, though more content would be justified given the tool's complexity.

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?

For a complex tool with 12 parameters, no annotations, and no output schema, the description is inadequate. It doesn't explain what 'advanced features' means, doesn't describe the return format or structure, and provides no context about error conditions, rate limits, or typical use cases. The description fails to compensate for the lack of structured metadata.

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 input schema has 100% description coverage with detailed parameter documentation, so the baseline is 3. The description adds minimal value beyond the schema by mentioning 'advanced features' which vaguely references some parameters like grounding and jsonMode, but doesn't provide meaningful semantic context about how parameters interact or when to use specific combinations.

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

Purpose3/5

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

The description states the tool 'Generate text using Google Gemini with advanced features' which provides a clear verb ('Generate text') and resource ('Google Gemini'). However, it's somewhat vague about what 'advanced features' entails and doesn't distinguish this text generation tool from its sibling tools like 'analyze_image' or 'embed_text' beyond the basic domain difference.

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?

The description provides no guidance on when to use this tool versus alternatives. There's no mention of when to choose this over other text generation methods, when to use specific parameter combinations, or how it relates to sibling tools like 'count_tokens' or 'embed_text' which might be complementary.

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/gurveeer/mcp-server-gemini-pro'

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