You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When I create an agent with mcp seems like I cannot decouple agent decleration and message processing.
This causes loosing context in a chat history (every time agent reinitialized).
I couldn't find any example which can support add_history_to_messages=True together with mcpserver with successful context keeping.
example:
class myAgent:
def init(self, config=None, knowledge_base=None):
"""Initialize configuration for DBT connection."""
self.config = config or {}
self.knowledge_base = knowledge_base
# Configuration for connecting to the server
self.server_port = int(os.getenv("MCP_PORT", "8766"))
self.server_host = os.getenv("MCP_HOST", "127.0.0.1")
def process_message(self, message):
"""Process message synchronously by delegating to async method."""
import asyncio
print(f"Processing message synchronously: {message[:50]}...")
try:
# Create a new event loop for this request
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# Run the async method and get the result
result = loop.run_until_complete(self._process_message_async(message))
return result
except Exception as e:
print(f"ERROR in DBTAgent.process_message: {e}")
import traceback
traceback.print_exc()
return f"Error processing message: {str(e)}"
finally:
# Clean up
loop.close()
async def _process_message_async(self, message):
"""Internal async method to process messages with MCPTools."""
print(f"Starting async message processing: {message[:50]}...")
try:
# Define the URL for connecting to the already running MCP server
base_url = f"http://{self.server_host}:{self.server_port}"
sse_url = f"{base_url}/sse"
print(f"Attempting to connect to MCP server at {sse_url}")
try:
# Create MCP server parameters to connect to the remote server
mcp_server_params = StdioServerParameters(
command="npx",
args=[
"-y",
"mcp-remote",
sse_url
]
)
async with MCPTools(server_params=mcp_server_params) as mcp_tools:
print("Successfully connected to MCP server via MCPTools")
# Get model instance based on configuration
model = get_model_instance(self.config)
# Create a fresh agent for each request
print("Creating agent instance...")
self.agent = Agent(
tools=[mcp_tools],
model=model,
instructions=dedent("""\
instructions...."""),
markdown=True,
add_history_to_messages=True,
show_tool_calls=True,
knowledge=self.knowledge_base
)
print("agent created successfully")
# Run the agent with the message
print("Running agent with message...")
try:
response = await asyncio.wait_for(self.agent.arun(message), timeout=60)
print("Agent response received!")
# Extract response content
if hasattr(response, 'content'):
print(f"Response length: {len(response.content)} chars")
return response.content
else:
print("Response has no content attribute")
return str(response)
except asyncio.TimeoutError:
return "The agent's response timed out after 60 seconds. This could indicate the server is running slowly."
except Exception as e:
print(f"ERROR during agent run: {e}")
import traceback
traceback.print_exc()
return f"Error generating response: {str(e)}"
except Exception as conn_error:
print(f"Error establishing MCPTools connection: {conn_error}")
import traceback
traceback.print_exc()
return f"Error connecting to MCP server: {str(conn_error)}"
except Exception as e:
print(f"Error during agent execution: {e}")
import traceback
traceback.print_exc()
return f"Error processing your request: {str(e)}"
Steps to Reproduce
create an agent with mcp server
start a chat interface and check if it can remember previous messages
I expect agent to remember previous messages so it can have a continous conversation with the user.
Actual Behavior
forgets previous messages and asks the same details over and over again loosing context.
Screenshots or Logs (if applicable)
example:
class myAgent:
def init(self, config=None, knowledge_base=None):
"""Initialize configuration for DBT connection."""
self.config = config or {}
self.knowledge_base = knowledge_base
# Configuration for connecting to the server
self.server_port = int(os.getenv("MCP_PORT", "8766"))
self.server_host = os.getenv("MCP_HOST", "127.0.0.1")
def process_message(self, message):
"""Process message synchronously by delegating to async method."""
import asyncio
print(f"Processing message synchronously: {message[:50]}...")
try:
# Create a new event loop for this request
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# Run the async method and get the result
result = loop.run_until_complete(self._process_message_async(message))
return result
except Exception as e:
print(f"ERROR in DBTAgent.process_message: {e}")
import traceback
traceback.print_exc()
return f"Error processing message: {str(e)}"
finally:
# Clean up
loop.close()
async def _process_message_async(self, message):
"""Internal async method to process messages with MCPTools."""
print(f"Starting async message processing: {message[:50]}...")
try:
# Define the URL for connecting to the already running MCP server
base_url = f"http://{self.server_host}:{self.server_port}"
sse_url = f"{base_url}/sse"
print(f"Attempting to connect to MCP server at {sse_url}")
try:
# Create MCP server parameters to connect to the remote server
mcp_server_params = StdioServerParameters(
command="npx",
args=[
"-y",
"mcp-remote",
sse_url
]
)
async with MCPTools(server_params=mcp_server_params) as mcp_tools:
print("Successfully connected to MCP server via MCPTools")
# Get model instance based on configuration
model = get_model_instance(self.config)
# Create a fresh agent for each request
print("Creating agent instance...")
self.agent = Agent(
tools=[mcp_tools],
model=model,
instructions=dedent("""\
instructions...."""),
markdown=True,
add_history_to_messages=True,
show_tool_calls=True,
knowledge=self.knowledge_base
)
print("agent created successfully")
# Run the agent with the message
print("Running agent with message...")
try:
response = await asyncio.wait_for(self.agent.arun(message), timeout=60)
print("Agent response received!")
# Extract response content
if hasattr(response, 'content'):
print(f"Response length: {len(response.content)} chars")
return response.content
else:
print("Response has no content attribute")
return str(response)
except asyncio.TimeoutError:
return "The agent's response timed out after 60 seconds. This could indicate the server is running slowly."
except Exception as e:
print(f"ERROR during agent run: {e}")
import traceback
traceback.print_exc()
return f"Error generating response: {str(e)}"
except Exception as conn_error:
print(f"Error establishing MCPTools connection: {conn_error}")
import traceback
traceback.print_exc()
return f"Error connecting to MCP server: {str(conn_error)}"
except Exception as e:
print(f"Error during agent execution: {e}")
import traceback
traceback.print_exc()
return f"Error processing your request: {str(e)}"
Environment
macos
Possible Solutions (optional)
No response
Additional Context
No response
The text was updated successfully, but these errors were encountered:
I'm facing a similar problem that I don't yet know how to solve. The root of the issue is that some tasks cannot be completed in a single run. If you find a solution or have any feedback on my issue, I would greatly appreciate it.
Description
When I create an agent with mcp seems like I cannot decouple agent decleration and message processing.
This causes loosing context in a chat history (every time agent reinitialized).
I couldn't find any example which can support add_history_to_messages=True together with mcpserver with successful context keeping.
example:
class myAgent:
def init(self, config=None, knowledge_base=None):
"""Initialize configuration for DBT connection."""
self.config = config or {}
self.knowledge_base = knowledge_base
Steps to Reproduce
Agent Configuration (if applicable)
self.agent = Agent(
tools=[mcp_tools],
model=model,
instructions=dedent("""
instructions...."""),
markdown=True,
add_history_to_messages=True,
show_tool_calls=True,
knowledge=self.knowledge_base
)
Expected Behavior
I expect agent to remember previous messages so it can have a continous conversation with the user.
Actual Behavior
forgets previous messages and asks the same details over and over again loosing context.
Screenshots or Logs (if applicable)
example:
class myAgent:
def init(self, config=None, knowledge_base=None):
"""Initialize configuration for DBT connection."""
self.config = config or {}
self.knowledge_base = knowledge_base
Environment
Possible Solutions (optional)
No response
Additional Context
No response
The text was updated successfully, but these errors were encountered: