Skip to content

Commit f29a2e6

Browse files
Update version to 0.1.20 and enhance MCP integration with support for log suppression during subprocess execution. Added documentation for MCP connection examples, progress tracking, and error handling best practices.
1 parent 5e4a015 commit f29a2e6

4 files changed

Lines changed: 385 additions & 6 deletions

File tree

README.md

Lines changed: 333 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1858,6 +1858,339 @@ I need accommodation in Toronto between 15th to 20th of May. Give me 5 options f
18581858
await test_agent(task, model="gpt-5-mini")
18591859
```
18601860

1861+
## 🔌 MCP (Model Context Protocol) Integration
1862+
1863+
TinyAgent provides comprehensive support for connecting to MCP servers with multiple transport types, progress tracking, and robust error handling. MCP allows agents to connect to external tools and services seamlessly.
1864+
1865+
### 🚀 Quick MCP Connection
1866+
1867+
```python
1868+
import asyncio
1869+
from tinyagent import TinyAgent
1870+
1871+
async def basic_mcp_example():
1872+
agent = TinyAgent(model="gpt-5-mini")
1873+
1874+
try:
1875+
# Connect to an MCP server (STDIO transport)
1876+
await agent.connect_to_server(
1877+
command="npx",
1878+
args=["@openbnb/mcp-server-airbnb", "--ignore-robots-txt"]
1879+
)
1880+
1881+
result = await agent.run("Find me hotels in Tokyo for 2 adults")
1882+
print(result)
1883+
finally:
1884+
await agent.close()
1885+
1886+
asyncio.run(basic_mcp_example())
1887+
```
1888+
1889+
### 🎯 Progress Callback Support
1890+
1891+
Track progress from long-running MCP tools with real-time updates:
1892+
1893+
#### Default Progress Callback (Recommended)
1894+
```python
1895+
import asyncio
1896+
from tinyagent import TinyAgent
1897+
1898+
async def progress_example():
1899+
agent = TinyAgent(model="gpt-5-mini")
1900+
1901+
try:
1902+
# Enable default progress callback (logs to agent's logger + stdout)
1903+
await agent.connect_to_server(
1904+
command="python",
1905+
args=["my_slow_mcp_server.py"],
1906+
enable_default_progress_callback=True
1907+
)
1908+
1909+
# Progress updates will be automatically logged during tool execution
1910+
result = await agent.run("Process this large dataset")
1911+
print(result)
1912+
finally:
1913+
await agent.close()
1914+
1915+
asyncio.run(progress_example())
1916+
```
1917+
1918+
#### Custom Progress Callback
1919+
```python
1920+
import asyncio
1921+
from tinyagent import TinyAgent
1922+
1923+
class ProgressTracker:
1924+
def __init__(self, name: str):
1925+
self.name = name
1926+
self.updates = []
1927+
1928+
async def __call__(self, progress: float, total: float = None, message: str = None):
1929+
"""Custom progress callback function."""
1930+
self.updates.append({"progress": progress, "total": total, "message": message})
1931+
1932+
if total and total > 0:
1933+
percentage = (progress / total) * 100
1934+
print(f"🔄 {self.name}: [{percentage:5.1f}%] {message}")
1935+
else:
1936+
print(f"🔄 {self.name}: [Step {progress}] {message}")
1937+
1938+
async def custom_progress_example():
1939+
agent = TinyAgent(model="gpt-5-mini")
1940+
tracker = ProgressTracker("Data Processing")
1941+
1942+
try:
1943+
# Use custom progress callback
1944+
await agent.connect_to_server(
1945+
command="python",
1946+
args=["my_mcp_server.py"],
1947+
progress_callback=tracker
1948+
)
1949+
1950+
result = await agent.run("Analyze this complex dataset")
1951+
print(f"Completed with {len(tracker.updates)} progress updates")
1952+
finally:
1953+
await agent.close()
1954+
1955+
asyncio.run(custom_progress_example())
1956+
```
1957+
1958+
### 🌐 MCP Transport Types
1959+
1960+
TinyAgent supports multiple MCP transport protocols for different deployment scenarios:
1961+
1962+
#### 1. STDIO Transport (Default)
1963+
Best for local development and command-line tools:
1964+
1965+
```python
1966+
# STDIO transport (default)
1967+
await agent.connect_to_server(
1968+
command="python",
1969+
args=["mcp_server.py"],
1970+
env={"API_KEY": "your-key"} # Optional environment variables
1971+
)
1972+
1973+
# Node.js MCP server
1974+
await agent.connect_to_server(
1975+
command="npx",
1976+
args=["@modelcontextprotocol/server-filesystem", "/tmp"]
1977+
)
1978+
1979+
# Python MCP server with arguments
1980+
await agent.connect_to_server(
1981+
command="python",
1982+
args=["-m", "my_mcp_package", "--config", "production.yaml"]
1983+
)
1984+
```
1985+
1986+
#### 2. SSE (Server-Sent Events) Transport
1987+
For web-based MCP servers with HTTP streaming:
1988+
1989+
```python
1990+
from tinyagent.mcp_client import MCPServerConfig
1991+
1992+
# SSE transport configuration
1993+
config = MCPServerConfig(
1994+
name="web_mcp_server",
1995+
transport="sse",
1996+
sse_url="http://localhost:3000/mcp",
1997+
headers={"Authorization": "Bearer your-token"},
1998+
timeout=120.0
1999+
)
2000+
2001+
# Connect using TinyMultiMCPTools directly for SSE
2002+
from tinyagent.mcp_client import TinyMultiMCPTools
2003+
2004+
async def sse_example():
2005+
agent = TinyAgent(model="gpt-5-mini")
2006+
2007+
async with TinyMultiMCPTools([config], agent.logger) as multi_mcp:
2008+
# Use SSE-connected tools
2009+
result = await multi_mcp.call_tool(
2010+
tool_name="web_search",
2011+
arguments={"query": "latest AI news"}
2012+
)
2013+
print(result)
2014+
2015+
asyncio.run(sse_example())
2016+
```
2017+
2018+
#### 3. HTTP Transport
2019+
For RESTful MCP servers:
2020+
2021+
```python
2022+
# HTTP transport configuration
2023+
config = MCPServerConfig(
2024+
name="rest_mcp_server",
2025+
transport="http",
2026+
http_base_url="https://api.example.com/mcp",
2027+
headers={
2028+
"Authorization": "Bearer your-api-token",
2029+
"Content-Type": "application/json"
2030+
},
2031+
timeout=60.0
2032+
)
2033+
2034+
async def http_example():
2035+
agent = TinyAgent(model="gpt-5-mini")
2036+
2037+
async with TinyMultiMCPTools([config], agent.logger) as multi_mcp:
2038+
result = await multi_mcp.call_tool(
2039+
tool_name="process_data",
2040+
arguments={"input": "user data"}
2041+
)
2042+
print(result)
2043+
2044+
asyncio.run(http_example())
2045+
```
2046+
2047+
### 🔄 Multiple MCP Servers
2048+
2049+
Connect to multiple MCP servers simultaneously:
2050+
2051+
```python
2052+
import asyncio
2053+
from tinyagent import TinyAgent
2054+
2055+
async def multi_server_example():
2056+
agent = TinyAgent(model="gpt-5-mini")
2057+
2058+
try:
2059+
# Connect to multiple servers
2060+
await agent.connect_to_server(
2061+
command="npx",
2062+
args=["@openbnb/mcp-server-airbnb"],
2063+
enable_default_progress_callback=True
2064+
)
2065+
2066+
await agent.connect_to_server(
2067+
command="python",
2068+
args=["weather_mcp_server.py"],
2069+
progress_callback=custom_tracker
2070+
)
2071+
2072+
await agent.connect_to_server(
2073+
command="node",
2074+
args=["travel_mcp_server.js"]
2075+
)
2076+
2077+
# All servers' tools are now available
2078+
result = await agent.run("""
2079+
Plan a trip to Tokyo:
2080+
1. Check the weather forecast
2081+
2. Find accommodation options
2082+
3. Suggest travel routes
2083+
""")
2084+
2085+
print(result)
2086+
finally:
2087+
await agent.close()
2088+
2089+
asyncio.run(multi_server_example())
2090+
```
2091+
2092+
### 🛠️ Advanced MCP Configuration
2093+
2094+
#### Tool Filtering
2095+
Control which MCP tools are available:
2096+
2097+
```python
2098+
# Include only specific tools
2099+
await agent.connect_to_server(
2100+
command="python",
2101+
args=["comprehensive_mcp_server.py"],
2102+
include_tools=["search", "analyze", "export"], # Only these tools
2103+
enable_default_progress_callback=True
2104+
)
2105+
2106+
# Exclude specific tools
2107+
await agent.connect_to_server(
2108+
command="python",
2109+
args=["mcp_server.py"],
2110+
exclude_tools=["delete", "admin"], # Skip these tools
2111+
progress_callback=tracker
2112+
)
2113+
```
2114+
2115+
#### Environment Variables
2116+
Pass configuration to MCP servers:
2117+
2118+
```python
2119+
await agent.connect_to_server(
2120+
command="python",
2121+
args=["configurable_mcp_server.py"],
2122+
env={
2123+
"API_BASE_URL": "https://api.production.com",
2124+
"API_KEY": os.getenv("PRODUCTION_API_KEY"),
2125+
"LOG_LEVEL": "INFO",
2126+
"RATE_LIMIT": "1000"
2127+
},
2128+
enable_default_progress_callback=True
2129+
)
2130+
```
2131+
2132+
### 📊 Progress Callback Features
2133+
2134+
Progress callbacks provide detailed insights into long-running operations:
2135+
2136+
**Default Progress Callback Features:**
2137+
- ✅ Automatic logging to TinyAgent's logger
2138+
- ✅ Console output with progress bars
2139+
- ✅ Consistent formatting
2140+
- ✅ Error handling
2141+
2142+
**Custom Progress Callback Capabilities:**
2143+
- 🎯 Custom progress tracking and storage
2144+
- 📈 Real-time progress visualization
2145+
- 🔔 Progress-based notifications
2146+
- 📊 Performance metrics collection
2147+
- 🎨 Custom UI integration
2148+
2149+
### 🚨 Error Handling & Best Practices
2150+
2151+
```python
2152+
import asyncio
2153+
import logging
2154+
from tinyagent import TinyAgent
2155+
2156+
async def robust_mcp_example():
2157+
agent = TinyAgent(model="gpt-5-mini")
2158+
2159+
try:
2160+
# Configure with timeouts and error handling
2161+
await agent.connect_to_server(
2162+
command="python",
2163+
args=["reliable_mcp_server.py"],
2164+
enable_default_progress_callback=True,
2165+
env={"TIMEOUT": "300"} # 5 minute timeout
2166+
)
2167+
2168+
# Handle potential tool failures gracefully
2169+
result = await agent.run("""
2170+
Process this data with error handling:
2171+
1. Validate input data
2172+
2. Process with retry logic
2173+
3. Export results with verification
2174+
""")
2175+
2176+
except Exception as e:
2177+
logging.error(f"MCP operation failed: {e}")
2178+
# Implement fallback logic
2179+
result = "Operation failed, using fallback approach"
2180+
finally:
2181+
await agent.close()
2182+
2183+
asyncio.run(robust_mcp_example())
2184+
```
2185+
2186+
**Best Practices:**
2187+
1. 🕐 **Set appropriate timeouts** for long-running operations
2188+
2. 🔄 **Use progress callbacks** to monitor MCP tool execution
2189+
3. 🛡️ **Implement error handling** for network and server failures
2190+
4. 📝 **Filter tools** to expose only what's needed
2191+
5. 🔐 **Secure credentials** using environment variables
2192+
6. 🧹 **Always close agents** to clean up MCP connections
2193+
18612194
## 🔒 Cross-Platform Sandboxing & Security
18622195

18632196
TinyAgent provides comprehensive cross-platform sandboxing with multiple provider options for secure code execution. Choose the best sandbox for your platform and requirements:

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ tinyagent = ["prompts/*.yaml"]
1212

1313
[project]
1414
name = "tinyagent-py"
15-
version = "0.1.19"
15+
version = "0.1.20"
1616
description = "🛠️ Build your own AI coding assistant with any model you want. Revolutionary agent framework with secure sandboxed execution, parallel subagents, and freedom to choose any LLM provider - OpenAI, Anthropic, Ollama, or 100+ others."
1717
readme = "README.md"
1818
authors = [

0 commit comments

Comments
 (0)