-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.py
More file actions
252 lines (201 loc) · 8.37 KB
/
demo.py
File metadata and controls
252 lines (201 loc) · 8.37 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
"""
Local demo runner for OpsAgent-MCP.
Runs the full LangGraph pipeline against a fixture log using a mock LLM —
no ANTHROPIC_API_KEY required.
Usage:
# Analyze a specific fixture
.venv/bin/python demo.py
# Pick a different fixture
.venv/bin/python demo.py --fixture oom_killed.log
# List available fixtures
.venv/bin/python demo.py --list
"""
from __future__ import annotations
import asyncio
import sys
from pathlib import Path
import click
PROJECT_ROOT = Path(__file__).parent
FIXTURES_DIR = PROJECT_ROOT / "tests" / "fixtures"
sys.path.insert(0, str(PROJECT_ROOT))
# ---------------------------------------------------------------------------
# App banner
# ---------------------------------------------------------------------------
from banner import print_banner as _shared_banner
def _print_banner(mode: str, log_path: str, workspace: str) -> None:
_shared_banner(log_path=log_path, workspace=workspace, model=f"mock ({mode})")
# ---------------------------------------------------------------------------
# Mock LLM — returns a canned RCA built from the log analyzer output
# ---------------------------------------------------------------------------
def _make_mock_llm(log_path: str):
"""
Return a LangChain-compatible chat model that never calls an external API.
On the first invocation (investigation phase) it asks for the read_build_log
and analyze_log_issues tools. On subsequent calls it returns a formatted RCA.
"""
from langchain_core.messages import AIMessage
from mcp_tools.log_analyzer import IssueKind, first_error, summarize_issues
log_content = Path(log_path).read_text(encoding="utf-8", errors="replace")
summary = summarize_issues(log_content)
issues = __import__("mcp_tools.log_analyzer", fromlist=["analyze_log_for_issues"]).analyze_log_for_issues(log_content)
# Prefer the most informative issue over a generic "Traceback" line
PRIORITY = [
IssueKind.OOM_KILLED, IssueKind.SYNTAX_ERROR, IssueKind.MISSING_DEPENDENCY,
IssueKind.DEPENDENCY_VERSION, IssueKind.TEST_FAILURE, IssueKind.DOCKER_BUILD,
IssueKind.TIMEOUT, IssueKind.PERMISSION, IssueKind.FATAL, IssueKind.PROCESS_EXIT,
IssueKind.PYTHON_EXCEPTION, IssueKind.GENERIC_ERROR,
]
top = next(
(i for k in PRIORITY for i in issues if i.kind == k),
issues[0] if issues else None,
)
severity = "P2"
if top:
if top.kind.value in ("oom_killed", "fatal_error"):
severity = "P1"
elif top.kind.value in ("syntax_error", "missing_dependency"):
severity = "P3"
rca_text = f"""\
## Root Cause Analysis *(generated by mock LLM — replace with real Claude for production)*
**Root Cause:** {top.detail if top else "No errors detected in the provided log."}
**Severity:** {severity}
**Evidence:**
{chr(10).join(f"- Line {i.line_number}: `{i.line}`" for i in issues[:5])}
**Blast Radius:** CI pipeline blocked; no artefacts produced.
**Recommended Fix:**
> ⚠️ *Mock mode — fix steps are generic. In production, Claude correlates the error
> with actual git commits and diffs to produce specific, commit-level recommendations
> (e.g. "revert commit a3f91bc which bumped redis 4.5.1 → 5.0.0 in requirements.txt").*
1. Review the error(s) listed under Evidence above.
2. Apply the targeted fix (install missing dependency / revert bad commit / fix syntax).
3. Re-trigger the pipeline and confirm green build.
**Confidence:** High — evidence sourced directly from build log line numbers.
---
*Detailed issue scan:*
```
{summary}
```
"""
call_count = 0
class _MockLLM:
"""Minimal duck-type of a bound LangChain chat model."""
def bind_tools(self, tools):
return self # tools are ignored in mock mode
def invoke(self, messages):
nonlocal call_count
call_count += 1
# First call: trigger tool use for read_build_log
if call_count == 1:
return AIMessage(
content="",
tool_calls=[
{
"id": "mock-tool-call-1",
"name": "read_build_log",
"args": {"log_path": log_path},
},
{
"id": "mock-tool-call-2",
"name": "analyze_log_issues",
"args": {"log_path": log_path},
},
],
)
# Second call (after tools): produce RCA directly
return AIMessage(content=rca_text)
return _MockLLM()
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
@click.command()
@click.option(
"--fixture",
default="python_import_error.log",
show_default=True,
help="Fixture log filename from tests/fixtures/.",
)
@click.option("--list", "list_fixtures", is_flag=True, help="List available fixture logs and exit.")
def main(fixture: str, list_fixtures: bool):
"""Run OpsAgent-MCP locally with a mock LLM (no API key needed)."""
if list_fixtures:
click.echo("Available fixtures:")
for f in sorted(FIXTURES_DIR.glob("*.log")):
click.echo(f" {f.name}")
return
log_path = FIXTURES_DIR / fixture
if not log_path.exists():
click.echo(f"ERROR: fixture not found: {log_path}", err=True)
sys.exit(1)
workspace = str(PROJECT_ROOT)
_print_banner(mode="demo", log_path=str(log_path), workspace=workspace)
asyncio.run(_run(str(log_path), workspace))
async def _run(log_path: str, workspace_path: str):
from agent import build_graph, AgentState
from langchain_core.messages import HumanMessage, SystemMessage
from agent import SYSTEM_PROMPT
mock_llm = _make_mock_llm(log_path)
# We still spin up the real MCP servers so the tool calls actually execute
try:
from langchain_mcp_adapters.client import MultiServerMCPClient
except ImportError:
click.echo("ERROR: langchain-mcp-adapters not installed.", err=True)
sys.exit(1)
_quiet_env = {"FASTMCP_SHOW_SERVER_BANNER": "false", "FASTMCP_LOG_LEVEL": "WARNING"}
server_configs = {
"workspace": {
"command": sys.executable,
"args": ["-m", "mcp_tools.workspace_server"],
"transport": "stdio",
"env": _quiet_env,
},
"git": {
"command": sys.executable,
"args": ["-m", "mcp_tools.git_server"],
"transport": "stdio",
"env": _quiet_env,
},
"notifications": {
"command": sys.executable,
"args": ["-m", "mcp_tools.notification_server"],
"transport": "stdio",
"env": _quiet_env,
},
}
click.echo(click.style(" >> Starting MCP tool servers…", fg="blue"))
mcp_client = MultiServerMCPClient(server_configs)
tools = await mcp_client.get_tools()
click.echo(click.style(f" >> {len(tools)} tools ready: ", fg="blue") + ", ".join(t.name for t in tools) + "\n")
graph = build_graph(
llm_with_tools=mock_llm,
llm_base=mock_llm,
tools=tools,
)
initial_state: AgentState = {
"messages": [
SystemMessage(content=SYSTEM_PROMPT),
HumanMessage(
content=(
f"A CI/CD pipeline has failed. Please investigate.\n"
f"Build log path: {log_path}\n"
f"Workspace path: {workspace_path}\n"
)
),
],
"log_path": log_path,
"workspace_path": workspace_path,
"slack_webhook_url": None,
"github_token": None,
"rca": None,
}
click.echo(click.style(" >> Running investigation graph…\n", fg="blue"))
final_state = await graph.ainvoke(initial_state)
rca = final_state.get("rca", "")
width = 70
click.echo(click.style("─" * width, fg="cyan"))
click.echo(click.style(" ROOT CAUSE ANALYSIS", fg="cyan", bold=True))
click.echo(click.style("─" * width, fg="cyan"))
click.echo(rca)
click.echo(click.style("─" * width, fg="cyan"))
click.echo(click.style("\n >> Done. ", fg="blue") + "To use real Claude: set ANTHROPIC_API_KEY and run cli.py")
if __name__ == "__main__":
main()