Skip to content

AgentTalk Integration Guide

Overview

This guide covers the new AgentTalk HTTP handler and the migration of MCP support directly into BasicAgent. These changes provide a more flexible and powerful way to interact with agents via HTTP APIs.

What's New

1. AgentTalk HTTP Handler

A new flexible HTTP endpoint for agent interactions with support for: - Multiple output formats (JSON, HTML, Markdown, Plain Text) - Content-Type negotiation - Dynamic MCP server registration - Integration with OutputMode from AbstractBot.ask() - Session-based conversation management

2. MCP Support in BasicAgent

MCP (Model Context Protocol) functionality has been migrated from MCPEnabledMixin directly into BasicAgent: - All agents now have MCP support built-in - No need for separate MCPAgent class (maintained for backward compatibility) - Simplified API for adding HTTP and local MCP servers - Support for API key, OAuth, and bearer token authentication

File Changes

New Files

  1. parrot/handlers/agent_talk.py
  2. New HTTP handler for flexible agent interaction
  3. Location: parrot/handlers/agent_talk.py

Modified Files

  1. parrot/bots/agent.py (BasicAgent)
  2. Added MCP support methods from MCPEnabledMixin
  3. Now includes: add_mcp_server(), add_http_mcp_server(), add_local_mcp_server(), etc.

  4. parrot/handlers/manager.py (BotManager)

  5. Updated setup() method to register AgentTalk route
  6. New route: POST /api/v1/agents/chat/

  7. parrot/bots/mcp.py (MCPAgent)

  8. Simplified to just inherit from BasicAgent
  9. Maintained for backward compatibility
  10. Now deprecated in favor of using BasicAgent directly

Installation & Setup

1. Add AgentTalk Handler

Create the new file:

# Create the handler file
touch parrot/handlers/agent_talk.py

Copy the AgentTalk class code into this file (see artifacts).

2. Update BasicAgent

Replace or update parrot/bots/agent.py with the new version that includes MCP methods.

3. Update BotManager

In parrot/handlers/manager.py, update the setup() method to include:

from ..handlers.agent_talk import AgentTalk

# In setup() method, add:
router.add_view(
    '/api/v1/agents/chat/',
    AgentTalk
)

4. Update MCPAgent (Optional)

Simplify parrot/bots/mcp.py to just inherit from BasicAgent (see artifacts).

API Endpoints

AgentTalk Endpoint

POST /api/v1/agents/chat/

Request Body:

{
  "agent_name": "MyAgent",
  "query": "Your question here",
  "output_format": "json",  // optional: json, html, markdown, text
  "search_type": "similarity",  // optional
  "return_sources": true,  // optional
  "use_vector_context": true,  // optional
  "mcp_servers": [  // optional: dynamic MCP server registration
    {
      "name": "weather",
      "url": "https://api.weather.com/mcp",
      "auth_type": "api_key",
      "auth_config": {
        "api_key": "your-key",
        "header_name": "X-API-Key"
      }
    }
  ],
  "format_kwargs": {  // optional: formatting options
    "include_sources": true,
    "show_metadata": true
  }
}

Response (JSON format):

{
  "success": true,
  "content": "Agent response content...",
  "metadata": {
    "model": "gpt-4",
    "provider": "openai",
    "session_id": "abc123",
    "response_time": 1.23
  },
  "sources": [...],
  "tool_calls": [...]
}

Response (HTML format): Complete HTML document ready for display in browser.

Response (Markdown/Text format): Plain text response with optional source citations.

Usage Examples

1. Basic JSON Request

import aiohttp
import json

async def ask_agent():
    async with aiohttp.ClientSession() as session:
        url = "http://localhost:8080/api/v1/agents/chat/"

        payload = {
            "agent_name": "MyAssistant",
            "query": "What is AI?",
            "output_format": "json"
        }

        async with session.post(url, json=payload) as resp:
            result = await resp.json()
            print(json.dumps(result, indent=2))

2. HTML Output

async def get_html_response():
    async with aiohttp.ClientSession() as session:
        url = "http://localhost:8080/api/v1/agents/chat/"

        payload = {
            "agent_name": "ReportAgent",
            "query": "Generate Q4 report",
            "output_format": "html"
        }

        async with session.post(url, json=payload) as resp:
            html = await resp.text()

            # Save to file
            with open("report.html", "w") as f:
                f.write(html)

3. Content Negotiation

async def use_accept_header():
    async with aiohttp.ClientSession() as session:
        headers = {"Accept": "text/html"}

        payload = {
            "agent_name": "MyAgent",
            "query": "Explain quantum computing"
        }

        async with session.post(url, json=payload, headers=headers) as resp:
            html = await resp.text()

4. Dynamic MCP Server Registration

async def use_mcp_servers():
    payload = {
        "agent_name": "DataAgent",
        "query": "Get weather in Madrid",
        "mcp_servers": [
            {
                "name": "weather_api",
                "url": "https://api.weather.com/mcp",
                "auth_type": "api_key",
                "auth_config": {
                    "api_key": "your-api-key",
                    "header_name": "X-API-Key"
                }
            }
        ],
        "output_format": "json"
    }

    async with session.post(url, json=payload) as resp:
        result = await resp.json()

MCP Server Integration

Using MCP with BasicAgent

from parrot.bots.agent import BasicAgent

# Create agent
agent = BasicAgent(
    name="MyAgent",
    role="Multi-purpose assistant"
)

await agent.configure()

# Add HTTP MCP server (public)
await agent.add_http_mcp_server(
    name="public_tools",
    url="https://api.example.com/mcp"
)

# Add HTTP MCP server (API key auth)
await agent.add_api_key_mcp_server(
    name="weather",
    url="https://api.weather.com/mcp",
    api_key="your-api-key"
)

# Add local MCP server
await agent.add_local_mcp_server(
    name="file_tools",
    script_path="./mcp_servers/files.py"
)

# List MCP servers
servers = agent.list_mcp_servers()
print(f"Connected: {servers}")

# Get tools from specific server
tools = agent.get_mcp_server_tools("weather")
print(f"Weather tools: {tools}")

MCP Server Configuration Types

1. Public HTTP Server (No Auth)

await agent.add_http_mcp_server(
    name="public",
    url="https://api.example.com/mcp"
)

2. API Key Authentication

await agent.add_api_key_mcp_server(
    name="service",
    url="https://api.service.com/mcp",
    api_key="your-api-key",
    header_name="X-API-Key"  # optional, default: "X-API-Key"
)

3. OAuth Authentication

await agent.add_oauth_mcp_server(
    name="google",
    url="https://mcp.googleapis.com",
    client_id="client-id",
    client_secret="client-secret",
    auth_url="https://accounts.google.com/o/oauth2/auth",
    token_url="https://oauth2.googleapis.com/token",
    scopes=["mcp.read", "mcp.write"],
    user_id="user@example.com"
)

4. Local Stdio Server

await agent.add_local_mcp_server(
    name="local_tools",
    script_path="./servers/tools.py",
    interpreter="python"
)

Output Formats

Supported Formats

  1. JSON (output_format: "json")
  2. Structured response with metadata
  3. Includes sources and tool calls
  4. Best for programmatic access

  5. HTML (output_format: "html")

  6. Complete HTML document
  7. Styled and formatted
  8. Ready for browser display

  9. Markdown (output_format: "markdown")

  10. Plain markdown text
  11. Optional source citations
  12. Good for documentation

  13. Text (output_format: "text")

  14. Plain text output
  15. Simple and clean
  16. No formatting

Format Negotiation

AgentTalk supports format negotiation via:

  1. Explicit parameter: output_format in request body
  2. Query string: ?output_format=html
  3. Accept header: Accept: text/html

Priority: Explicit parameter > Query string > Accept header > Default (JSON)

Webapp Generators Integration

AgentTalk can leverage webapp generators if they're registered as tools:

# If agent has HTMLGenerator, PowerPointGenerator, etc. as tools
payload = {
    "agent_name": "WebDevAgent",
    "query": "Create a todo list web app",
    "output_format": "html"
}

# Agent uses HTMLGenerator tool to create the app
# Returns complete HTML application

Migration Guide

From MCPAgent to BasicAgent

Old Code:

from parrot.bots.mcp import MCPAgent

agent = MCPAgent(name="MyAgent")
await agent.configure()
await agent.add_mcp_server(config)

New Code:

from parrot.bots.agent import BasicAgent

agent = BasicAgent(name="MyAgent")
await agent.configure()
await agent.add_mcp_server(config)

The API is identical - just use BasicAgent instead of MCPAgent.

From ChatHandler to AgentTalk

Old Code:

POST /api/v1/chat/MyBot
{
  "query": "Hello"
}

New Code:

POST /api/v1/agents/chat/
{
  "agent_name": "MyBot",
  "query": "Hello",
  "output_format": "json"
}

Testing

Test the AgentTalk Endpoint

# Create a test agent first via BotManager
curl -X POST http://localhost:8080/api/v1/agents/chat/ \
  -H "Content-Type: application/json" \
  -d '{
    "agent_name": "TestAgent",
    "query": "Hello, world!",
    "output_format": "json"
  }'

Test with MCP Servers

curl -X POST http://localhost:8080/api/v1/agents/chat/ \
  -H "Content-Type: application/json" \
  -d '{
    "agent_name": "MyAgent",
    "query": "Get weather data",
    "mcp_servers": [
      {
        "name": "weather",
        "url": "https://api.weather.com/mcp"
      }
    ],
    "output_format": "json"
  }'

Best Practices

  1. Output Format Selection
  2. Use JSON for APIs and programmatic access
  3. Use HTML for browser display and reports
  4. Use Markdown for documentation
  5. Use Text for simple responses

  6. MCP Server Management

  7. Pre-configure commonly used MCP servers in agent factory functions
  8. Use dynamic registration for user-specific or temporary servers
  9. Always handle MCP connection errors gracefully
  10. Use list_mcp_servers() to verify connections

  11. Authentication

  12. AgentTalk requires authentication (@is_authenticated)
  13. Ensure proper session management
  14. Use secure storage for MCP server credentials

  15. Error Handling

  16. Always check HTTP response status
  17. Handle 404 (agent not found), 401 (auth required), 400 (bad request)
  18. Implement retry logic for transient failures

  19. Performance

  20. Reuse agent instances when possible
  21. Cache MCP server connections
  22. Use connection pooling for HTTP requests

Troubleshooting

Agent Not Found (404)

# Ensure agent is registered with BotManager
manager.add_bot(agent)

# Or use agent_registry
await agent_registry.get_instance("AgentName")

MCP Server Connection Failed

# Check URL and network connectivity
# Verify authentication credentials
# Check MCP server logs

# Test manually:
tools = await agent.add_http_mcp_server(
    name="test",
    url="https://api.example.com/mcp"
)
print(f"Connected tools: {tools}")

Session Required (401)

# Ensure user is authenticated
# Include session cookies in request
# Check @is_authenticated decorator

Invalid Output Format

# Use one of: json, html, markdown, text
# Default is json if not specified

Future Enhancements

Potential future improvements:

  1. Streaming Responses
  2. Support for server-sent events (SSE)
  3. Real-time agent responses

  4. WebSocket Support

  5. Bidirectional communication
  6. Real-time updates

  7. MCP Server Discovery

  8. Automatic discovery of available MCP servers
  9. Registry of public MCP servers

  10. Advanced Caching

  11. Cache agent responses
  12. Cache MCP server tool definitions

  13. Rate Limiting

  14. Per-user rate limits
  15. Per-agent rate limits

Conclusion

The AgentTalk handler provides a modern, flexible way to interact with AI-Parrot agents via HTTP APIs. Combined with built-in MCP support in BasicAgent, it enables powerful integration with external tools and services.

For more examples and advanced usage, see the accompanying example files.