M4: Tavily parity + MCP — /search/contents and MCP web_search/fetch_url
- pipeline.search_contents: search then render+extract all results in parallel; per-URL failures degrade to content:null + failed_urls instead of failing the request - REST: POST /search/contents (Tavily-like full flow with trace) - MCP server (streamable HTTP, stateless) mounted at /mcp on the orchestrator; tools web_search (with optional full content) and fetch_url share the exact pipeline + caches as REST Verified: /search/contents end-to-end with parallel scrapes; MCP tool listing and both tool calls via the official Python MCP client. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
parent
53f0d50e7a
commit
a70a6b5f5f
3 changed files with 118 additions and 1 deletions
|
|
@ -9,6 +9,7 @@ from pydantic import BaseModel
|
||||||
from . import config, pipeline
|
from . import config, pipeline
|
||||||
from .cache import Cache
|
from .cache import Cache
|
||||||
from .logging_setup import setup
|
from .logging_setup import setup
|
||||||
|
from .mcp_server import mcp, runtime
|
||||||
|
|
||||||
log = setup()
|
log = setup()
|
||||||
|
|
||||||
|
|
@ -17,12 +18,16 @@ log = setup()
|
||||||
async def lifespan(app: FastAPI):
|
async def lifespan(app: FastAPI):
|
||||||
app.state.client = httpx.AsyncClient()
|
app.state.client = httpx.AsyncClient()
|
||||||
app.state.cache = Cache(config.REDIS_URL)
|
app.state.cache = Cache(config.REDIS_URL)
|
||||||
yield
|
runtime["client"] = app.state.client
|
||||||
|
runtime["cache"] = app.state.cache
|
||||||
|
async with mcp.session_manager.run():
|
||||||
|
yield
|
||||||
await app.state.cache.close()
|
await app.state.cache.close()
|
||||||
await app.state.client.aclose()
|
await app.state.client.aclose()
|
||||||
|
|
||||||
|
|
||||||
app = FastAPI(title="LWSS Orchestrator", lifespan=lifespan)
|
app = FastAPI(title="LWSS Orchestrator", lifespan=lifespan)
|
||||||
|
app.mount("/mcp", mcp.streamable_http_app())
|
||||||
|
|
||||||
|
|
||||||
class ScrapeRequest(BaseModel):
|
class ScrapeRequest(BaseModel):
|
||||||
|
|
@ -69,6 +74,22 @@ async def search(req: SearchRequest) -> dict:
|
||||||
return {"results": results, "trace": trace.as_dict()}
|
return {"results": results, "trace": trace.as_dict()}
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/search/contents")
|
||||||
|
async def search_contents(req: SearchRequest) -> dict:
|
||||||
|
try:
|
||||||
|
data = await pipeline.search_contents(app.state.client, req.query, req.max_results, app.state.cache)
|
||||||
|
except pipeline.StageError as exc:
|
||||||
|
log.error("search/contents failed at %s: %s", exc.stage, exc.detail)
|
||||||
|
raise HTTPException(status_code=502, detail={"stage": exc.stage, "error": exc.detail}) from exc
|
||||||
|
log.info(
|
||||||
|
"search/contents %r -> %d results (%d failed)",
|
||||||
|
req.query,
|
||||||
|
len(data["results"]),
|
||||||
|
len(data["failed_urls"]),
|
||||||
|
)
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
@app.post("/scrape")
|
@app.post("/scrape")
|
||||||
async def scrape(req: ScrapeRequest) -> dict:
|
async def scrape(req: ScrapeRequest) -> dict:
|
||||||
if not req.url.startswith(("http://", "https://")):
|
if not req.url.startswith(("http://", "https://")):
|
||||||
|
|
|
||||||
54
services/orchestrator/app/mcp_server.py
Normal file
54
services/orchestrator/app/mcp_server.py
Normal file
|
|
@ -0,0 +1,54 @@
|
||||||
|
"""MCP server: the primary interface. Tools call the same pipeline as REST.
|
||||||
|
|
||||||
|
Mounted into the FastAPI app at /mcp (streamable HTTP, stateless).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
|
||||||
|
from mcp.server.fastmcp import FastMCP
|
||||||
|
|
||||||
|
from . import pipeline
|
||||||
|
|
||||||
|
# Populated by main.py's lifespan with the shared httpx client + cache.
|
||||||
|
runtime: dict = {"client": None, "cache": None}
|
||||||
|
|
||||||
|
mcp = FastMCP(
|
||||||
|
"local-web-search",
|
||||||
|
instructions=(
|
||||||
|
"Private, self-hosted web search and page fetching. web_search returns "
|
||||||
|
"ranked open-web results (optionally with full page content); fetch_url "
|
||||||
|
"returns the cleaned text of a single page. Content is mechanically "
|
||||||
|
"extracted (boilerplate stripped); rank/filter relevance yourself."
|
||||||
|
),
|
||||||
|
streamable_http_path="/",
|
||||||
|
stateless_http=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _compact(trace: dict) -> dict:
|
||||||
|
return {"total_ms": round(sum(s["ms"] for s in trace["stages"]), 1), "degraded": trace["degraded"]}
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def web_search(query: str, max_results: int = 5, include_content: bool = True) -> str:
|
||||||
|
"""Search the web. Returns ranked results as JSON: url, title, snippet, and
|
||||||
|
(when include_content is true) the cleaned full text of each page."""
|
||||||
|
client, cache = runtime["client"], runtime["cache"]
|
||||||
|
if include_content:
|
||||||
|
data = await pipeline.search_contents(client, query, max_results, cache)
|
||||||
|
results, trace = data["results"], data["trace"]
|
||||||
|
else:
|
||||||
|
trace_obj = pipeline.Trace()
|
||||||
|
results = await pipeline.search(client, query, max_results, trace_obj)
|
||||||
|
trace = trace_obj.as_dict()
|
||||||
|
return json.dumps({"results": results, "meta": _compact(trace)})
|
||||||
|
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def fetch_url(url: str) -> str:
|
||||||
|
"""Fetch one URL (with JS rendering) and return its cleaned text content,
|
||||||
|
title, and metadata as JSON."""
|
||||||
|
client, cache = runtime["client"], runtime["cache"]
|
||||||
|
result = await pipeline.scrape_url(client, url, cache)
|
||||||
|
trace = result.pop("trace")
|
||||||
|
return json.dumps({**result, "meta": _compact(trace)})
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
"""Pipeline stages and tracing. The orchestrator owns sequencing + degradation."""
|
"""Pipeline stages and tracing. The orchestrator owns sequencing + degradation."""
|
||||||
|
|
||||||
|
import asyncio
|
||||||
import time
|
import time
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
|
|
@ -111,3 +112,44 @@ async def scrape_url(client: httpx.AsyncClient, url: str, cache: Cache | None =
|
||||||
if cache and result["content"] and not result["thin"]:
|
if cache and result["content"] and not result["thin"]:
|
||||||
await cache.set_json(cache_key, result, config.EXTRACT_CACHE_TTL)
|
await cache.set_json(cache_key, result, config.EXTRACT_CACHE_TTL)
|
||||||
return {**result, "trace": trace.as_dict()}
|
return {**result, "trace": trace.as_dict()}
|
||||||
|
|
||||||
|
|
||||||
|
async def search_contents(
|
||||||
|
client: httpx.AsyncClient, query: str, max_results: int, cache: Cache | None = None
|
||||||
|
) -> dict:
|
||||||
|
"""Tavily-equivalent flow: search, then render+extract the results in parallel.
|
||||||
|
|
||||||
|
Per-URL failures degrade to a result without content instead of failing the
|
||||||
|
whole request.
|
||||||
|
"""
|
||||||
|
trace = Trace()
|
||||||
|
results = await search(client, query, max_results, trace)
|
||||||
|
|
||||||
|
start = time.monotonic()
|
||||||
|
scraped = await asyncio.gather(
|
||||||
|
*(scrape_url(client, r["url"], cache) for r in results), return_exceptions=True
|
||||||
|
)
|
||||||
|
trace.record("contents", (time.monotonic() - start) * 1000)
|
||||||
|
|
||||||
|
out = []
|
||||||
|
failed = []
|
||||||
|
for meta, page in zip(results, scraped):
|
||||||
|
entry = dict(meta)
|
||||||
|
if isinstance(page, StageError):
|
||||||
|
entry.update({"content": None, "error": page.detail})
|
||||||
|
failed.append(meta["url"])
|
||||||
|
elif isinstance(page, BaseException):
|
||||||
|
raise page
|
||||||
|
else:
|
||||||
|
entry.update(
|
||||||
|
{
|
||||||
|
"content": page["content"],
|
||||||
|
"title": page.get("title") or meta["title"],
|
||||||
|
"metadata": page.get("metadata", {}),
|
||||||
|
"final_url": page.get("final_url"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
out.append(entry)
|
||||||
|
if failed:
|
||||||
|
trace.degraded.append("contents")
|
||||||
|
return {"results": out, "failed_urls": failed, "trace": trace.as_dict()}
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue