Repository navigation
Expand file tree
/
Copy path_server.py
More file actions
262 lines (224 loc) · 8.63 KB
/
Copy path_server.py
File metadata and controls
262 lines (224 loc) · 8.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
"""Prefect documentation MCP server backed by OpenAI and TurboPuffer."""
from __future__ import annotations
import json
from typing import Annotated, Any
import httpx
import logfire
from fastmcp import FastMCP
from mcp.types import ToolAnnotations
from openai import AsyncOpenAI, OpenAIError
from pydantic import Field
from turbopuffer import (
APIError,
AsyncTurbopuffer,
AuthenticationError,
NotFoundError,
PermissionDeniedError,
)
from turbopuffer.types.row import Row
from docs_mcp_server._release_notes import ReleaseNotes, fetch_release_notes
from docs_mcp_server._settings import settings
logfire.configure(
service_name="prefect-docs-mcp",
token=settings.logfire.token.get_secret_value() if settings.logfire.token else None,
console=settings.logfire.console,
send_to_logfire=settings.logfire.send_to_logfire,
environment=settings.logfire.environment,
)
# instrument ALL OpenAI clients to capture token usage automatically
logfire.instrument_openai(AsyncOpenAI)
app = FastMCP("Prefect Docs MCP", version="0.1.0")
SEARCH_TOOL_ANNOTATIONS = ToolAnnotations(
title="Search Prefect Documentation",
readOnlyHint=True,
openWorldHint=False,
destructiveHint=False,
)
RELEASE_NOTES_TOOL_ANNOTATIONS = ToolAnnotations(
title="Get Prefect Release Notes",
readOnlyHint=True,
openWorldHint=False,
destructiveHint=False,
)
def _build_response(
query: str, results: list[dict[str, Any]], error: str | None = None
) -> dict[str, Any]:
"""build a response payload for the search tool."""
payload: dict[str, Any] = {
"query": query,
"namespace": settings.turbopuffer.namespace,
"results": results,
}
if error:
payload["error"] = error
return payload
@app.tool(annotations=SEARCH_TOOL_ANNOTATIONS)
async def search_prefect(
query: Annotated[
str,
Field(
description=(
"a search query to find relevant document excerpts from Prefect's knowledgebase"
)
),
],
top_k: Annotated[
int | None,
Field(
ge=1,
le=20,
description="How many document excerpts to return.",
),
] = None,
) -> dict[str, Any]:
"""Search Prefect documentation for concepts, examples, and best practices.
Returns ranked excerpts from Prefect's knowledge base for a natural-language
query.
"""
if not query.strip():
raise ValueError("Query must not be empty.")
if settings.turbopuffer.api_key is None:
return _build_response(
query,
[],
"TurboPuffer is not configured; set TURBOPUFFER_API_KEY to use documentation search.",
)
result_limit = top_k or settings.top_k
include_attributes = list(dict.fromkeys(settings.include_attributes))
with logfire.span(
"search_prefect",
query=query,
top_k=result_limit,
namespace=settings.turbopuffer.namespace,
query_length=len(query),
) as span:
try:
with logfire.span("vector_query", top_k=result_limit) as vq_span:
async with AsyncTurbopuffer(
region=settings.turbopuffer.region,
api_key=settings.turbopuffer.api_key.get_secret_value(),
) as client:
namespace = client.namespace(settings.turbopuffer.namespace)
async with AsyncOpenAI() as openai_client:
embedding = await openai_client.embeddings.create(
input=query, model="text-embedding-3-small", timeout=60
)
response = await namespace.query(
rank_by=("vector", "ANN", embedding.data[0].embedding),
top_k=result_limit,
include_attributes=include_attributes,
)
rows_returned = len(response.rows or [])
vq_span.set_attribute("rows_returned", rows_returned)
vq_span.set_attribute("partial_results", rows_returned < result_limit)
except NotFoundError:
rows: list[Row] = []
span.set_attribute("error_type", "not_found")
except (AuthenticationError, PermissionDeniedError) as exc:
span.set_attribute("error_type", "authentication")
span.record_exception(exc)
return _build_response(
query, [], f"TurboPuffer authentication error: {exc}"
)
except APIError as exc:
span.set_attribute("error_type", "api_error")
span.record_exception(exc)
return _build_response(query, [], f"TurboPuffer API error: {exc}")
except OpenAIError as exc:
span.set_attribute("error_type", "openai_error")
span.record_exception(exc)
return _build_response(query, [], f"OpenAI error: {exc}")
except ValueError as exc:
span.set_attribute("error_type", "config_error")
span.record_exception(exc)
return _build_response(
query,
[],
"TurboPuffer configuration error. Ensure API key and namespace are set.",
)
else:
rows = list(response.rows or [])
results: list[dict[str, Any]] = []
scores: list[float] = []
with logfire.span("format_response", result_count=len(rows)):
for row in rows:
data = row_to_dict(row)
snippet = data.get("text") or data.get("content")
# no slicing - content is already chunked at ingestion time
snippet_text = str(snippet) if snippet else ""
score = normalize_score(
data.get("$dist") # turbopuffer returns distance as $dist
or data.get("score")
or data.get("distance")
or data.get("similarity")
)
if score is not None:
scores.append(score)
result_payload: dict[str, Any] = {
"snippet": snippet_text,
"id": data.get("id"),
"score": score,
}
metadata: dict[str, Any] | None = (
data.get("metadata")
if isinstance(data.get("metadata"), dict)
else None
)
title = data.get("title") or (metadata or {}).get("title")
link = data.get("link") or (metadata or {}).get("link")
if title:
result_payload["title"] = title
if link:
result_payload["link"] = link
if metadata:
result_payload["metadata"] = metadata
results.append(result_payload)
span.set_attribute("result_count", len(results))
span.set_attribute("success", True)
# add score statistics for dashboard analysis
if scores:
span.set_attribute("score_min", min(scores))
span.set_attribute("score_max", max(scores))
span.set_attribute("score_avg", sum(scores) / len(scores))
response = _build_response(query, results)
logfire.force_flush()
return response
@app.tool(annotations=RELEASE_NOTES_TOOL_ANNOTATIONS)
async def get_release_notes(
version: Annotated[
str,
Field(
description=(
"'latest' for the latest stable Prefect OSS release, or an exact "
"version such as '3.7.8'"
),
examples=["latest", "3.7.8"],
),
] = "latest",
) -> ReleaseNotes:
"""Get authoritative, structured release notes for a Prefect OSS release.
Accepts "latest" or an exact version and returns the release title, date,
Markdown notes, and source URL.
"""
async with httpx.AsyncClient(timeout=30, follow_redirects=True) as client:
return await fetch_release_notes(version, client=client)
def row_to_dict(row: Row) -> dict[str, Any]:
"""normalize turbopuffer row objects to plain dictionaries."""
data = row.model_dump(mode="python")
if row.model_extra:
data.update(row.model_extra)
metadata = data.get("metadata")
if isinstance(metadata, str):
try:
data["metadata"] = json.loads(metadata)
except json.JSONDecodeError:
pass
return data
def normalize_score(value: Any) -> float | None:
"""coerce turbopuffer scores into floats when present."""
if value is None:
return None
try:
return float(value)
except (TypeError, ValueError):
return None