AI IT Helpdesk Assistant MCP Server
README.md
# AI IT Helpdesk Assistant (MCP + Multi-Agent)
An AI-powered IT Helpdesk built on the layered MCP architecture from class. Employees chat
with an assistant that answers IT questions from real documentation, creates and tracks
support tickets, generates reports, and notifies teams on Slack — with every step of the
reasoning pipeline visible for teaching and demos.
This repository includes:
- A FastMCP server exposing **29 tools**, **10 resources**, and **6 prompts**
- A **multi-agent** system: Supervisor + Knowledge, Ticket, Reporting, and Notification agents
- A Streamlit chat interface with an explainable execution pipeline
- PostgreSQL with automatic Alembic migrations and seed data
- Docker Compose setup that works out of the box
## Project Overview
The domain is an internal IT helpdesk. It is exposed through two interfaces:
1. **MCP interface** for AI agents and MCP clients
2. **Streamlit interface** for employees and instructors
Both use the **same service layer**, so business logic is never duplicated.
## Architecture Diagram
```mermaid
flowchart TD
U[Employee] --> UI[Streamlit Chat UI]
UI --> CS[ChatService pipeline]
CS --> LLM[LLM: summary / intent / entities]
CS --> SUP[Supervisor Agent]
SUP --> PL[Planner]
SUP --> KA[Knowledge Agent]
SUP --> TA[Ticket Agent]
SUP --> RA[Reporting Agent]
SUP --> NA[Notification Agent]
KA --> MC[Shared MCP Client]
TA --> MC
RA --> MC
NA --> MC
MC -->|streamable-http| MCP[FastMCP Server]
MCP --> TOOLS[Tools / Resources / Prompts]
TOOLS --> SVC[Service Layer]
UI -.direct pages.-> SVC
SVC --> REPO[Repository Layer]
REPO --> DB[(PostgreSQL)]
SVC --> SLACK[Slack API]
```
Two rules keep the layering honest:
- **Agents never touch the database.** They reach data only through the shared MCP client.
- **Agents never talk to each other directly.** The Supervisor passes each agent's result
forward, which is how the Notification Agent can announce a ticket it never queried.
## Folder Structure
```text
it-helpdesk-mcp/
├── app.py # Streamlit UI (chat + dashboards + inspector)
├── main.py # MCP server entrypoint (FastAPI + FastMCP)
├── server.py # FastMCP wiring + ServiceFactory
├── config.py # Environment-driven settings
├── database.py # Engine, session, migrations
├── models.py # SQLAlchemy ORM models
├── schemas.py # Pydantic v2 validation schemas
├── repositories.py # All SQL lives here
├── services.py # Shared business logic
├── tools.py # MCP tools
├── resources.py # MCP resources
├── prompts.py # MCP prompts
├── seed.py # Migrations + demo data
├── agents/
│ ├── base_agent.py # Abstract agent + allowed-tools guard
│ ├── planner.py # Dependency-aware execution planning
│ ├── supervisor_agent.py # Coordination and delegation
│ ├── knowledge_agent.py
│ ├── ticket_agent.py
│ ├── reporting_agent.py
│ ├── notification_agent.py
│ ├── agent_context.py # AgentContext, ExecutionPlanStep
│ ├── agent_response.py # AgentResponse, AgentToolCall
│ ├── agent_registry.py
│ ├── memory_manager.py
│ └── prompts/ # Per-agent system prompts
├── chat/
│ ├── chat_service.py # The 13-stage execution pipeline
│ ├── conversation.py
│ ├── conversation_service.py # Memory + analytics
│ ├── openai_client.py # Provider-agnostic LLM wrapper
│ ├── tool_executor.py # Shared MCP client
│ ├── intent_service.py
│ ├── entity_service.py
│ ├── summary_service.py
│ ├── prompt_service.py
│ ├── prompt_builder.py # Assistant personas
│ ├── json_parsing.py
│ └── prompt_templates/ # system / intent / entity / summary / response
├── migrations/
│ ├── env.py
│ └── versions/0001_initial.py
├── requirements.txt
├── Dockerfile
├── docker-compose.yml
├── .env.example
├── alembic.ini
└── README.md
```
## Database Schema
### employees
| Column | Type | Notes |
|---|---|---|
| id | int | PK |
| name | varchar(120) | |
| email | varchar(255) | unique, indexed |
| department | varchar(100) | indexed |
| role | varchar(100) | |
| slack_handle | varchar(80) | must start with `@` |
| created_at | timestamptz | |
### tickets
| Column | Type | Notes |
|---|---|---|
| id | int | PK |
| employee_id | int | FK → employees.id, ON DELETE CASCADE |
| title | varchar(200) | |
| description | text | |
| category | varchar(60) | indexed |
| priority | varchar(20) | `low` / `medium` / `high` / `critical` |
| status | varchar(20) | `open` / `in_progress` / `resolved` / `closed` |
| assigned_team | varchar(80) | nullable, indexed |
| resolution_notes | text | nullable |
| created_at / updated_at | timestamptz | |
| resolved_at | timestamptz | set on resolve, cleared on reopen |
### knowledge_articles
| Column | Type | Notes |
|---|---|---|
| id | int | PK |
| title | varchar(200) | indexed |
| category | varchar(60) | indexed |
| content | text | |
| tags | varchar(255) | comma-separated keywords |
| created_at | timestamptz | |
Relationships: one employee has many tickets.
## MCP Concepts
### Tool
Performs an operation and may change data.
Examples: `create_ticket`, `update_ticket`, `send_slack_message`.
### Resource
Read-only, fetchable data snapshots.
Examples: `tickets://open`, `knowledge://categories`.
### Prompt
Reusable instruction templates for LLM workflows.
Examples: `Daily Incident Report`, `Knowledge Answer`.
## Implemented MCP Tools (29)
### Ticket tools
`create_ticket` · `update_ticket` · `get_ticket` · `get_ticket_status` ·
`list_open_tickets` · `list_tickets` · `tickets_by_status` · `tickets_by_priority` ·
`tickets_by_category` · `tickets_by_employee` · `search_tickets` · `assign_ticket` ·
`resolve_ticket` · `delete_ticket` · `count_tickets`
### Knowledge base tools
`search_knowledge` · `list_knowledge_articles` · `get_knowledge_article` ·
`knowledge_by_category`
### Employee tools
`search_employee` · `get_employee` · `get_employee_by_email` · `list_employees` ·
`employees_by_department`
### Reporting tools
`generate_daily_report` · `generate_incident_summary` · `helpdesk_summary` ·
`tickets_per_department`
### Notification tools
`send_slack_message`
## Implemented MCP Resources (10)
`tickets://all` · `tickets://open` · `tickets://critical` · `tickets://summary` ·
`tickets://schema` · `knowledge://all` · `knowledge://categories` · `employees://all` ·
`employees://departments` · `reports://daily`
## Implemented MCP Prompts (6)
`Ticket Summary` · `Daily Incident Report` · `Knowledge Answer` · `Escalation Notice` ·
`Generate Ticket Email` · `Helpdesk Triage Assistant`
## Multi-Agent Design
| Agent | Responsibility | Allowed tools |
|---|---|---|
| **Supervisor** | Plans, delegates, threads results between agents, synthesizes | none (coordination only) |
| **Knowledge Agent** | Searches documentation for troubleshooting steps | knowledge tools |
| **Ticket Agent** | Creates, updates, assigns, resolves, and looks up tickets | ticket + employee tools |
| **Reporting Agent** | Daily reports, incident summaries, backlog analytics | reporting tools |
| **Notification Agent** | Composes and sends Slack messages | `send_slack_message` |
Each agent enforces an `allowed_tools` allowlist in `BaseAgent.use_tool`, so a specialist
physically cannot call a tool outside its remit.
### Planning rules
- Documentation is searched **before** a ticket is created, so a self-service fix is
offered first.
- A notification step always **depends on** the steps producing the content it announces.
- If a follow-up mentions no ticket ID but memory holds one, the Ticket Agent runs first
so the Slack message carries the real title and priority.
### Example collaboration
> "Create a support ticket — the VPN gateway is down for the whole Sales floor, this is critical"
> → `knowledge_agent → ticket_agent` (ticket #30 created, priority critical)
>
> "Notify the DevOps team on Slack about it"
> → `ticket_agent → notification_agent`
> → Slack: *"Critical ticket opened: VPN Gateway Down for Sales Floor (ID 30). Impacting Sales Floor operations. Please review and assign."*
## Execution Pipeline (13 stages)
Every user message flows through these stages, all inspectable in the UI:
1. Conversation History → 2. Conversation Summary → 3. Intent Detection →
4. Entity Extraction → 5. Relevant Context → 6. Prompt Construction → 7. Planning →
8. Supervisor Decision → 9. Task Delegation → 10. Agent Execution → 11. Tool Selection →
12. MCP Execution → 13. Response Generation
## Conversation Memory
`ConversationService` persists per-session state so follow-ups work:
rolling summary, known entities, referenced tickets, tool-usage counts, agent-usage
counts, intent distribution, execution plan, collaboration messages, and a debug
event timeline.
This is what lets *"notify DevOps about **it**"* resolve to the ticket created a turn earlier.
## Validation and Error Handling
Validation uses Pydantic v2 and covers email format, Slack handle format, required
fields, positive IDs, enum-constrained status/priority, and length bounds.
Handled errors:
- Validation errors → `ServiceValidationError`
- Missing ticket/employee/article → `NotFoundError`
- Duplicate employee email
- Invalid status/priority values
- MCP transport failures vs. tool-level rejections (handled separately)
- Slack delivery failures (returned as data, never crashing the pipeline)
## Logging
Every MCP tool invocation is logged with timestamp, tool name, arguments, execution time,
and success/failure:
```
2026-08-01 11:57:39 INFO mcp.requests timestamp=2026-08-01T05:57:39Z tool=search_knowledge args={'query': 'vpn', 'limit': 5} execution_ms=47.83 success=true
2026-08-01 11:57:39 ERROR mcp.requests timestamp=2026-08-01T05:57:39Z tool=get_ticket args={'ticket_id': 999999} execution_ms=15.97 success=false error=Ticket with id=999999 not found
```
## Docker Quick Start
### 1) Configure environment
```bash
cp .env.example .env
```
Add your LLM API key to `.env`. The client speaks the OpenAI **Chat Completions**
protocol, so switching providers is a base-URL change only:
| Provider | `OPENAI_BASE_URL` | Example `OPENAI_MODEL` |
|---|---|---|
| Groq (free) | `https://api.groq.com/openai/v1` | `llama-3.3-70b-versatile` |
| Google Gemini (free) | `https://generativelanguage.googleapis.com/v1beta/openai/` | `gemini-2.0-flash` |
| OpenAI | `https://api.openai.com/v1` | `gpt-4o-mini` |
### 2) Start everything
```bash
docker compose up --build
```
This starts PostgreSQL, the MCP server, and the Streamlit dashboard, running migrations
and seeding demo data automatically.
### 3) Open the app
- Streamlit UI: http://localhost:8511
- MCP endpoint: http://localhost:8010/mcp
- Health check: http://localhost:8010/health
> Ports **8010/8511/5433** are used instead of 8000/8501/5432 so this project can run
> alongside the `customer-order-mcp` class project without conflicts.
## Running Without Docker (optional)
```bash
python -m venv .venv
source .venv/bin/activate # Linux/macOS
# .venv\Scripts\activate # Windows PowerShell
pip install -r requirements.txt
# Start only PostgreSQL from compose
docker compose up -d postgres
# Point the app at the host-mapped database port
export POSTGRES_HOST=localhost POSTGRES_PORT=5433
python seed.py --migrate
python main.py
```
In another terminal:
```bash
export POSTGRES_HOST=localhost POSTGRES_PORT=5433
streamlit run app.py --server.port 8511
```
## Slack Integration
The Notification Agent supports three delivery modes, selected automatically:
| Mode | Configuration | Behavior |
|---|---|---|
| `bot_token` | `SLACK_BOT_TOKEN` (+ `chat:write` scope) | Posts to any channel by name |
| `webhook` | `SLACK_WEBHOOK_URL` | Posts to the webhook's preconfigured channel |
| `dry_run` | neither set | Logs the message and reports it as **not delivered** |
Dry-run is the default so the app runs without a Slack workspace. The response prompt
instructs the assistant never to claim delivery unless the tool result says
`delivered: true`.
## Streamlit Pages
- **AI Helpdesk Assistant** — chat + live pipeline inspector
- **Dashboard** — ticket metrics and department breakdown
- **Ticket Management** — list, create, update, search
- **Knowledge Base** — search, browse, add articles
- **Agent Monitor** — agent status, utilization, plans, collaboration messages
- **Developer Tools** — memory, execution timeline, raw tool calls
- **MCP Playground** — call any discovered tool with raw JSON
- **Database Viewer** — all three tables
## Testing: Example MCP Requests and Expected Responses
1. `search_knowledge({"query":"password reset"})`
→ `{"articles":[{"title":"How to reset your password", ...}]}`
2. `search_knowledge({"query":"vpn"})`
→ `{"articles":[{"title":"VPN connection troubleshooting", ...}]}`
3. `list_open_tickets({})`
→ `{"tickets":[...]}` sorted critical-first (18 seeded)
4. `get_ticket_status({"ticket_id":1})`
→ `{"ticket_id":1,"status":"in_progress","priority":"high", ...}`
5. `create_ticket({"title":"Laptop overheating","description":"Shuts down under load","category":"Hardware","priority":"high","employee_id":1})`
→ new ticket object with `"status":"open"`
6. `update_ticket({"ticket_id":1,"updates":{"priority":"critical"}})`
→ ticket object with updated priority
7. `assign_ticket({"ticket_id":1,"team":"DevOps"})`
→ ticket with `assigned_team:"DevOps"`, `status:"in_progress"`
8. `resolve_ticket({"ticket_id":1,"resolution_notes":"Reissued MFA token."})`
→ ticket with `status:"resolved"` and `resolved_at` set
9. `generate_daily_report({"days":7})`
→ `{"tickets_created":23,"tickets_resolved":6,"open_backlog":18,"critical_open":3, ...}`
10. `helpdesk_summary({})`
→ `{"total_tickets":25,"open_tickets":11,"critical_tickets":4, ...}`
11. `send_slack_message({"channel":"#devops","message":"Test"})`
→ `{"delivered":false,"mode":"dry_run", ...}` when Slack is unconfigured
12. `get_ticket({"ticket_id":999999})`
→ MCP error: `Ticket with id=999999 not found`
## Example User Queries
| Query | Agents | Tools called |
|---|---|---|
| "My VPN is not working" | knowledge | `search_knowledge` |
| "What is the password reset procedure?" | knowledge | `search_knowledge` |
| "Show all open tickets" | ticket | `list_open_tickets` |
| "Create a support ticket for my broken laptop" | knowledge → ticket | `search_knowledge`, `create_ticket` |
| "Summarize today's incidents" | reporting | `generate_incident_summary`, `helpdesk_summary` |
| "Notify the DevOps team on Slack" | ticket → notification | `get_ticket_status`, `send_slack_message` |
## MCP Inspector / Claude Desktop / Cursor
Use the MCP server URL: `http://localhost:8010/mcp` (streamable HTTP transport).
If you connect from another hostname, add it to `MCP_ALLOWED_HOSTS` in `.env` — the MCP
SDK enables DNS-rebinding protection and rejects unlisted `Host` headers with HTTP 421.
## Troubleshooting
1. **Ports already in use** — change the host port mappings in `docker-compose.yml`.
2. **DB connection issues** — confirm `.env` matches the compose service name
(`POSTGRES_HOST=postgres`). For local runs use `POSTGRES_HOST=localhost POSTGRES_PORT=5433`.
3. **Migration errors** — rebuild: `docker compose down -v` then `docker compose up --build`.
4. **HTTP 421 Misdirected Request** — the hostname is missing from `MCP_ALLOWED_HOSTS`.
5. **Streamlit shows no data** — check `docker compose logs mcp-server` to confirm
migrations and seeding completed.
6. **Assistant says the API key is missing** — set `OPENAI_API_KEY` in `.env` and restart.
7. **Slack says dry run** — expected until `SLACK_BOT_TOKEN` or `SLACK_WEBHOOK_URL` is set.
## Teaching Notes
The code includes concise comments and docstrings explaining what each layer does, why it
exists in a real architecture, which parts demonstrate MCP tools/resources/prompts, and
how AI agents invoke these components through MCP.
## License
Use this project for classroom teaching, internal demos, and MCP learning labs.
This server cannot be deployed
Maintenance
ActivitySlowing
ResponsivenessNo issues