Skip to content

Commit 16684c8

Browse files
committed
Add MCP integration for stock price retrieval
- Introduced multiple new files for MCP agent functionality, including `mcp-agents-detailed.py`, `mcp-agents.py`, `mcp-basic.py`, `mcp-multiagents.py`, and `mcp-test.py`. - Implemented a dedicated `MCP` class for managing connections and tool execution. - Created an asynchronous function to retrieve stock prices using MCP tools. - Added example agents for stock price checking and web searching. - Updated `pyproject.toml` and `uv.lock` to reflect version increment to 0.0.66. - Ensured backward compatibility and improved tool function generation for better usability.
1 parent bd5c73f commit 16684c8

File tree

9 files changed

+457
-3
lines changed

9 files changed

+457
-3
lines changed
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from praisonaiagents import Agent, MCP
2+
3+
agent = Agent(
4+
instructions="""You are a helpful assistant that can check stock prices and perform other tasks.
5+
Use the available tools when relevant to answer user questions.""",
6+
llm="gpt-4o-mini",
7+
tools=MCP(
8+
command="/Users/praison/miniconda3/envs/mcp/bin/python",
9+
args=["/Users/praison/stockprice/app.py"]
10+
)
11+
)
12+
13+
agent.start("What is the stock price of Tesla?")

src/praisonai-agents/mcp-agents.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from praisonaiagents import Agent, MCP
2+
3+
agent = Agent(
4+
instructions="""You are a helpful assistant that can check stock prices and perform other tasks.
5+
Use the available tools when relevant to answer user questions.""",
6+
llm="gpt-4o-mini",
7+
tools = MCP("/Users/praison/miniconda3/envs/mcp/bin/python /Users/praison/stockprice/app.py")
8+
)
9+
10+
agent.start("What is the stock price of Tesla?")

src/praisonai-agents/mcp-basic.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
import asyncio
2+
from praisonaiagents import Agent
3+
from mcp import ClientSession, StdioServerParameters
4+
from mcp.client.stdio import stdio_client
5+
6+
# Define server configuration - pointing to your stock price app
7+
server_params = StdioServerParameters(
8+
command="/Users/praison/miniconda3/envs/mcp/bin/python",
9+
args=[
10+
"/Users/praison/stockprice/app.py",
11+
],
12+
)
13+
14+
# Function to get stock price using MCP
15+
async def get_stock_price(symbol):
16+
# Start server and connect client
17+
async with stdio_client(server_params) as (read, write):
18+
async with ClientSession(read, write) as session:
19+
# Initialize the connection
20+
await session.initialize()
21+
22+
# Get tools
23+
tools_result = await session.list_tools()
24+
tools = tools_result.tools
25+
print(f"Available tools: {[tool.name for tool in tools]}")
26+
27+
# Find a tool that can get stock prices
28+
# Assuming there's a tool like "get_stock_price" or similar
29+
stock_tool = None
30+
for tool in tools:
31+
if "stock" in tool.name.lower() or "price" in tool.name.lower():
32+
stock_tool = tool
33+
break
34+
35+
if stock_tool:
36+
print(f"Using tool: {stock_tool.name}")
37+
# Call the tool with the stock symbol
38+
result = await session.call_tool(
39+
stock_tool.name,
40+
arguments={"ticker": symbol}
41+
)
42+
return result
43+
else:
44+
return "No suitable stock price tool found"
45+
46+
# Create a custom tool for the agent
47+
def stock_price_tool(symbol: str) -> str:
48+
"""Get the current stock price for a given symbol"""
49+
# Run the async function to get the stock price
50+
result = asyncio.run(get_stock_price(symbol))
51+
return f"Stock price for {symbol}: {result}"
52+
53+
# Create agent with the stock price tool
54+
agent = Agent(
55+
instructions="You are a helpful assistant that can check stock prices. When asked about stock prices, use the stock_price_tool.",
56+
llm="gpt-4o-mini",
57+
tools=[stock_price_tool]
58+
)
59+
60+
# Start the agent
61+
agent.start("What is the stock price of Tesla?")
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from praisonaiagents import Agent, MCP
2+
3+
stock_agent = Agent(
4+
instructions="""You are a helpful assistant that can check stock prices and perform other tasks.
5+
Use the available tools when relevant to answer user questions.""",
6+
llm="gpt-4o-mini",
7+
tools=MCP(
8+
command="/Users/praison/miniconda3/envs/mcp/bin/python",
9+
args=["/Users/praison/stockprice/app.py"]
10+
)
11+
)
12+
13+
search_agent = Agent(
14+
instructions="""You are a helpful assistant that can search the web for information.
15+
Use the available tools when relevant to answer user questions.""",
16+
llm="gpt-4o-mini",
17+
tools=MCP('npx -y @smithery/cli@latest install @smithery-ai/brave-search --client claude --config "{\"braveApiKey\":\"BSANfDaqLKO9wq7e08mrPth9ZlJvKtc\"}"')
18+
)
19+
20+
stock_agent.start("What is the stock price of Tesla?")
21+
search_agent.start("What is the weather in San Francisco?")

src/praisonai-agents/mcp-test.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import asyncio
2+
import json
3+
from typing import Dict, Any
4+
from mcp import ClientSession, StdioServerParameters
5+
from mcp.client.stdio import stdio_client
6+
7+
# Define server configuration
8+
server_params = StdioServerParameters(
9+
command="/Users/praison/miniconda3/envs/mcp/bin/python",
10+
args=[
11+
"/Users/praison/stockprice/app.py",
12+
],
13+
)
14+
15+
async def execute_tool(session: ClientSession, tool_name: str, params: Dict[str, Any]) -> Any:
16+
"""
17+
Execute a tool with proper error handling and return the result.
18+
19+
This follows the pattern shown in the article for reliable tool execution.
20+
"""
21+
try:
22+
result = await session.call_tool(tool_name, arguments=params)
23+
return result
24+
except Exception as e:
25+
print(f"Error executing tool {tool_name}: {str(e)}")
26+
return {"error": str(e)}
27+
28+
async def main():
29+
# Start server and connect client
30+
async with stdio_client(server_params) as (read, write):
31+
async with ClientSession(read, write) as session:
32+
# Initialize the connection
33+
await session.initialize()
34+
35+
# Get details of available tools
36+
tools_result = await session.list_tools()
37+
tools = tools_result.tools
38+
39+
# Print available tools for debugging
40+
print(f"Available tools: {[tool.name for tool in tools]}")
41+
42+
# Example: Call a tool if it exists
43+
if tools and len(tools) > 0:
44+
# Assuming first tool as an example
45+
tool = tools[0]
46+
print(f"Calling tool: {tool.name}")
47+
print(f"Tool schema: {json.dumps(tool.inputSchema, indent=2)}")
48+
49+
# Create parameters based on the tool's input schema
50+
# This is a simplification - in a real application, you would parse
51+
# the schema and provide appropriate values
52+
params = {}
53+
54+
# For demonstration, we'll check if the tool needs any parameters
55+
if tool.inputSchema and "properties" in tool.inputSchema:
56+
# Just populate with empty values for demonstration
57+
params = {
58+
key: "" for key in tool.inputSchema["properties"].keys()
59+
}
60+
61+
# Call the tool with appropriate parameters
62+
response = await execute_tool(session, tool.name, params)
63+
64+
# Process the response
65+
print(f"Tool response: {response}")
66+
67+
# Run the async function
68+
if __name__ == "__main__":
69+
asyncio.run(main())

src/praisonai-agents/praisonaiagents/__init__.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
from .agents.autoagents import AutoAgents
1111
from .knowledge.knowledge import Knowledge
1212
from .knowledge.chunking import Chunking
13+
from .mcp.mcp import MCP
1314
from .main import (
1415
TaskOutput,
1516
ReflectionOutput,
@@ -51,5 +52,6 @@
5152
'sync_display_callbacks',
5253
'async_display_callbacks',
5354
'Knowledge',
54-
'Chunking'
55+
'Chunking',
56+
'MCP'
5557
]

0 commit comments

Comments
 (0)