Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
560 changes: 560 additions & 0 deletions samples/mcp-refactoring-assistant/.agent/CLI_REFERENCE.md

Large diffs are not rendered by default.

92 changes: 92 additions & 0 deletions samples/mcp-refactoring-assistant/.agent/REQUIRED_STRUCTURE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
## Required Agent Structure

**IMPORTANT**: All UiPath coded agents MUST follow this standard structure unless explicitly specified otherwise by the user.

### Required Components

Every agent implementation MUST include these three Pydantic models:

```python
from pydantic import BaseModel

class Input(BaseModel):
"""Define input fields that the agent accepts"""
# Add your input fields here
pass

class State(BaseModel):
"""Define the agent's internal state that flows between nodes"""
# Add your state fields here
pass

class Output(BaseModel):
"""Define output fields that the agent returns"""
# Add your output fields here
pass
```

### Required LLM Initialization

Unless the user explicitly requests a different LLM provider, always use `UiPathChat`:

```python
from uipath_langchain.chat import UiPathChat

llm = UiPathChat(model="gpt-4o-2024-08-06", temperature=0.7)
```

**Alternative LLMs** (only use if explicitly requested):
- `ChatOpenAI` from `langchain_openai`
- `ChatAnthropic` from `langchain_anthropic`
- Other LangChain-compatible LLMs

### Standard Agent Template

Every agent should follow this basic structure:

```python
from langchain_core.messages import SystemMessage, HumanMessage
from langgraph.graph import START, StateGraph, END
from uipath_langchain.chat import UiPathChat
from pydantic import BaseModel

# 1. Define Input, State, and Output models
class Input(BaseModel):
field: str

class State(BaseModel):
field: str
result: str = ""

class Output(BaseModel):
result: str

# 2. Initialize UiPathChat LLM
llm = UiPathChat(model="gpt-4o-2024-08-06", temperature=0.7)

# 3. Define agent nodes (async functions)
async def process_node(state: State) -> State:
response = await llm.ainvoke([HumanMessage(state.field)])
return State(field=state.field, result=response.content)

async def output_node(state: State) -> Output:
return Output(result=state.result)

# 4. Build the graph
builder = StateGraph(State, input=Input, output=Output)
builder.add_node("process", process_node)
builder.add_node("output", output_node)
builder.add_edge(START, "process")
builder.add_edge("process", "output")
builder.add_edge("output", END)

# 5. Compile the graph
graph = builder.compile()
```

**Key Rules**:
1. Always use async/await for all node functions
2. All nodes (except output) must accept and return `State`
3. The final output node must return `Output`
4. Use `StateGraph(State, input=Input, output=Output)` for initialization
5. Always compile with `graph = builder.compile()`
619 changes: 619 additions & 0 deletions samples/mcp-refactoring-assistant/.agent/SDK_REFERENCE.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions samples/mcp-refactoring-assistant/.env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ANTHROPIC_API_KEY=***
21 changes: 21 additions & 0 deletions samples/mcp-refactoring-assistant/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Agent Code Patterns Reference

This document provides practical code patterns for building UiPath coded agents using LangGraph and the UiPath Python SDK.

---

## Documentation Structure

This documentation is split into multiple files for efficient context loading. Load only the files you need:

1. **@.agent/REQUIRED_STRUCTURE.md** - Agent structure patterns and templates
- **When to load:** Creating a new agent or understanding required patterns
- **Contains:** Required Pydantic models (Input, State, Output), LLM initialization patterns, standard agent template

2. **@.agent/SDK_REFERENCE.md** - Complete SDK API reference
- **When to load:** Calling UiPath SDK methods, working with services (actions, assets, jobs, etc.)
- **Contains:** All SDK services and methods with full signatures and type annotations

3. **@.agent/CLI_REFERENCE.md** - CLI commands documentation
- **When to load:** Working with `uipath init`, `uipath run`, or `uipath eval` commands
- **Contains:** Command syntax, options, usage examples, and workflows
1 change: 1 addition & 0 deletions samples/mcp-refactoring-assistant/CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
@AGENTS.md
64 changes: 64 additions & 0 deletions samples/mcp-refactoring-assistant/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Code Refactoring Assistant with MCP

A LangGraph agent that demonstrates how to use **MCP (Model Context Protocol)** for code analysis and refactoring guidance.

## What It Does

This agent analyzes Python code, detects issues (complexity, code smells, deep nesting), and provides tailored refactoring guidance using MCP prompts.

Shows how to use `client.get_prompt()` to fetch prompt templates dynamically from an MCP server.


## MCP Components

### Server (`server.py`)
Exposes:
- **Tools**: Code analysis functions
- `analyze_code_complexity` - Detects complexity metrics
- `detect_code_smells` - Finds common issues
- `get_refactoring_guide` - Returns which prompt to use

- **Prompts**: Refactoring templates
- `extract_method_prompt` - For long functions
- `simplify_conditional_prompt` - For nested conditions
- `remove_duplication_prompt` - For duplicate code
- `improve_naming_prompt` - For poor variable names

### Client (`graph.py`)
- Agent uses tools to analyze code
- Agent determines which refactoring approach to use
- **`client.get_prompt()`** fetches the appropriate template from MCP server
- LLM generates final refactoring guidance

## How to Run

1. **Install dependencies**:
```bash
uv sync
```

2. **Initialize** (if needed):
```bash
uipath init
```

3. **Run the agent**:
```bash
uipath run agent --input-file input.json
```

## Example Input

```json
{
"code": "def process_data(x, y, z):\n if x:\n if y:\n if z:\n return x + y + z"
}
```

## Example Output

The agent will:
1. Detect the issue (deep nesting)
2. Fetch the `simplify_conditional_prompt` via MCP
3. Generate refactoring guidance using guard clauses

8 changes: 8 additions & 0 deletions samples/mcp-refactoring-assistant/agent.mermaid
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
flowchart TB
__start__(__start__)
agent(agent)
prompt(prompt)
__end__(__end__)
__start__ --> agent
agent --> prompt
prompt --> __end__
4 changes: 4 additions & 0 deletions samples/mcp-refactoring-assistant/bindings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"version": "2.0",
"resources": []
}
83 changes: 83 additions & 0 deletions samples/mcp-refactoring-assistant/entry-points.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
{
"$schema": "https://cloud.uipath.com/draft/2024-12/entry-point",
"$id": "entry-points.json",
"entryPoints": [
{
"filePath": "agent",
"uniqueId": "426f3cb2-ac10-4969-840e-399932250e3a",
"type": "agent",
"input": {
"type": "object",
"properties": {
"code": {
"title": "Code",
"type": "string"
}
},
"required": [
"code"
]
},
"output": {
"type": "object",
"properties": {
"result": {
"default": null,
"title": "Result",
"type": "string"
}
},
"required": []
},
"graph": {
"nodes": [
{
"id": "__start__",
"name": "__start__",
"type": "__start__",
"subgraph": null,
"metadata": {}
},
{
"id": "agent",
"name": "agent",
"type": "node",
"subgraph": null,
"metadata": {}
},
{
"id": "prompt",
"name": "prompt",
"type": "node",
"subgraph": null,
"metadata": {}
},
{
"id": "__end__",
"name": "__end__",
"type": "__end__",
"subgraph": null,
"metadata": {}
}
],
"edges": [
{
"source": "__start__",
"target": "agent",
"label": null
},
{
"source": "agent",
"target": "prompt",
"label": null
},
{
"source": "prompt",
"target": "__end__",
"label": null
}
]
}
}
]
}
Loading