Files
mcp-use__mcp-use/docs/python/agent/interactive-chat-patterns.mdx
Pietro Zullo 8348c59a53 docs: reorganize, fix accuracy, and update for agent readability (#1502)
* docs: reorganize navigation and clean up content

- Remove 'Misc' group with misplaced blog posts
- Remove 'Libraries' redirect group from Home nav
- Simplify 'Dev Tools' group (flatten Inspector, CLI, Tunneling)
- Remove individual changelog versions from Python nav (keep summary)
- Remove changelog from TypeScript 'Get Started' group
- Remove tunneling duplicate from Python Development group
- Rewrite mcp101 as clean MCP concepts page (was pitch deck)
- Delete typescript/blog posts (not technical docs)
- Add redirects for deleted blog post URLs

* docs: fix content accuracy and remove sloppy language

- Fix broken python/server/mcp-apps link in home page
- Remove informal pitch-speak from python/server/index.mdx
- Fix grammar error in typescript/server/index.mdx
- Update typescript/client/logging.mdx: remove fake 'coming soon' API code
- Fix non-existent model name gpt-5.1 in typescript quickstart
- Fix mcp_use naming in development contributing guide

* docs: fix incorrect TypeScript server API calls in inspector docs

- Replace server.addTool() with server.tool() (correct mcp-use API)
- Add missing zod import to debugging-chatgpt-apps example

* docs: fix fake model names (gpt-5.1 → gpt-4o) in agent docs

* docs: update model names, fix APIs, and add agent visibility hints

- Replace all deprecated model names with latest: gpt-4.1, gpt-4.1-mini,
  claude-sonnet-4-6, claude-opus-4-7, gemini-2.5-flash across all docs
- Fix TypeScript server.tool() API in installation.mdx (old positional string form)
- Fix TypeScript agent.run() in quickstart.mdx (deprecated string form → object)
- Remove broken manufact.com/docs/llms.txt hidden hints from 5 pages
- Add <Visibility for="agents"> block to mcp101.mdx with install commands,
  key classes, and API signatures for agent-oriented navigation
- Add LangChain provider install note to Python quickstart (mcp-use agent
  requires a separate langchain-* provider package)
- Update model name cards in Python llm-integration.mdx

* docs: clean up remaining stale model names and improve accuracy

- Update supported model lists in Python and TypeScript llm-integration pages
- Fix cost optimization table to use current model IDs
- Update TypeScript agent overview supported providers list

* docs: add LangChain provider install to TypeScript quickstart agent section

The MCPAgent requires a separate @langchain/* provider package; this was
not mentioned before the code example that imports from @langchain/openai.

* docs: update to latest flagship model IDs (May 2026)

- OpenAI: gpt-4.1 → gpt-5.5, gpt-4.1-mini → gpt-5.5-mini
- Google: gemini-2.5-flash → gemini-3.1-flash, gemini-2.5-pro → gemini-3.1-pro
- Groq: llama-3.1-* → llama-4-scout-17b-16e-instruct
- Anthropic (claude-opus-4-7, claude-sonnet-4-6) already current, no change

* docs: replace all em dashes with hyphens

* docs: restore llms.txt hints using Visibility component

* docs: simplify TypeScript logging page to unsupported notice only

* docs: rewrite mcp101 to explain MCP protocol with mcp-use examples and doc links

* docs: remove goal.md

* docs: revert nav changes, keep only Misc group removal and blog redirects

* docs: reorder mcp101 to Server/App -> Client/Inspector -> Agent, restore title

* docs: add code examples for Resources and Prompts in mcp101

* docs: remove em dashes from mcp101

* docs: add MCPClient code examples to mcp101

* docs: add React client example to mcp101

* docs: add agent code examples to mcp101

* docs: expand MCP Apps section in mcp101 with example and links

* docs: restore Contacts, Socials, and Founders sections to mcp101

* docs: add context-setting intro paragraph to mcp101 for new readers

* docs: add MCP stores section to mcp101 intro with Claude, ChatGPT, Cursor

* docs: fix Claude store link

* docs: fix ChatGPT store link

* docs: fix Cursor store link

* docs: replace store Cards with linked image grid

* docs: add captions to store images

* docs: add Notifications to client primitives table in mcp101

* docs: add lead-in paragraph before resource cards at bottom of mcp101

* docs: move resource cards to end of page after Contacts/Socials/Founders

* docs: demote Contacts/Socials/Founders to bold text to remove from TOC

* docs: move Contacts/Socials/Founders to very end of mcp101

* docs: add Resources and Contacts section headers, link official MCP docs

* chore(docs): update site metadata, footer links, and rename mcp_use to mcp-use

* update docs metadata + images

* docs: enhance MCP section by highlighting the reach of MCP stores with 1 billion weekly active users

* api ref
2026-05-14 18:49:06 +02:00

280 lines
8.6 KiB
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: "Interactive Chat Patterns"
description: "Create interactive chat interfaces with persistent conversation memory"
icon: "message-circle"
---
## Building a chat loop
With mcp-use you can build interactive interface where users can have conversations with
your `MCPAgent`, maintaining context and memory across multiple queries.
## Basic chat loop
Here's a basic chat-loop with conversation memory enabled:
<CodeGroup>
```python Python
import asyncio
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from mcp_use import MCPAgent, MCPClient
async def basic_chat_loop():
"""Simple console chat loop with MCPAgent"""
# Load environment variables
load_dotenv()
# MCP server configuration
config = {
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"],
"env": {"DISPLAY": ":1"}
},
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]
}
}
}
# Create client and agent
client = MCPClient(config)
llm = ChatOpenAI(model="gpt-5.5")
agent = MCPAgent(llm=llm,
client=client,
memory_enabled=True, # Enable memory to track conversation history
max_steps=20)
# Some initial messages
print("🤖 MCP Agent Chat")
print("Type 'quit/exit' to exit the chat.")
print("Type 'clear' to clear conversation history")
try:
while True:
user_input = input("\nYou: ")
if user_input.lower() in ['quit', 'exit']:
print("👋 Goodbye!")
break
if user_input.lower() == 'clear':
agent.clear_conversation_history()
print("🧹 Conversation history cleared.")
continue
# Skip empty messages
if not user_input:
continue
try:
print("\n🤖 Assistant: ", end="", flush=True)
response = await agent.run(user_input)
print(response)
except KeyboardInterrupt: # Handle keyboard interrupt
print("\n\n⏸️ Interrupted by user")
break
except Exception as e:
print(f"\n❌ Error: {e}")
print("Please try again or type 'exit' to quit.")
finally:
await client.close_all_sessions()
if __name__ == "__main__":
asyncio.run(basic_chat_loop())
```
</CodeGroup>
## Streaming Chat Loop
Here's a chat loop with streaming responses enabled:
<CodeGroup>
```python Python
import asyncio
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from mcp_use import MCPAgent, MCPClient
async def streaming_chat_loop():
"""Chat loop with streaming responses with MCPAgent"""
# Load environment variables
load_dotenv()
# MCP server configuration
config = {
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"],
"env": {"DISPLAY": ":1"}
}
}
}
# Create client and agent
client = MCPClient(config)
llm = ChatOpenAI(model="gpt-5.5")
agent = MCPAgent(llm=llm,
client=client,
memory_enabled=True, # Enable memory to track conversation history
max_steps=20)
# Some initial messages
print("🤖 MCP Agent Chat (Streaming)")
print("Type 'quit/exit' to exit the chat.")
print("Type 'clear' to clear conversation history")
try:
while True:
user_input = input("\nYou: ")
if user_input.lower() in ['quit', 'exit']:
print("👋 Goodbye!")
break
if user_input.lower() == 'clear':
agent.clear_conversation_history()
print("🧹 Conversation history cleared.")
continue
if not user_input: # Skip empty messages
continue
try:
print("\n🤖 Assistant: ", end="", flush=True)
# Stream the response
async for chunk in agent.stream(user_input):
print(chunk, end="", flush=True)
print()
except KeyboardInterrupt: # Handle keyboard interrupt
print("\n\n⏸️ Interrupted by user")
break
except Exception as e:
print(f"\n❌ Error: {e}")
print("Please try again or type 'exit' to quit.")
finally:
await client.close_all_sessions()
if __name__ == "__main__":
asyncio.run(streaming_chat_loop())
```
</CodeGroup>
## Chat Loop with Structured I/O
It's possible to create a chat loop that can handle both natural language and structured inputs, allowing users to request specific tasks or analyses in a structured format. Here's an example of how to implement this:
<CodeGroup>
```python Python
import asyncio
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from langchain_openai import ChatOpenAI
from mcp_use import MCPAgent, MCPClient
from typing import Optional
class TaskRequest(BaseModel):
task_type: Optional[str] = Field(description="The type of task to perform")
description: Optional[str] = Field(description="Detailed description of the task")
priority: Optional[str] = Field(description="Priority level: low, medium, high")
async def structured_chat_loop():
"""Chat loop that can handle both natural language and structured inputs."""
# Load environment variables
load_dotenv()
# MCP server configuration
config = {
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"],
"env": {"DISPLAY": ":1"}
}
}
}
# Create client and agent
client = MCPClient(config)
llm = ChatOpenAI(model="gpt-5.5")
agent = MCPAgent(
llm=llm,
client=client,
memory_enabled=True, # Enable memory to track conversation history
max_steps=20
)
# Initial messages
print("🤖 MCP Agent Chat (Structured)")
print("You can chat naturally or request structured task analysis")
print("Type 'task' to create a structured task request")
try:
while True:
user_input = input("\nYou: ")
if user_input.lower() in ['exit', 'quit']:
print("👋 Goodbye!")
break
try:
if user_input.lower() == 'task':
print("\n📋 Creating structured task...")
task_description = input("Describe your task: ")
task: TaskRequest = await agent.run(
f"Analyze a task with the following description: {task_description}",
output_schema=TaskRequest
)
# Print task analysis
print(f"\n✅ Task Analysis:")
print(f"• Type: {task.task_type}")
print(f"• Description: {task.description}")
print(f"• Priority: {task.priority or 'low'}")
proceed = input("\nDo you want to proceed with this task? (y/n)")
if proceed.lower() == 'y':
response = await agent.run(
f"Execute the following task: {task.description}"
)
print(f"\n🤖 Assistant: {response}")
else:
# Regular conversation
response = await agent.run(user_input)
print(f"\n🤖 Assistant: {response}")
except KeyboardInterrupt:
print("\n👋 Goodbye!")
break
except Exception as e:
print(f"❌ Error: {e}")
print("Please try again or type 'exit' to quit.")
finally:
await client.close_all_sessions()
if __name__ == "__main__":
asyncio.run(structured_chat_loop())
```
</CodeGroup>
## Next Steps
<CardGroup cols={3}>
<Card title="Agent Configuration" icon="cloud" href="/python/agent/agent-configuration">
Learn more about configuring agents for optimal streaming performance
</Card>
<Card title="Multi-Server Setup" icon="server" href="/python/client/multi-server-setup">
Stream output from agents using multiple MCP servers
</Card>
<Card title="Security Best Practices" icon="shield" href="/python/development/security">
Learn how to secure your MCP deployments
</Card>
</CardGroup>