Add FastMCP tool for web scrapping.

Add logging info for tools calling
This commit is contained in:
2026-07-29 16:28:15 +09:00
parent e5bb49a596
commit afb10aa52e
8 changed files with 606 additions and 73 deletions
+209 -32
View File
@@ -1,13 +1,20 @@
import json
import os
from langchain_community.utilities import SerpAPIWrapper
from pydantic import BaseModel, Field as PydanticField # Alias it to avoid conflicts
from crewai.tools import tool
from typing import List, Dict, Any
from shared_config import verbose, logger
from shared_config import verbose, logger, useSerpAPI
from crewai import Agent, Task, Crew, Process, LLM, TaskOutput, TaskOutput
from crewai.tools import tool
from langchain_community.tools import DuckDuckGoSearchRun
from langchain_community.utilities import DuckDuckGoSearchAPIWrapper
from datetime import datetime
import os
import requests
import asyncio
from fastmcp.client import Client
from fastmcp.client.transports import StreamableHttpTransport
###########################################################################################
#Define a callback function to log CrewAI step task
@@ -34,25 +41,166 @@ def create_crew(config):
# 1. DEFINE CUSTOM TOOLS & OUTPUT SCHEMAS
# ==========================================
# Simple search tool for the Research Agent
@tool("web_search")
def web_search_tool(query: str) -> str:
"""Search the web for current events, news, or factual information."""
ddg = DuckDuckGoSearchRun()
return ddg.invoke(query)
class ResearchEvidence(BaseModel):
source_url: str = PydanticField(..., description="The source URL of the evidence.")
claim: str = PydanticField(..., description="The factual finding or data point.")
context: str = PydanticField(..., description="The context or time frame of this data point.")
class ResearchOutputSchema(BaseModel):
competitors: List[Dict[str, Any]] = PydanticField(..., description="List of competitors with pricing, features, and target audience.")
market_trends: List[str] = PydanticField(..., description="Key macro trends observed.")
competitors: List[Dict[str, Any]] = PydanticField(..., description="List of competitors with products pricing range, features, and target audience.")
market_trends: List[str] = PydanticField(..., description="Market Analysis & Growth Trends")
evidence_citations: List[ResearchEvidence] = PydanticField(..., description="Valid source citations for facts collected.")
if useSerpAPI:
#Define SerpAPI Search Tool
@tool("Web Search Tool")
def web_search_tool(search_query: str) -> str:
"""
Search Google for real-time information, news, and facts using SerpAPI.
Input should be a simple text search query string.
"""
# Strip potential quotes added by the agent to clean up the query
search_query = search_query.strip("'\"")
if not search_query:
logger.info(f"Web Search tool used. Error: Empty query")
return "Error: Received an empty search query."
url = "https://serpapi.com/search"
payload = {
"q": search_query,
"api_key": os.getenv("SERPAPI_API_KEY"),
"engine": "google",
"num": 10
}
try:
response = requests.get(url, params=payload, timeout=10)
# 1. Check HTTP Status (e.g., 403 Forbidden, 400 Bad Request)
if response.status_code != 200:
logger.info(f"Web Search tool used. API Error (Status {response.status_code}): {response.text}")
return f"API Error (Status {response.status_code}): {response.text}"
# 2. Safely parse JSON
try:
data = response.json()
except ValueError:
logger.info(f"Web Search tool used. Error: Server returned non-JSON data. Raw Response: {response.text[:200]}")
return f"Error: Server returned non-JSON data. Raw Response: {response.text[:200]}"
# 3. Handle backend errors sent inside valid JSON
if "error" in data:
logger.info(f"Web Search tool used. SerpAPI Error: {data['error']}")
return f"SerpAPI Error: {data['error']}"
organic_results = data.get("organic_results", [])
if not organic_results:
logger.info(f"Web Search tool used. No organic results found for query: '{search_query}'")
return f"No organic results found for query: '{search_query}'"
results_summary = []
for result in organic_results:
title = result.get("title")
link = result.get("link")
snippet = result.get("snippet")
results_summary.append(f"Title: {title}\nLink: {link}\nSnippet: {snippet}\n---")
strResult = "\n".join(results_summary)
logger.info(f"""Web Search tool used.\nQuery: {search_query}\nResult:\n{strResult}""")
return strResult
except requests.exceptions.RequestException as e:
logger.info(f"Web Search tool used. Network connection error occurred: {str(e)}")
return f"Network connection error occurred: {str(e)}"
else:
#Define DuckDuckGo Search Tool
@tool("Web Search Tool")
def web_search_tool(query: str) -> str:
"""
Search the web for real-time information, news, and facts using DuckDuckGo and return the structured Title, Link, and Snippet for each result.
Args:
query (str): The search query text.
Returns:
str: Text containing Title, Link, and Snippet fields for each search result.
"""
# Max results set to 5 for optimal context length
api_wrapper = DuckDuckGoSearchAPIWrapper()
try:
# Fetch structured list of dictionaries
results = api_wrapper.results(query, 15)
if not results:
logger.info(f"""Web Search tool used. No search results found for""")
return f"No search results found for: '{query}'"
output = []
for i, res in enumerate(results, start=1):
item_str = (
f"Result #{i}\n"
f"Title: {res.get('title', 'N/A')}\n"
f"Link: {res.get('link', 'N/A')}\n"
f"Snippet: {res.get('snippet', 'N/A')}\n"
f"{'-'*40}"
)
output.append(item_str)
logger.info(f"""Web Search tool used.\nQuery: {query}\nResult:\n{"\n".join(output)}""")
return "\n".join(output)
except Exception as e:
logger.info(f"""Web Search tool used. Error executing search: {str(e)}""")
return f"Error executing search: {str(e)}"
@tool("FastMCP Batch Web Content extraction Tool")
def fastmcp_batch_web_content_extraction_tool(urls: list[str]) -> str:
"""
Connects directly to the FastMCP HTTP server to scrape and extract text from
a list of multiple URLs simultaneously in parallel.
"""
async def call_fast_mcp():
# Initialize client using FastMCP's precise matching transport protocol
transport = StreamableHttpTransport("http://localhost:8000/mcp/")
async with Client(transport) as client:
# call_tool abstracts away deep JSON-RPC structures perfectly
result = await client.call_tool("batch_web_content_extraction", {"urls": urls})
return result
try:
# Spin up clean execution loop for this worker thread
mcp_response = asyncio.run(call_fast_mcp())
# FastMCP Client response objects expose string contents naturally via .content
# Ensure we safely extract the raw text string from the MCP content blocks
if hasattr(mcp_response, "content") and mcp_response.content:
# The text is inside the first content block object
raw_content = mcp_response.content[0].text
else:
# Fallback to string casting if it's already a plain string
raw_content = str(mcp_response)
# Parse JSON and pretty-format the string back to the CrewAI Agent
try:
parsed_data = json.loads(raw_content)
formatted_output = []
for item in parsed_data:
formatted_output.append(f"=== SOURCE URL: {item['url']} ===")
formatted_output.append(f"STATUS: {item['status']}")
formatted_output.append(f"CONTENT:\n{item['content']}\n")
formatted_output.append("=" * 40 + "\n")
logger.info(f"""FastMCP Batch Web Content extraction tool used.\nURLs:\n{"\n".join(urls)}\nResult:\n{"\n".join(formatted_output)}""")
return "\n".join(formatted_output)
except json.JSONDecodeError:
logger.info(f"""FastMCP Batch Web Content extraction tool used. Error in JSON formatting so raw data returned:\nURLs:\n{"\n".join(urls)}\nResult:\n{raw_content}""")
return raw_content
except Exception as e:
logger.info(f"""FastMCP Batch Web Content extraction tool used. Error executing the tool and no data returned.""")
return f"Error executing Parallel FastMCP tool over Streamable HTTP: {str(e)}"
# ---------------------------------------------------------
#Create llm instance
@@ -93,13 +241,14 @@ def create_crew(config):
# 2. researcher
researcher_agent = Agent(
role="Market Research Specialist",
goal="Gather raw competitive intelligence, target audience signals, and pricing tiers with structural citations.",
backstory="An elite OSINT researcher who tracks digital signals. You ignore marketing fluff and extract verifiable numbers, product capabilities, and structural URLs.",
#role='Research Agent',
#goal='Gather comprehensive market data, identify industry trends, and map out the competitive landscape.',
#backstory='You are an elite Market Research Analyst. You are an expert at mining deep web data, extracting customer pain points, and finding precise statistical facts from modern industry reports.',
#goal="Gather raw competitive intelligence, target audience signals, and pricing tiers with structural citations.",
#backstory="An elite OSINT researcher who tracks digital signals. You ignore marketing fluff and extract verifiable numbers, product capabilities, and structural URLs.",
goal ="Gather search market data and extract multiple deep resources simultaneously to speed up workflows. Identify industry trends, pricing tiers, core features, and target customer profiles, while ensuring all data is verifiable with source URLs.",
#goal='Gather search market data and extract multiple deep resources simultaneously to speed up workflows. Identify industry trends, and map out the competitive landscape.',
backstory="""You are an elite Market Research Specialist. You are an expert at mining deep web data and finding precise statistical facts from modern industry reports.
You use your Web Search tool to find matching links, and then pass all relevant URLs at the exact same time into your batch web content extraction tool for immediate, parallel analysis.""",
verbose=verbose,
tools=[web_search_tool],
tools=[web_search_tool, fastmcp_batch_web_content_extraction_tool],
use_system_prompt=False,
llm=llm
)
@@ -136,14 +285,24 @@ def create_crew(config):
# Task 1: Research Agent gathers raw intelligence
research_task = Task(
description=(
"Search the web for the top 3-5 players in the target market: '{query}'. "
"Extract pricing tiers, core feature modules, and target customer profiles. "
"Every single metric or claim MUST have a URL source tracked inside the JSON structure. "
"Do not fabricate any data and do not make assumptions. Only include verifiable facts using working URLs."
"If you cannot find a specific metric, leave it blank and do not fabricate data."
# description=(
# "Search the web for the top 3-5 players in the target market: '{query}'. "
# "Extract pricing tiers, core feature modules, and target customer profiles. "
# "Every single metric or claim MUST have a URL source tracked inside the JSON structure. "
# "Do not fabricate any data and do not make assumptions. Only include verifiable facts using working URLs."
# "If you cannot find a specific metric, leave it blank and do not fabricate data."
description=("""
1. Using your Web Search Tool, search websites for the compagnies related the target market: '{query}'. When sending the search query, do not add any information about the year. It should be the most recent data.
2. Review the result snippets and keep URLs that match the target market. Make sure URLs are not borken or do not redirect to "Not Found" website
3. Collect those URLs into a list and feed them into the 'FastMCP Batch Web Content Extraction Tool' in a single call.
4. Review the returned parallel scrape data and extract following information:
a. List of compagnies with products pricing range, keys features, and target audience. Do not list more than one time a specific compagny.
b. Market Analysis & Growth Trends
c. Evidence citations which include URL, the factual finding or data point and the context or time frame of this data point.
5. Every single metric or claim MUST have a URL source tracked inside the JSON structure.
"""
),
expected_output="A structured JSON file matching the schema with validated competitive rows and strict citation tracking.",
expected_output="A structured JSON file matching the schema and strict citation tracking.",
output_json=ResearchOutputSchema,
agent=researcher_agent
)
@@ -152,10 +311,11 @@ def create_crew(config):
analysis_task = Task(
description=(
"Review the structured JSON output provided by the Research Agent. "
"Construct a detailed markdown competitive landscape table and a pricing matrix. "
"Construct a detailed markdown competitive landscape table and a pricing matrix. Include source URL in the table."
"Perform a comprehensive SWOT, 4P, and 7P analysis based strictly on the evidence compiled."
),
expected_output="A deep-dive analytical report featuring clean markdown tables, a SWOT quadrant, and an exhaustive 4P/7P matrix analysis.",
context=[research_task],
agent=analyst_agent
)
@@ -168,15 +328,32 @@ def create_crew(config):
"Identify high-ROI acquisition channels and detail a 30-60-90 day milestone launch plan."
),
expected_output="An actionable, comprehensive market entry strategy blueprint divided into logical execution phases.",
context=[analysis_task],
agent=strategist_agent
)
# Task 4: Head Planner synthesizes, formats, and exports
compilation_task = Task(
description=(
"Synthesize the outputs from the Research, Analyst, and Strategy agents into a seamless, high-caliber Master GTM Report. "
"Include all research data tables, citations, SWOT/7P strategic matrices, and execution timelines. "
"Include a title that cleary identifies the target market and a subtitle that highlights the core value proposition. "
"""Synthesize the outputs from the Research, Analyst, and Strategy agents into a seamless, high-caliber Master GTM Report.
Include all research data tables, citations, SWOT/7P strategic matrices, and execution timelines.
Include a title and small summary that cleary identifies the target market and highlights the core value proposition. Include the input query '{query}' for reference at the end of the summary.
Include a table of contents.
Include a conclusion and Evidence Citations section at the end.
Ensure the document is formatted for executive-level presentation.
[OUTPUT FORMAT SPECIFICATION]:
Format your entire document exclusively in clean, standard Markdown.
Strict Structural Formatting Rules:
1. DOCUMENT TITLE & SUMMARY: Start immediately with the document title as a level-1 heading (# Title) and your summary sections. Do NOT include numbers on these meta-sections.
2. MAIN SECTIONS & SUBSECTIONS: You must explicitly number all research content headings manually (e.g., "# 1. Competitive Landscape Analysis", "## 1.1 Competitive Landscape Table", "# 2. Go-To-Market Strategy").
3. TABLE OF CONTENTS: Directly after your summary block, include a manually written, clean Markdown Table of Contents listing your explicitly numbered headings. Example:
### Table of Contents
- [1. Competitive Landscape Analysis](#1-competitive-landscape-analysis)
- [1.1 Competitive Landscape Table](#11-competitive-landscape-table)
- [1.2 Pricing Matrix](#12-pricing-matrix)
- [2. Go-To-Market (GTM) Strategy Blueprint](#2-go-to-market-gtm-strategy-blueprint)
4. NO MARKDOWN TOC MARKERS: Do NOT output the text string "[TOC]". Write out the table of contents yourself using bullet points and standard markdown links."""
),
expected_output="Final master GTM document.",
context=[research_task, analysis_task, strategy_task],