-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_server.py
More file actions
360 lines (298 loc) · 13.2 KB
/
Copy pathmcp_server.py
File metadata and controls
360 lines (298 loc) · 13.2 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
"""MCP server exposing Allure failure + Jira analysis tools for Claude."""
import json
import httpx
from fastmcp import FastMCP
from analyzer import analyze_allure_url, format_report_markdown
from build_report import generate_build_report as build_report_from_urls
from config import resolve_jira_base_url, resolve_jira_token, settings
from jira import get_jira_ticket, search_jira_for_test
mcp = FastMCP(
name="Allure Jira Analyzer",
instructions="""You are connected to the Allure Jira Analyzer MCP server for Magento MFTF test reports.
## Available tools
- `analyze_allure_report` — ONE Allure URL: fetch failures, load test-case JSON for method names, search Jira for open tickets.
- `generate_build_report` — MULTIPLE Allure URLs: produce a CE/EE/B2B build report with known Jira failures and Run-1/Run-2 links.
- `search_jira` — search Jira for one test method name or ticket ID.
- `fetch_jira_ticket` — fetch one Jira issue by key.
## Tool selection (mandatory)
- User provides ONE Allure URL → call `analyze_allure_report`.
- User provides TWO OR MORE Allure URLs, or asks for a "build report" → call `generate_build_report`.
- Do NOT manually summarize Allure data when these tools are available — always call the tool first.
## Credentials
- Jira URL/token are loaded from the server .env by default.
- Only pass `jira_token` or `jira_base_url` if the user explicitly provides overrides.
## Output rules
- For `generate_build_report`: return the tool response VERBATIM in a markdown code block. Do not reformat, summarize, or omit sections.
- For `analyze_allure_report`: present the markdown report, then add a short summary table of failures vs Jira matches.
""",
)
ANALYZE_REPORT_PROMPT = """# Task: Analyze a single Magento MFTF Allure report
You MUST use the `analyze_allure_report` MCP tool. Do not guess or fabricate failure data.
## Input
Allure URL:
{allure_url}
Accepted URL forms:
- `.../allure-report-ce/index.html` (or `-ee`, `-b2b`)
- `.../allure-report-ce/index.html#categories`
- `.../data/suites.json`
## Steps
1. **Call the tool** `analyze_allure_report` with:
- `allure_url`: the URL above (strip `#categories` fragment if needed; the tool handles both)
- `jira_token` / `jira_base_url`: only if the user provided overrides; otherwise omit (loaded from .env)
2. **What the tool does** (for your understanding):
- Fetches `suites.json` from the Allure report
- Extracts all `failed` and `broken` MFTF tests
- For each failure, fetches `data/test-cases/<uid>.json` to get the test method name (`fullName`)
- Searches Jira for **open** tickets matching the method name (e.g. `PageBuilderWorksForEachCatalogProductAttributeTest`) or ticket ID (e.g. `MC-13680`)
3. **Present results** in this order:
a. **Summary** — total scanned, failed, broken, count with Jira tickets
b. **Failure table** — for each failed/broken test:
- Test name
- Status (failed/broken)
- Jira search term used (method name)
- Linked open Jira tickets: `[KEY](url) — summary (status)`
- Note if no open Jira ticket was found or if Jira search errored
c. **Action items** — list tests with no Jira match that may need new tickets
4. **On errors**:
- HTTP 403 on Allure URL → tell user the report may need an auth token (`allure_auth_token`)
- Jira credential error → tell user to set `JIRA_TOKEN` in `.env` or pass token in chat
- Do not invent ticket keys or test names
## Constraints
- Only report **open** Jira tickets returned by the tool.
- Do not skip calling the tool.
"""
BUILD_REPORT_PROMPT = """# Task: Generate an MFTF multi-run Build Report
You MUST use the `generate_build_report` MCP tool. Do not build the report manually.
## Input
Allure URLs (one per line; labels like "CE Run-1:" are OK — extract the URL from each line):
{allure_urls}
## Steps
1. **Parse URLs**
- Split input by newlines
- From each line, extract the `https://...` Allure URL (ignore prefixes like `CE:`, `Run-1:`, `EE Run-2:`)
- Skip empty lines
- Pass all URLs as the `allure_urls` list to the tool
2. **Call the tool** `generate_build_report` with:
- `allure_urls`: list of parsed URLs
- `jira_token` / `jira_base_url`: only if user provided overrides; otherwise omit
3. **What the tool does** (for your understanding):
- Groups URLs by suite: `allure-report-ce` → CE, `allure-report-ee` → EE, `allure-report-b2b` → B2B
- Numbers runs Run-1, Run-2, … within each suite (in the order provided)
- For each run: fetches failures, loads test method names, searches Jira for open tickets
- **Known failures** = Jira tickets linked to tests that fail in EVERY run of that suite
- **Flaky** = remaining failures that differ between runs (shown as Run-1/Run-2 category links)
4. **Output (CRITICAL)**
- Return the tool response **VERBATIM** — copy the entire text exactly as returned
- Wrap it in a markdown code block so formatting is preserved
- Do NOT summarize, rephrase, reorder tickets, or add commentary inside the report
- After the verbatim report, you may add a one-line note if the tool returned an error
## Expected report format
```
Build Report:
_____________________
Functional Tests CE:
N known failures: [ACQE-9660](jira-url), ...
Remaining are flaky as different failures on each run: [Run-1](allure-url#categories), [Run-2](...)
_____________________
Functional Tests EE:
...
_____________________
Functional Tests B2B:
...
```
## Typical input
A full build has 6 URLs: 2× CE, 2× EE, 2× B2B. If fewer URLs are given, still call the tool with what is available.
## On errors
- If tool says Jira credentials required → ask user to set `.env` or provide token
- If HTTP 403 on Allure → ask for `allure_auth_token`
- Never fabricate ticket keys or run links
"""
@mcp.prompt(
name="analyze_allure_report",
description="Analyze a single Allure report for MFTF failures and open Jira tickets",
tags={"allure", "mftf", "jira"},
)
def analyze_allure_report_prompt(allure_url: str) -> str:
"""Predefined prompt to analyze one Allure report URL."""
return ANALYZE_REPORT_PROMPT.format(allure_url=allure_url.strip())
@mcp.prompt(
name="generate_build_report",
description="Generate a CE/EE/B2B build report from multiple Allure URLs (2+ runs)",
tags={"allure", "mftf", "build-report"},
)
def generate_build_report_prompt(allure_urls: str) -> str:
"""Predefined prompt to generate a multi-run build report."""
return BUILD_REPORT_PROMPT.format(allure_urls=allure_urls.strip())
def _jira_credentials_missing() -> str:
return (
"Jira credentials are required. Set JIRA_BASE_URL and JIRA_TOKEN in .env "
"(or mcp.json env), or pass them when calling this tool."
)
@mcp.tool
async def analyze_allure_report(
allure_url: str,
jira_token: str | None = None,
allure_auth_token: str | None = None,
jira_base_url: str | None = None,
) -> str:
"""
Analyze failed and broken MFTF tests from an Allure report URL.
Fetches suites.json (or converts index.html URLs automatically), loads per-test
detail JSON to extract the MFTF method name, then searches Jira for open tickets.
Args:
allure_url: Allure report URL (index.html or .../data/suites.json).
jira_token: Optional Jira PAT. Falls back to JIRA_TOKEN from .env.
allure_auth_token: Optional bearer token if the Allure report is behind auth.
jira_base_url: Optional Jira base URL override. Falls back to JIRA_BASE_URL from .env.
"""
token = resolve_jira_token(jira_token)
base_url = resolve_jira_base_url(jira_base_url)
if not token or not base_url:
return _jira_credentials_missing()
try:
response, method_names = await analyze_allure_url(
allure_url=allure_url,
jira_token=token,
allure_auth_token=allure_auth_token,
jira_base_url=base_url,
search_jira=True,
)
except httpx.HTTPStatusError as e:
return f"Failed to fetch Allure report: HTTP {e.response.status_code}"
except httpx.RequestError as e:
return f"Network error fetching Allure report: {e}"
except Exception as e:
return f"Error analyzing Allure report: {e}"
markdown = format_report_markdown(response, method_names)
payload = {
"summary": response.summary.model_dump(),
"results": [item.model_dump() for item in response.results],
"jira_search_terms": {
item.test.uid: method_names.get(item.test.uid, item.test.mftf_test_name)
for item in response.results
},
}
return f"{markdown}\n\n---\n\n```json\n{json.dumps(payload, indent=2)}\n```"
@mcp.tool
async def search_jira(
test_name: str,
jira_token: str | None = None,
jira_base_url: str | None = None,
) -> str:
"""
Search Jira for open tickets matching an MFTF test name or ticket ID.
Args:
test_name: MFTF test method name (e.g. PageBuilderWorksForEachCatalogProductAttributeTest)
or ticket ID (e.g. MC-13680).
jira_token: Optional Jira PAT. Falls back to JIRA_TOKEN from .env.
jira_base_url: Optional Jira base URL override. Falls back to JIRA_BASE_URL from .env.
"""
token = resolve_jira_token(jira_token)
base_url = resolve_jira_base_url(jira_base_url)
if not token or not base_url:
return _jira_credentials_missing()
try:
tickets = await search_jira_for_test(
mftf_test_name=test_name,
base_url=base_url,
token=token,
)
except ValueError as e:
return str(e)
except httpx.HTTPStatusError as e:
return f"Jira API error: HTTP {e.response.status_code}"
if not tickets:
return f"No open Jira tickets found for `{test_name}`."
lines = [f"# Jira results for `{test_name}`", ""]
for ticket in tickets:
lines.append(f"- [{ticket.key}]({ticket.url}) — **{ticket.summary}**")
lines.append(f" - Status: {ticket.status}")
if ticket.description:
lines.append(f" - Description: {ticket.description[:300]}")
return "\n".join(lines)
@mcp.tool
async def fetch_jira_ticket(
ticket_key: str,
jira_token: str | None = None,
jira_base_url: str | None = None,
) -> str:
"""
Fetch a single Jira ticket by key.
Args:
ticket_key: Jira issue key (e.g. MC-13680).
jira_token: Optional Jira PAT. Falls back to JIRA_TOKEN from .env.
jira_base_url: Optional Jira base URL override. Falls back to JIRA_BASE_URL from .env.
"""
token = resolve_jira_token(jira_token)
base_url = resolve_jira_base_url(jira_base_url)
if not token or not base_url:
return _jira_credentials_missing()
try:
ticket = await get_jira_ticket(
ticket_key=ticket_key,
base_url=base_url,
token=token,
)
except ValueError as e:
return str(e)
except httpx.HTTPStatusError as e:
return f"Jira returned HTTP {e.response.status_code} for {ticket_key}"
lines = [
f"# {ticket.key}",
"",
f"- **Summary:** {ticket.summary}",
f"- **Status:** {ticket.status}",
f"- **URL:** {ticket.url}",
]
if ticket.description:
lines.extend(["", "**Description:**", ticket.description])
return "\n".join(lines)
@mcp.tool
async def generate_build_report(
allure_urls: list[str],
jira_token: str | None = None,
allure_auth_token: str | None = None,
jira_base_url: str | None = None,
) -> str:
"""
Generate a multi-run MFTF build report from multiple Allure report URLs.
Use this tool when the user asks for a "build report" or pastes multiple
Allure URLs for CE, EE, and/or B2B runs. URLs are auto-grouped by suite
(allure-report-ce / -ee / -b2b) and numbered Run-1, Run-2 within each group.
Returns the build report markdown. Present the returned text verbatim to the user.
Args:
allure_urls: List of Allure report URLs (index.html or suites.json).
jira_token: Optional Jira PAT. Falls back to JIRA_TOKEN from .env.
allure_auth_token: Optional bearer token if reports are behind auth.
jira_base_url: Optional Jira base URL override. Falls back to JIRA_BASE_URL from .env.
"""
if not allure_urls:
return "Provide at least one Allure report URL."
try:
return await build_report_from_urls(
allure_urls=allure_urls,
jira_token=jira_token,
allure_auth_token=allure_auth_token,
jira_base_url=jira_base_url,
)
except ValueError as e:
return str(e)
except httpx.HTTPStatusError as e:
return f"Failed to fetch Allure report: HTTP {e.response.status_code}"
except httpx.RequestError as e:
return f"Network error: {e}"
except Exception as e:
return f"Error generating build report: {e}"
@mcp.resource("config://jira")
def jira_config() -> str:
"""Current Jira configuration loaded from environment (token is never exposed)."""
return json.dumps(
{
"jira_base_url": settings.jira_base_url,
"jira_project_keys": settings.project_keys_list,
"jira_token_configured": bool(settings.jira_token),
},
indent=2,
)
if __name__ == "__main__":
mcp.run()