|
| 1 | +"""LangGraph agent for Code Refactoring Assistant. |
| 2 | +""" |
| 3 | + |
| 4 | +import json |
| 5 | +import sys |
| 6 | +from contextlib import asynccontextmanager |
| 7 | +from pathlib import Path |
| 8 | +from typing import Any, Optional |
| 9 | + |
| 10 | +from langchain_anthropic import ChatAnthropic |
| 11 | +from langchain_core.messages import HumanMessage |
| 12 | +from langchain_mcp_adapters.client import MultiServerMCPClient |
| 13 | +from langgraph.graph import END, START, StateGraph |
| 14 | +from langgraph.prebuilt import create_react_agent |
| 15 | +from typing_extensions import TypedDict |
| 16 | + |
| 17 | +model = ChatAnthropic( |
| 18 | + model_name="claude-3-7-sonnet-latest", |
| 19 | + timeout=60, |
| 20 | + stop=None |
| 21 | +) |
| 22 | + |
| 23 | +server_path = Path(__file__).parent / "server.py" |
| 24 | + |
| 25 | + |
| 26 | +def _try_parse_json(value: Any) -> Optional[dict]: |
| 27 | + """Robustly parse JSON from various formats (dict, str, list).""" |
| 28 | + if value is None: |
| 29 | + return None |
| 30 | + |
| 31 | + if isinstance(value, dict): |
| 32 | + if 'text' in value: |
| 33 | + return _try_parse_json(value['text']) |
| 34 | + if 'prompt_name' in value or 'error' in value: |
| 35 | + return value |
| 36 | + return None |
| 37 | + |
| 38 | + if isinstance(value, str): |
| 39 | + value = value.strip() |
| 40 | + if not value: |
| 41 | + return None |
| 42 | + try: |
| 43 | + parsed = json.loads(value) |
| 44 | + return parsed if isinstance(parsed, dict) else None |
| 45 | + except json.JSONDecodeError: |
| 46 | + return None |
| 47 | + |
| 48 | + if isinstance(value, list): |
| 49 | + for item in value: |
| 50 | + parsed = _try_parse_json(item) |
| 51 | + if parsed: |
| 52 | + return parsed |
| 53 | + |
| 54 | + return None |
| 55 | + |
| 56 | + |
| 57 | +class InputSchema(TypedDict): |
| 58 | + """Input schema: the code to analyze.""" |
| 59 | + code: str |
| 60 | + |
| 61 | + |
| 62 | +class OutputSchema(TypedDict): |
| 63 | + """Output schema: just the refactoring result.""" |
| 64 | + result: str |
| 65 | + |
| 66 | + |
| 67 | +class GraphState(TypedDict, total=False): |
| 68 | + """Internal state for the graph (not exposed to user).""" |
| 69 | + code: str |
| 70 | + messages: list |
| 71 | + prompt_name: str |
| 72 | + prompt_arguments: dict |
| 73 | + result: str |
| 74 | + |
| 75 | + |
| 76 | +@asynccontextmanager |
| 77 | +async def make_graph(): |
| 78 | + """Create the refactoring assistant graph with MCP client.""" |
| 79 | + # Initialize MCP client |
| 80 | + client = MultiServerMCPClient({ |
| 81 | + "code-refactoring": { |
| 82 | + "command": sys.executable, |
| 83 | + "args": [str(server_path)], |
| 84 | + "transport": "stdio", |
| 85 | + }, |
| 86 | + }) |
| 87 | + |
| 88 | + tools = await client.get_tools() |
| 89 | + react_agent = create_react_agent(model, tools) |
| 90 | + |
| 91 | + async def agent_node(state: dict) -> GraphState: |
| 92 | + """Agent analyzes code and determines which prompt to use.""" |
| 93 | + code = state.get('code', '') |
| 94 | + initial_msg = HumanMessage( |
| 95 | + content=f"""You are a refactoring assistant. |
| 96 | +
|
| 97 | +1) Analyze this code using analyze_code_complexity |
| 98 | +2) Detect issues using detect_code_smells |
| 99 | +3) Call get_refactoring_guide with: |
| 100 | + - issue_type: the main issue detected |
| 101 | + - code: the code to refactor |
| 102 | + - complexity_info: results from step 1 |
| 103 | + - smells_info: results from step 2 |
| 104 | +
|
| 105 | +The get_refactoring_guide tool will return {{\"prompt_name\": \"...\", \"arguments\": {{...}}}} ready for the next step. |
| 106 | +
|
| 107 | +CODE: |
| 108 | +{code} |
| 109 | +""" |
| 110 | + ) |
| 111 | + |
| 112 | + result = await react_agent.ainvoke({"messages": [initial_msg]}) |
| 113 | + |
| 114 | + prompt_name = "" |
| 115 | + prompt_args: dict = {} |
| 116 | + |
| 117 | + for msg in result.get("messages", []): |
| 118 | + if hasattr(msg, 'type') and msg.type == 'tool': |
| 119 | + tool_name = getattr(msg, 'name', None) or getattr(msg, 'tool', None) |
| 120 | + if tool_name == 'get_refactoring_guide': |
| 121 | + data = _try_parse_json(getattr(msg, 'content', None)) |
| 122 | + if data and 'prompt_name' in data: |
| 123 | + prompt_name = data['prompt_name'] |
| 124 | + prompt_args = data.get('arguments', {}) or {} |
| 125 | + break |
| 126 | + |
| 127 | + if not prompt_name: |
| 128 | + return { |
| 129 | + "prompt_name": "", |
| 130 | + "prompt_arguments": {}, |
| 131 | + } |
| 132 | + |
| 133 | + prompt_args.setdefault('code', code) |
| 134 | + |
| 135 | + return { |
| 136 | + "prompt_name": prompt_name, |
| 137 | + "prompt_arguments": prompt_args, |
| 138 | + } |
| 139 | + |
| 140 | + async def prompt_node(state: GraphState) -> dict: |
| 141 | + """Fetch prompt using client.get_prompt() and generate final response.""" |
| 142 | + prompt_name = state.get("prompt_name", "") |
| 143 | + |
| 144 | + if not prompt_name: |
| 145 | + return { |
| 146 | + "result": "Unable to determine appropriate refactoring prompt. " |
| 147 | + "Please ensure the agent analyzed the code and called get_refactoring_guide." |
| 148 | + } |
| 149 | + |
| 150 | + prompt_messages = await client.get_prompt( |
| 151 | + "code-refactoring", |
| 152 | + prompt_name, |
| 153 | + arguments=state.get("prompt_arguments", {}) |
| 154 | + ) |
| 155 | + |
| 156 | + final_response = await model.ainvoke(prompt_messages) |
| 157 | + |
| 158 | + return {"result": final_response.content} |
| 159 | + |
| 160 | + builder = StateGraph(GraphState, input=InputSchema, output=OutputSchema) |
| 161 | + builder.add_node("agent", agent_node) |
| 162 | + builder.add_node("prompt", prompt_node) |
| 163 | + |
| 164 | + builder.add_edge(START, "agent") |
| 165 | + builder.add_edge("agent", "prompt") |
| 166 | + builder.add_edge("prompt", END) |
| 167 | + |
| 168 | + yield builder.compile() |
| 169 | + |
0 commit comments