Skip to main content
Glama

AI-Powered Agent Assistant

agent-ai-assist

Provides AI assistance for agent decisions, responses, and analysis within the MCP Agentic Framework. Helps craft message replies, generate status updates, make choices, and analyze situations using context-aware sampling.

Instructions

Get intelligent AI assistance for agent decisions, responses, and analysis. Uses MCP sampling to provide context-aware help. Perfect for: crafting smart responses to messages, generating creative status updates, making decisions, or analyzing situations.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
agent_idYesThe ID of the agent requesting assistance
contextYesThe context or situation requiring AI assistance
request_typeYesType of assistance needed: response (craft message reply), status (generate status), decision (yes/no choice), analysis (situation analysis)

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
successYesWhether the AI assistance was successful
aiGuidanceNoFallback guidance when sampling is not available
aiResponseNoThe AI-generated response or guidance
requestTypeNoThe type of request that was processed
requiresManualExecutionNoWhether manual execution is required (fallback mode)

Implementation Reference

  • Main handler function `agentAiAssist` that implements the tool logic. Validates agent exists, prepares prompts based on request type (response/status/decision/analysis), handles both SSE and stdio MCP sampling modes, and falls back to instruction-based guidance when sampling is unavailable.
    export async function agentAiAssist(agentId, context, requestType) {
      const startTime = Date.now();
      
      try {
        // Verify agent exists
        const agent = await agentRegistry.getAgent(agentId);
        if (!agent) {
          throw Errors.resourceNotFound(`Agent not found: ${agentId}`);
        }
        
        // Prepare prompt based on request type
        let prompt;
        const agentContext = `You are helping agent "${agent.name}" (${agent.id}) - ${agent.description}`;
        
        switch (requestType) {
          case 'response':
            prompt = `${agentContext}\n\nThe agent needs help crafting a response to this situation:\n${context}\n\nProvide a thoughtful, contextually appropriate response the agent could send.`;
            break;
            
          case 'status':
            prompt = `${agentContext}\n\nThe agent needs a creative status update based on:\n${context}\n\nGenerate a short, engaging status message (max 100 chars) that reflects the agent's current activity.`;
            break;
            
          case 'decision':
            prompt = `${agentContext}\n\nThe agent needs help making a decision:\n${context}\n\nAnalyze the situation and provide a clear yes/no recommendation with brief reasoning.`;
            break;
            
          case 'analysis':
            prompt = `${agentContext}\n\nThe agent needs help analyzing this situation:\n${context}\n\nProvide a concise analysis highlighting key insights and suggested actions.`;
            break;
            
          default:
            throw Errors.invalidParams(`Unknown request type: ${requestType}`);
        }
        
        // Check for SSE connection first (for HTTP+SSE mode)
        const sseConnection = global.currentSseConnection;
        const sessionId = global.currentSessionId;
        
        if (sseConnection && sseConnection.connected) {
          // Use SSE for real AI sampling
          return new Promise((resolve, reject) => {
            const requestId = `sampling-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
            
            // Initialize pending requests map if not exists
            if (!global.pendingSamplingRequests) {
              global.pendingSamplingRequests = new Map();
            }
            
            // Set up timeout
            const timeout = setTimeout(() => {
              global.pendingSamplingRequests.delete(requestId);
              reject(Errors.internalError('Sampling request timeout (30s)'));
            }, 30000);
            
            // Store pending request
            global.pendingSamplingRequests.set(requestId, {
              resolve: (result) => {
                clearTimeout(timeout);
                const aiResponse = result.content?.text || result.content || 'Unable to generate AI response';
                
                const metadata = createMetadata(startTime, { 
                  tool: 'agent-ai-assist',
                  requestType,
                  samplingUsed: true,
                  transportType: 'sse'
                });
                
                resolve(structuredResponse(
                  { 
                    success: true, 
                    aiResponse,
                    requestType 
                  },
                  `AI assistance provided for ${requestType} request`,
                  metadata
                ));
              },
              reject: (error) => {
                clearTimeout(timeout);
                
                // If client doesn't support sampling via SSE, fall back to guidance
                if (error.message && error.message.includes('Method not found')) {
                  const instructions = generateAiInstructions(requestType, context, agent);
                  
                  const metadata = createMetadata(startTime, { 
                    tool: 'agent-ai-assist',
                    requestType,
                    fallbackMode: true,
                    fallbackReason: 'Client does not support SSE sampling'
                  });
                  
                  resolve(structuredResponse(
                    { 
                      success: true, 
                      aiGuidance: instructions,
                      requiresManualExecution: true 
                    },
                    `AI assistance instructions generated for ${requestType}. Client does not support SSE sampling.`,
                    metadata
                  ));
                } else {
                  reject(error);
                }
              }
            });
            
            // Send sampling request over SSE
            const samplingParams = {
              modelPreferences: {
                hints: [
                  {
                    name: 'claude-3-haiku-20240307'
                  }
                ],
                intelligenceLevel: 0.5,
                speedLevel: 0.9
              },
              systemPrompt: 'You are an AI assistant helping autonomous agents make intelligent decisions and craft appropriate responses. Be concise and practical.',
              maxTokens: requestType === 'status' ? 50 : 500
            };
            
            sseConnection.sendSamplingRequest(requestId, prompt, samplingParams);
            
            console.log(`Sent sampling request ${requestId} over SSE`);
          });
        }
        
        // Check if MCP server supports sampling (stdio mode)
        if (!mcpServer || !mcpServer.request) {
          // Fallback to instruction-based approach
          const instructions = generateAiInstructions(requestType, context, agent);
          
          const metadata = createMetadata(startTime, { 
            tool: 'agent-ai-assist',
            requestType,
            fallbackMode: true
          });
          
          return structuredResponse(
            { 
              success: true, 
              aiGuidance: instructions,
              requiresManualExecution: true 
            },
            `AI assistance instructions generated for ${requestType}. Please follow the guidance provided.`,
            metadata
          );
        }
        
        // Use MCP sampling to get AI assistance
        const response = await mcpServer.request({
          method: 'sampling/createMessage',
          params: {
            messages: [
              {
                role: 'user',
                content: {
                  type: 'text',
                  text: prompt
                }
              }
            ],
            modelPreferences: {
              hints: [
                {
                  name: 'claude-3-haiku-20240307'
                }
              ],
              intelligenceLevel: 0.5,
              speedLevel: 0.9
            },
            systemPrompt: 'You are an AI assistant helping autonomous agents make intelligent decisions and craft appropriate responses. Be concise and practical.',
            maxTokens: requestType === 'status' ? 50 : 500
          }
        });
        
        const aiResponse = response.content?.text || 'Unable to generate AI response';
        
        const metadata = createMetadata(startTime, { 
          tool: 'agent-ai-assist',
          requestType,
          samplingUsed: true
        });
        
        return structuredResponse(
          { 
            success: true, 
            aiResponse,
            requestType 
          },
          `AI assistance provided for ${requestType} request`,
          metadata
        );
        
      } catch (error) {
        if (error instanceof MCPError) {
          throw error;
        }
        throw Errors.internalError(error.message);
      }
  • Tool schema definition including inputSchema (agent_id, context, request_type) and outputSchema (success, aiResponse, aiGuidance, requiresManualExecution) for the agent-ai-assist tool.
    name: 'agent-ai-assist',
    title: 'AI-Powered Agent Assistant',
    description: 'Get intelligent AI assistance for agent decisions, responses, and analysis. Uses MCP sampling to provide context-aware help. Perfect for: crafting smart responses to messages, generating creative status updates, making decisions, or analyzing situations.',
    inputSchema: {
      $schema: 'http://json-schema.org/draft-07/schema#',
      type: 'object',
      properties: {
        agent_id: {
          type: 'string',
          description: 'The ID of the agent requesting assistance',
          minLength: 1
        },
        context: {
          type: 'string',
          description: 'The context or situation requiring AI assistance',
          minLength: 1,
          maxLength: 5000
        },
        request_type: {
          type: 'string',
          enum: ['response', 'status', 'decision', 'analysis'],
          description: 'Type of assistance needed: response (craft message reply), status (generate status), decision (yes/no choice), analysis (situation analysis)'
        }
      },
      required: ['agent_id', 'context', 'request_type'],
      additionalProperties: false
    },
    outputSchema: {
      $schema: 'http://json-schema.org/draft-07/schema#',
      type: 'object',
      properties: {
        success: {
          type: 'boolean',
          description: 'Whether the AI assistance was successful'
        },
        aiResponse: {
          type: 'string',
          description: 'The AI-generated response or guidance'
        },
        requestType: {
          type: 'string',
          description: 'The type of request that was processed'
        },
        aiGuidance: {
          type: 'object',
          description: 'Fallback guidance when sampling is not available'
        },
        requiresManualExecution: {
          type: 'boolean',
          description: 'Whether manual execution is required (fallback mode)'
        }
      },
      required: ['success'],
      additionalProperties: false
    }
  • Helper function `generateAiInstructions` that provides fallback guidance when MCP sampling is unavailable. Generates context-specific instructions for each request type (response, status, decision, analysis).
    function generateAiInstructions(requestType, context, agent) {
      const baseInstructions = {
        response: {
          title: 'Crafting an Intelligent Response',
          steps: [
            '1. Read the context carefully to understand the situation',
            '2. Consider the agent\'s role and capabilities',
            '3. Draft a response that is:',
            '   - Relevant to the context',
            '   - Consistent with the agent\'s purpose',
            '   - Clear and actionable',
            '4. Keep the response concise but informative'
          ],
          example: 'Example: If asked about data analysis, mention specific capabilities and offer concrete next steps.'
        },
        status: {
          title: 'Creating a Status Update',
          steps: [
            '1. Summarize current activity in 2-5 words',
            '2. Make it descriptive and engaging',
            '3. Keep under 100 characters',
            '4. Reflect the agent\'s current focus'
          ],
          example: 'Examples: "analyzing patterns", "compiling reports", "awaiting input", "processing requests"'
        },
        decision: {
          title: 'Making an Informed Decision',
          steps: [
            '1. List pros and cons based on context',
            '2. Consider the agent\'s goals and constraints',
            '3. Make a clear yes/no choice',
            '4. Provide 1-2 sentences of reasoning'
          ],
          example: 'Example: "Yes, proceed with the analysis. The data is sufficient and aligns with our objectives."'
        },
        analysis: {
          title: 'Analyzing the Situation',
          steps: [
            '1. Identify key elements in the context',
            '2. Note patterns or important relationships',
            '3. Highlight 2-3 main insights',
            '4. Suggest 1-2 actionable next steps'
          ],
          example: 'Example: Identify bottlenecks, opportunities, and risks, then propose specific actions.'
        }
      };
      
      const instructions = baseInstructions[requestType];
      
      return {
        title: instructions.title,
        context: `Agent: ${agent.name} - ${agent.description}`,
        situation: context,
        guidelines: instructions.steps,
        example: instructions.example,
        note: 'Since MCP sampling is not available, please use these guidelines to manually craft your response.'
      };
    }
  • src/server.js:184-188 (registration)
    Registration point in stdio MCP server where the agent-ai-assist tool is routed to the handler function via dynamic import.
    case 'agent-ai-assist': {
      const { agent_id, context, request_type } = args;
      const { agentAiAssist } = await import('./tools.js');
      return await agentAiAssist(agent_id, context, request_type);
    }
  • Registration point in HTTP+SSE server that routes agent-ai-assist calls to the handler, with additional logic to pass SSE connection context for real-time sampling.
    case 'agent-ai-assist': {
      const { agent_id, context, request_type } = args;
      const { agentAiAssist } = await import('./tools.js');
      
      // Check if session has SSE connection
      const sessionId = args._sessionId;
      const sseConnection = sseConnections.get(sessionId);
      
      // Pass SSE connection to the function via global
      if (sseConnection && sseConnection.connected) {
        global.currentSseConnection = sseConnection;
        global.currentSessionId = sessionId;
      }
      
      try {
        return await agentAiAssist(agent_id, context, request_type);
      } finally {
        // Clean up globals
        delete global.currentSseConnection;
        delete global.currentSessionId;
      }
    }
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. While it mentions 'Uses MCP sampling to provide context-aware help,' it doesn't describe important behavioral traits like whether this is a read-only or write operation, authentication requirements, rate limits, or what the output looks like. For a tool with no annotation coverage, this leaves significant gaps in understanding its behavior.

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 appropriately sized with three sentences. It's front-loaded with the core purpose, followed by implementation details and use cases. Each sentence earns its place, though the 'Perfect for:' list could be slightly more concise.

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

Completeness3/5

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

Given that an output schema exists (though not shown), the description doesn't need to explain return values. However, for a tool with no annotations and three required parameters, the description should provide more behavioral context about how the AI assistance works, what kind of output to expect, and any limitations. The current description is adequate but has clear gaps in completeness.

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 already documents all three parameters thoroughly. The description doesn't add any meaningful parameter semantics beyond what's in the schema. It mentions 'context-aware help' which loosely relates to the 'context' parameter, but provides no additional details about parameter usage, constraints, or interactions.

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: 'Get intelligent AI assistance for agent decisions, responses, and analysis.' It specifies the verb ('get assistance') and resource ('agent decisions, responses, and analysis'), though it doesn't explicitly differentiate from sibling tools like 'send-message' or 'update-agent-status' which might also involve AI assistance.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool: 'Perfect for: crafting smart responses to messages, generating creative status updates, making decisions, or analyzing situations.' It lists specific use cases but doesn't explicitly state when NOT to use it or mention alternatives among sibling tools.

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/Piotr1215/mcp-agentic-framework'

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