Skip to content

How do i connect to MCP? #133

@karim1007

Description

@karim1007
import asyncio
from contextlib import asynccontextmanager
from langchain_mcp_adapters.client import MultiServerMCPClient
from langgraph.prebuilt import create_react_agentimport os
from whatsapp import create_whatsapp_graph
from dotenv import load_dotenv
from langchain_together import ChatTogether
from langgraph_supervisor import create_supervisor

# Load environment variables
load_dotenv()



# Initialize the model
model = ChatTogether(
    model="meta-llama/Llama-3.3-70B-Instruct-Turbo-Free",
    api_key=os.getenv("TOGETHER_API_KEY")
)


@asynccontextmanager
async def create_whatsapp_graph():
    logger.info("Initializing WhatsApp MCP client")
    try:
        async with MultiServerMCPClient(
            {
                "whatsapp": {
                    "command": "C:\\Users\\PC\\AppData\\Local\\Programs\\Python\\Python310\\Scripts\\uv.exe",
                    "args": ["--directory", "C:\\Users\\PC\\Desktop\\test\\whatsapp-mcp\\whatsapp-mcp-server", "run", "main.py"],
                    "transport": "stdio",
                }
            }
        ) as client:
            logger.info("MCP client connection established")
            # Create the agent with MCP tools
            agent = create_react_agent(model, client.get_tools(),name="whatsapp")
            logger.info("React agent created successfully")
            yield agent
    except Exception as e:
        logger.error(f"Error in WhatsApp graph creation: {str(e)}", exc_info=True)
        raise









async def setup_supervised_workflow():
    """Set up and return the supervised workflow with all agents"""
    try:
        # Initialize all agents
        learning_planner = create_learning_planner_graph()
        logger.info("Learning planner agent initialized")

        async with create_whatsapp_graph() as whatsapp_agent, \
                 
            
            # Create the supervisor workflow
            workflow = create_supervisor(
                [whatsapp_agent],
                model=model,
                prompt=(
                    "You are a team supervisor managing 1 specialized agent:\n"
                   
                    "1. whatsapp_agent: For handling WhatsApp messaging\n"
               
            
                    "- Use whatsapp_agent for sending messages and managing WhatsApp communications\n"
                ),
                output_mode="full_history"  # Keep full conversation history
            )

            # Compile the workflow
            app = workflow.compile()
            logger.info("Supervisor workflow compiled successfully")
            
            return app

    except Exception as e:
        logger.error(f"Error setting up supervised workflow: {str(e)}", exc_info=True)
        raise

async def main():
    try:
        # Set up the supervised workflow
        app = await setup_supervised_workflow()
        logger.info("Supervised workflow initialized")

        # Example of how to use the supervised workflow
        result = await app.ainvoke({
            "messages": [
                {
                    "role": "system",
                    "content": "You are a helpful assistant that coordinates between calendar, WhatsApp agents"
                },
                {
                    "role": "user",
                    "content": "send a message to +xxx saying 'we made it!'"
                }
            ]
        })
        print(result)  # Print the result of the workflow invocation
        # Keep the application running
        await asyncio.Event().wait()
        
    except KeyboardInterrupt:
        logger.info("Application terminated by user")
    except Exception as e:
        logger.error(f"Application error: {str(e)}", exc_info=True)

if __name__ == "__main__":
    asyncio.run(main())

when I invoke the whatsapp agent alone it works and sends the message but when I try to use it with a supervisor agent it cannot even recall the tools that it has; it hallucinates fake tools
FYI: I tried it out with multiple mcp servers (google calendar , SQL. etc...)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions