Metadata-Version: 2.4
Name: agentapps
Version: 0.2.42
Summary: AgentApps — A flexible multi-agent orchestration framework with visual Flow Builder
Home-page: https://www.agentappsai.com
Author: AgentApps Team
Author-email: mannankhanabdul@googlemail.com
Project-URL: Bug Reports, https://github.com/91abdul/agentapps/issues
Project-URL: Source, https://github.com/91abdul/agentapps
Project-URL: Documentation, https://github.com/91abdul/agentapps#readme
Keywords: agents,ai,llm,orchestration,multi-agent,openai,flow-builder,visual,gemini,grok
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Requires-Python: >=3.8
Description-Content-Type: text/markdown
Requires-Dist: openai
Requires-Dist: ddgs
Requires-Dist: beautifulsoup4
Requires-Dist: requests
Requires-Dist: httpx
Requires-Dist: fastapi>=0.100.0
Requires-Dist: uvicorn[standard]>=0.24.0
Requires-Dist: python-multipart
Requires-Dist: rank-bm25
Requires-Dist: rapidfuzz
Requires-Dist: gdown
Requires-Dist: pymupdf
Requires-Dist: python-docx
Requires-Dist: cryptography
Requires-Dist: pdfplumber
Requires-Dist: openpyxl
Requires-Dist: python-pptx
Requires-Dist: msal
Requires-Dist: pyodbc
Requires-Dist: playwright
Requires-Dist: falkordb
Provides-Extra: gemini
Requires-Dist: google-genai; extra == "gemini"
Provides-Extra: ssl
Requires-Dist: cryptography; extra == "ssl"
Provides-Extra: all
Requires-Dist: google-genai; extra == "all"
Requires-Dist: cryptography; extra == "all"
Provides-Extra: dev
Requires-Dist: pytest; extra == "dev"
Requires-Dist: black; extra == "dev"
Requires-Dist: flake8; extra == "dev"
Requires-Dist: mypy; extra == "dev"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# AgentApps

A flexible multi-agent orchestration framework for building intelligent agent applications with a visual Flow Builder.

---

## Screenshots

![AgentApps Portal](https://raw.githubusercontent.com/91Abdul/agentapps/main/screenshots/portal.png)
![AgentApps Builder](https://raw.githubusercontent.com/91Abdul/agentapps/main/screenshots/builder.png)
![AgentApps Flow](https://raw.githubusercontent.com/91Abdul/agentapps/main/screenshots/flow.png)

---

## Features

🤖 **Simple Agent Creation** — Clean, intuitive agent setup  
👥 **Team Collaboration** — Multiple agents working together  
🔄 **Sequential Workflows** — Automatic multi-step execution  
🛠️ **Built-in Tools** — Web search, scraping, calculations  
🎯 **Custom Tools** — Easy 3rd-party integrations (Jira, Slack, GitHub, SMTP and more)  
📊 **Streaming Support** — Real-time responses  
🔍 **Web Search** — DuckDuckGo integration  
🌐 **Web Scraping** — Extract content from any URL  
🌟 **Multi-Model Support** — OpenAI, Google Gemini, xAI Grok, Ollama (local)  
🗂️ **Platform Tables** — Built-in structured data storage  
⏰ **Triggers & Scheduler** — Run agents on a schedule or via webhook  
🐚 **Shell Tool** — Execute server commands from agents (opt-in)  
🔐 **Role-Based Access** — Admin, Editor, Operator, Viewer roles  
🔑 **SSO / Microsoft Azure AD** — Single Sign-On support  
🏗️ **AI Builder** — Describe an agent in plain English and it builds itself  
🌍 **Portal** — End-user chat interface for your deployed agents  
🔌 **MCP Client Tool** — Connect to any MCP server and use its tools *(New)*  
📌 **Pinned Response Cards** — Pin agent responses to the Portal hero page *(New)*  
💾 **Session Persistence** — Responses saved even if you navigate away *(New)*  
🕸️ **Knowledge Graph (FalkorDB)** — Query a graph database with Cypher; dependency and blast-radius analysis *(New)*  
📈 **Graph Visualization in Chat** — Agents can draw the relationships they find as an interactive diagram *(New)*  
🌐 **REST API Tool** — Call any REST API from an agent with API key, Bearer, Basic or OAuth 2.0 *(New)*  
🔐 **OAuth 2.0** — Client credentials and user sign-in (authorization code + PKCE) with automatic token refresh, for the REST API and MCP tools *(New)*  

---

## Links

- **GitHub:** https://github.com/91Abdul/agentapps  
- **PyPI:** https://pypi.org/project/agentapps  
- **Website:** https://www.agentappsai.com  
- **Issues:** https://github.com/91Abdul/agentapps/issues  
- **Discord:** https://discord.gg/xAUYb2vujP  
- **LinkedIn Group:** https://www.linkedin.com/groups/14471903/  
- **Support:** ak@agentappsai.com  

---

## Installation

```bash
pip install agentapps
```

---

## Quick Start — Flow Builder UI

```bash
agentapps-flow
```

This starts the server and automatically opens the visual Flow Builder in your browser at `http://localhost:7860`.

```bash
# Custom port
agentapps-flow --port 8080

# Don't open browser automatically
agentapps-flow --no-browser

# Dev mode with hot-reload
agentapps-flow --reload
```

---

## Secure Login

### 1. CLI flag
```bash
agentapps-flow --password mysecretpassword
```

### 2. Environment variable (recommended for servers)
```bash
export AGENTAPPS_PASSWORD=mysecretpassword
agentapps-flow
```

### 3. Auto-generated password
If no password is set, one is auto-generated and printed to the console:

```
╔══════════════════════════════════════════════╗
║   🔑 Auto-generated password:                ║
║      xK9mP2nQvR4sT7uW                        ║
╚══════════════════════════════════════════════╝
```

> Passwords are stored as secure hashes — never in plaintext.

---

## Shell Tool (opt-in)

Enable agents to run shell commands on the server (Windows cmd, Mac/Linux bash, PowerShell):

```bash
agentapps-flow --enable-shell
```

Or via environment variable:
```bash
AGENTAPPS_ENABLE_SHELL=true agentapps-flow
```

Optionally restrict the working directory:
```bash
AGENTAPPS_SHELL_DIR=/path/to/scripts agentapps-flow --enable-shell
```

> Shell tool is **disabled by default**. All commands are logged and protected by a blocklist. Use with care on shared servers.

---

## Supported Models

| Provider | Model IDs |
|---|---|
| OpenAI | `gpt-4o`, `gpt-4-turbo`, `gpt-3.5-turbo`, `gpt-5.6-luna` | 
| Google Gemini | `gemini-2.0-flash`, `gemini-1.5-pro` |
| xAI Grok | `grok-3`, `grok-3-mini` |
| Ollama (local) | Any locally served model via `http://localhost:11434` |
| Azure OpenAI | Any Azure-hosted OpenAI deployment |

---

## Quick Start with OpenAI

```python
from agentapps import Agent
from agentapps.model import OpenAIChat
from agentapps.tools import SearchSummaryTool

agent = Agent(
    name="Research Assistant",
    role="Search and analyze information",
    model=OpenAIChat(id="gpt-4o", api_key="your-openai-key"),
    tools=[SearchSummaryTool()],
    instructions=["Always include sources"],
    show_tool_calls=True
)

agent.print_response("What is the latest news about AI?")
```

Get an OpenAI API key: https://platform.openai.com/api-keys

---

## Quick Start with Gemini

```python
from agentapps import Agent
from agentapps.model import GeminiChat
from agentapps.tools import SearchSummaryTool

agent = Agent(
    name="Research Assistant",
    role="Search and analyze information",
    model=GeminiChat(id="gemini-2.0-flash-exp", api_key="your-google-api-key"),
    tools=[SearchSummaryTool()],
    instructions=["Always include sources"],
    show_tool_calls=True
)

agent.print_response("What is the latest news about AI?")
```

Get a Gemini API key: https://makersuite.google.com/app/apikey

---

## Quick Start with Grok xAI

```python
from agentapps import Agent
from agentapps.model import GrokChat
from agentapps.tools import SearchSummaryTool

agent = Agent(
    name="Research Assistant",
    role="Search and analyze information",
    model=GrokChat(id="grok-3-mini", api_key="your-xai-api-key"),
    tools=[SearchSummaryTool()],
    instructions=["Always include sources"],
    show_tool_calls=True
)

agent.print_response("What is the latest news about AI?")
```

Get a Grok API key: https://console.x.ai

---

## Available Tools

### SearchSummaryTool
Search the web and get detailed snippets:

```python
from agentapps.tools import SearchSummaryTool

agent = Agent(
    name="Searcher",
    model=OpenAIChat(id="gpt-4o", api_key="key"),
    tools=[SearchSummaryTool()]
)
```

### WebScraperTool
Scrape content from URLs:

```python
from agentapps.tools import WebScraperTool

agent = Agent(
    name="Scraper",
    model=OpenAIChat(id="gpt-4o", api_key="key"),
    tools=[WebScraperTool()]
)
```

### CalculatorTool
Perform calculations:

```python
from agentapps.tools import CalculatorTool
agent = Agent(name="Calculator", model=OpenAIChat(id="gpt-4o", api_key="key"), tools=[CalculatorTool()])
```

### MCPClientTool *(New)*
Connect to any MCP server and use its tools:

```python
from agentapps.tools import MCPClientTool

tool = MCPClientTool(
    server_url="http://localhost:8000/mcp",
    tool_name="add_numbers",
    tool_description="Add two numbers together",
    auth_type="none"   # or "bearer" / "apikey"
)

agent = Agent(name="MCP Agent", model=OpenAIChat(id="gpt-4o", api_key="key"), tools=[tool])
agent.print_response("Add 42 and 58")
```

Or use the **MCP Tool node** in the Flow Builder — enter the server URL, click **Discover Tools**, select a tool, and it auto-fills all fields.

### FalkorDBTool — Knowledge Graph *(New)*
Query a FalkorDB graph (FalkorDB Cloud or self-hosted) directly — no MCP server needed:

```python
from agentapps.tools import FalkorDBTool

tool = FalkorDBTool(
    host="your-instance.falkordb.cloud",
    port=6379,
    password="your-password",
    graph_name="servicenow",
    ssl=False,          # match your instance (see Knowledge Graph section)
    read_only=True      # default: write queries are blocked
)

agent = Agent(name="Graph Analyst", model=OpenAIChat(id="gpt-4o", api_key="key"), tools=[tool])
agent.print_response("What is the blast radius of problem PRB0000051?")
```

Or drag the **Knowledge Graph** node (Tools palette) onto the Flow Builder canvas.

---

### RestAPITool — REST APIs with OAuth 2.0 *(New)*
Call any REST API, with optional OAuth 2.0 and automatic token refresh:

```python
from agentapps.tools import RestAPITool

tool = RestAPITool(
    base_url="https://api.example.com",
    auth_type="oauth2",                       # none | apikey | bearer | basic | oauth2 | oauth2_user
    token_url="https://login.example.com/oauth2/token",
    client_id="...", client_secret="...", scope="read",
)
agent = Agent(name="API Agent", model=OpenAIChat(id="gpt-4o", api_key="key"), tools=[tool])
agent.print_response("List my open tickets")
```

See [REST API Tool & OAuth 2.0](#rest-api-tool--oauth-20-new) for all options.

---

## Team Agents

Create teams that work together sequentially:

```python
from agentapps import Agent
from agentapps.model import OpenAIChat
from agentapps.tools import SearchSummaryTool, WebScraperTool

search_agent = Agent(
    name="Search Agent",
    role="Search the web",
    model=OpenAIChat(id="gpt-4o", api_key="your-key"),
    tools=[SearchSummaryTool()]
)

scraper_agent = Agent(
    name="Scraper Agent",
    role="Read web pages",
    model=OpenAIChat(id="gpt-4o", api_key="your-key"),
    tools=[WebScraperTool()]
)

team = Agent(
    team=[search_agent, scraper_agent],
    instructions=[
        "First, search for relevant URLs",
        "Then, scrape content from those URLs",
        "Finally, provide a comprehensive answer"
    ],
    show_tool_calls=True
)

team.print_response("Research NVIDIA's latest AI developments")
```

---

## Custom Tools

Create your own tools easily:

```python
from agentapps import Tool

class WeatherTool(Tool):
    def __init__(self):
        super().__init__(
            name="get_weather",
            description="Get weather for a city"
        )

    def execute(self, city: str) -> str:
        return f"Weather in {city}: Sunny, 72°F"

    def get_parameters(self):
        return {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name"}
            },
            "required": ["city"]
        }

agent = Agent(
    name="Weather Agent",
    model=OpenAIChat(id="gpt-4o", api_key="key"),
    tools=[WeatherTool()]
)
```

You can also register custom tools via the Flow Builder UI — no restart required.

---

## Portal — End User Interface *(Enhanced)*

The Portal is the end-user interface for interacting with your deployed agents.

### Hero Page
- **Bento-grid layout** — Quick Links, Popular Agents, Inbox, Calendar
- **Agent chips** — one-click access to agents, each starts a fresh chat
- **Search bar** — type a prompt and route to the right agent automatically
- Click the **agentapps. logo** to return to hero from any chat

### Pinned Response Cards *(New)*
Pin any agent response directly to the hero page:
- Click the 📌 pin icon on any assistant message
- Pinned cards appear in a horizontal strip above the bento grid
- **Expand** (↗) to read the full response in a modal
- **Refresh** (🔄) to re-run the original prompt and update the card
- **Unpin** (✕) to remove the card
- Maximum 6 pinned cards per user

### Session Persistence *(Improved)*
- Agent responses saved server-side regardless of client connection
- Navigate away during a long-running agent task — response appears when you return
- Works with approval workflows — approve from inbox, result saves automatically
- Execution logs and Recent Runs updated even after page refresh

### Approvals Inbox
- Pending approval notifications visible on the hero page
- Approve or reject agent actions without staying on the chat page

---

## Examples

### Stock Analysis
```python
agent = Agent(
    name="Stock Analyst",
    role="Analyze stocks",
    model=OpenAIChat(id="gpt-4o", api_key="key"),
    tools=[SearchSummaryTool()],
    instructions=["Include price targets and analyst ratings"]
)

agent.print_response("Analyze NVDA stock with latest news and recommendations")
```

### Research Team
```python
research_team = Agent(
    team=[search_agent, scraper_agent],
    instructions=[
        "Search for academic sources",
        "Read full articles",
        "Provide a comprehensive summary with citations"
    ]
)

research_team.print_response("What are the latest breakthroughs in quantum computing?")
```

---

## API Reference

### Agent

```python
Agent(
    name: str = "Agent",
    role: str = "General Assistant",
    model: Model = None,
    tools: List[Tool] = None,
    instructions: List[str] = None,
    team: List[Agent] = None,
    show_tool_calls: bool = False,
    markdown: bool = False,
    temperature: float = None
)
```

### Methods

| Method | Description |
|---|---|
| `run(message, stream=False)` | Execute agent |
| `print_response(message, stream=False)` | Print response to console |
| `clear_history()` | Clear conversation history |
| `add_tool(tool)` | Add a tool dynamically |
| `get_info()` | Get agent information |

---

## Role-Based Access Control

The platform supports four roles assignable per user:

| Role | Description |
|---|---|
| **Admin** | Full access — users, settings, SSO, shell tool |
| **Editor** | Build and run — create/edit agents, tools, schedules |
| **Operator** | Run only — use agents via portal, view reports and approvals |
| **Viewer** | Read only — view projects, tables, reports |

Manage users and assign roles from the **Admin → Users** section in the Flow Builder.

---

## Triggers & Scheduler

Run agents automatically on a schedule or via external webhook:

- **Scheduler** — run agents every N minutes, hourly, daily, or weekly
- **Webhook** — trigger agents via HTTP from any external service (Jira, Zapier, Slack, etc.)
- **Email** — poll IMAP inbox and trigger on new messages
- **API Poll** — monitor any external API and trigger on condition

---

## MCP Client Tool *(New)*

Connect to any MCP (Model Context Protocol) server directly from the Flow Builder.

**Supported transports:** Streamable HTTP (JSON-RPC 2.0)  
**Auth options:** None, Bearer Token, API Key, OAuth 2.0 client credentials, OAuth 2.0 user sign-in (see [REST API Tool & OAuth 2.0](#rest-api-tool--oauth-20-new))  
**Compatible with:** FastMCP, official MCP servers, any compliant server

### In the Flow Builder:
1. Drag **MCP Tool** node to canvas
2. Enter server URL + auth settings
3. Click **Discover Tools** — auto-connects and lists available tools
4. Click a tool — Tool Name, Description, Schema auto-fill
5. Connect to Agent node and save

### In Python:
```python
from agentapps.tools import MCPClientTool

tool = MCPClientTool(
    server_url="https://mcp.example.com",
    tool_name="search",
    tool_description="Search for information",
    tool_schema={
        "type": "object",
        "properties": {"query": {"type": "string"}},
        "required": ["query"]
    },
    auth_type="bearer",
    auth_value="your-token"
)
```

---

## Knowledge Graph — FalkorDB *(New)*

Give agents a **graph database** to reason over connected data — dependencies, ownership, relationships — using Cypher. AgentApps connects **directly** to FalkorDB with the `falkordb` Python client, so there is no MCP server for you or your customers to host.

**Works with:** FalkorDB Cloud and self-hosted FalkorDB  
**Agent operations:** `get_schema`, `query` (openCypher), `list_graphs`  
**Safe by default:** read-only mode blocks `CREATE`, `MERGE`, `DELETE`, `SET`, `REMOVE`, `DROP` and uses read-only queries on the server  
**Installed with:** `pip install agentapps` (includes the `falkordb` client)

### In the Flow Builder
1. Drag the **Knowledge Graph** node (Tools palette) to the canvas
2. Fill in the connection fields:

| Field | Description |
|---|---|
| Host | e.g. `your-instance.falkordb.cloud` |
| Port | Your instance port (the Cloud console shows it) |
| Username | Optional — leave blank unless your instance needs one |
| Password | Masked |
| Graph Name | The graph to query |
| Use SSL/TLS | `true` / `false` — must match your instance |
| Read-only | `true` (default) blocks all write queries |

3. Connect the node to an **Agent** node (and a model to the agent) and save
4. Ask questions in the playground or Portal

> **SSL tip:** if the connection times out, switch **Use SSL/TLS** to the opposite value. Some Cloud instances accept plain connections on their custom port.

### Suggested agent instructions
Keep them short and add detail only where the agent gets it wrong:

```
You are an IT operations analyst. Answer using the knowledge_graph tool.
Call get_schema first, then query with openCypher. Always use LIMIT.
Answer only from query results and never invent data. The graph is read-only.
If a query fails or returns nothing, fix it and retry before answering.
```

If the agent guesses wrong values or relationship directions, add the exact value formats (e.g. priority is `"1 - Critical"`) and a one-line note on direction.

### Loading your own data (CSV → graph)
Data is loaded **outside** the agent, so agents can never modify your graph. Use a mapping file plus a generic loader:

```bash
pip install falkordb pandas
python load_graph.py --mapping graph_mapping.json --dir ./csv \
  --host your-instance.falkordb.cloud --port 6379 --password "your-password"
```

| Option | Purpose |
|---|---|
| `--dry-run` | Parse files and show planned counts; no database needed |
| `--drop` | Delete the graph first (full rebuild) |
| `--rels-only` | Skip nodes, load relationships only |
| `--only A,B` | Load only these node labels / relationship types |
| `--no-ssl` | Force a non-SSL connection (otherwise both modes are tried) |

Without `--drop` the loader upserts (`MERGE`): re-running updates existing nodes and edges and adds new ones. Rows deleted from a CSV are not removed from the graph.

`graph_mapping.json` describes what to load, so you can change columns, nodes and relationships without touching code:

```json
{
  "graph": "servicenow",
  "files": { "incident": "incident.csv", "cmdb_ci": "cmdb_ci.csv" },
  "nodes": [
    { "label": "CI", "file": "cmdb_ci", "key": "name",
      "properties": { "class": "sys_class_name", "location": "location" } },
    { "label": "Incident", "file": "incident", "key": "number",
      "properties": { "priority": "priority", "state": "state" } }
  ],
  "relationships": [
    { "type": "AFFECTS", "file": "incident",
      "from": ["Incident", "number", "number"], "to": ["CI", "name", "cmdb_ci"] }
  ]
}
```

- **Property spec:** `"column"`, or `"column:bool"` / `"column:int"` to convert the value
- **Relationship `from` / `to`:** `[node label, key property, CSV column]`
- **Type from a column:** use `"type_from_column"` with `"type_transform": "first_part_upper"` (e.g. `Depends on::Used by` → `DEPENDS_ON`)
- **Duplicates:** `"dedupe_keep_latest_by": "sys_updated_on"` keeps the newest row per key
- **Sensitive values:** `"ignore_values_starting_with": ["$s$"]` drops values such as password hashes
- **Derived nodes:** `"collect_from"` builds one node type from several columns (e.g. Users)

### Example: dependency & blast-radius analysis
Walk dependencies backwards from a failing CI to everything that depends on it:

```cypher
MATCH (i:Incident {number:'INC0000050'})-[:AFFECTS]->(ci:CI)
MATCH (x:CI)-[:DEPENDS_ON|RUNS_ON|HOSTED_ON|MEMBERS*1..5]->(ci)
RETURN ci.name, count(DISTINCT x) AS impacted, collect(DISTINCT x.name) AS who
```

Typical questions an agent can answer once the graph is loaded:
- *"What is the blast radius of problem PRB0000051?"*
- *"Which CIs are the biggest single points of failure?"*
- *"Which services depend on this database?"*
- *"Incidents per assignment group?"*

### Showing relationships as a graph in chat *(New)*

The Knowledge Graph tool can draw what it finds as an **interactive diagram** under the agent's answer (Portal and Builder playground): drag nodes, scroll to zoom, hover for properties, and see a legend by node type.

- It is **off by default**. The model turns it on for a question only when the user asks to see, visualize or draw the relationships, or when the agent instructions say to always do it.
- It works by the agent calling the tool with `visualize=true` and a query that returns nodes and relationships (`RETURN a, r, b`) or paths (`MATCH p=(...)-[...]->(...) RETURN p`). Relationships between the returned nodes are filled in automatically.
- Diagrams are capped at 150 nodes and 300 relationships and are saved with the chat history.

Control it from the agent instructions:

```text
# Always show a graph
When you query the knowledge graph, always set visualize=true and return nodes and
relationships (RETURN a, r, b, or full paths) so a diagram is shown.

# Never show a graph
Never visualize. Always call the knowledge graph tool with visualize=false and answer in text only.

# Only when asked (default behaviour)
Set visualize=true only when the user asks to see, visualize or draw the relationships.

# Blast radius with the full chain
When visualizing a blast radius or dependencies, return full paths, for example
MATCH p=(x:CI)-[:DEPENDS_ON|RUNS_ON|HOSTED_ON|MEMBERS*1..5]->(ci) RETURN p
```

### Notes
- Results are capped at **200 rows** per query; ask the agent to filter or add `LIMIT`.
- Incidents and changes only have a blast radius if they link to a CI (export the `cmdb_ci` field and add an `AFFECTS` relationship).
- Treat passwords in saved flows like any other secret; rotate them if shared.

---

## REST API Tool & OAuth 2.0 *(New)*

Drag the **REST API** node into the Flow Builder to let an agent call any REST API. The node only shows the fields that match the selected **Auth Type**.

| Auth Type | Fields shown | Use for |
|---|---|---|
| `none` | — | Public APIs |
| `apikey` | API key, header name | `X-API-Key` style APIs |
| `bearer` | Bearer token | A static token |
| `basic` | `username:password` | Basic auth |
| `oauth2` | Token URL, Client ID, Client Secret, Scope, Audience, Client Auth | Machine-to-machine APIs (client credentials) |
| `oauth2_user` | Authorize URL, Token URL, Client ID, Client Secret (optional), Scope, Audience, **Connect** button | APIs that act as a signed-in user (Google, Microsoft, GitHub…) |

**Safety defaults**
- **Read-only** (GET/HEAD) unless you set *Allow write* to `true`.
- Requests are limited to the **base URL's host**; absolute URLs to other hosts, `..` in paths and redirects are not followed.
- Responses are cut at 12,000 characters. Secrets are masked in the UI and never sent to the model.

### OAuth 2.0 — client credentials (`oauth2`)
Fill in the token URL, client ID and secret (plus scope/audience if your provider needs them). AgentApps fetches a token, **caches it until shortly before it expires, refreshes it automatically, and retries once on a 401**. Client authentication can be sent in the request body or as HTTP Basic (*Client Auth* setting).

### OAuth 2.0 — user sign-in (`oauth2_user`)
For APIs where a person signs in and approves access (authorization code with **PKCE**):

1. Set Auth Type to `oauth2_user` and fill in the Authorize URL, Token URL, Client ID, optional Client Secret and Scope.
2. Register the **redirect URI** shown under the Connect button with your provider: `http(s)://<your-host>/auth/oauth-connect/callback`.
3. Click **Connect**, sign in in the popup. The node shows *Connected (auto-refresh on)*.
4. **Save the flow** (the connection id is saved with the node).

Notes:
- **One identity per node:** all users of the agent use the identity of whoever clicked Connect (like a service account).
- **Behind a domain or reverse proxy:** set `AGENTAPPS_PUBLIC_URL=https://your-domain` so the redirect URI is correct.
- **Refresh tokens:** some providers only issue one if asked. Google: add `access_type=offline&prompt=consent` to the Authorize URL. Microsoft: add `offline_access` to the scope. Without one you must reconnect when the token expires.
- **Storage:** tokens are encrypted on the server in `~/.agentapps/oauth_tokens.json` (key in `~/.agentapps/oauth.key`, owner-only). Disconnect removes them.
- Requires the `cryptography` package (installed with AgentApps).

### MCP Tool with OAuth
The **MCP Tool** node supports the same `oauth2` and `oauth2_user` options, including **Discover Tools**.

## Portal Connectors — Outlook / Microsoft 365 *(New)*

Drag the **Connector** node into a flow and pick a provider (currently **Microsoft 365 / Outlook**) to give an agent read (and optionally write) access to a tool that acts as the signed-in end user. Unlike the REST API node's `oauth2_user` mode — which is one shared identity for everyone running that flow — a Connector node is **per Portal user**: each person who chats with the agent authorizes their own Microsoft account, from inside the chat itself, and the agent only ever acts as them.

**Admin setup (one time):**
1. Register an app in Azure AD / Entra ID and add a redirect URI of `http(s)://<your-host>/auth/oauth-connect/callback` (the same callback used by the generic OAuth node; set `AGENTAPPS_PUBLIC_URL` if you're behind a domain or reverse proxy).
2. Set these environment variables before starting the server:
   - `AGENTAPPS_MS365_CLIENT_ID`
   - `AGENTAPPS_MS365_CLIENT_SECRET`
   - `AGENTAPPS_MS365_TENANT` (optional — defaults to `common`)
3. Restart the server. The Connector node and Portal's connectors panel will show Microsoft 365 as configured.

**What the end user sees:**
- A **cable icon** in the Portal header opens a Connectors panel listing every configured connector and whether *they personally* are connected.
- If an agent tries to use a connector the user hasn't linked yet, it says so and the chat renders an inline **Connect** button — clicking it opens the Microsoft sign-in popup right there, with no need to leave the conversation.
- Disconnecting only removes that one person's link; nobody else's connection is touched.

**Safety:**
- Each user's token is stored under a connection id derived from their username and the provider, so flows are never cached across users once a Connector node is present — two people running the same shared agent never see each other's mailbox.
- Connector tools default to **read-only**; check *Allow write* on the node to let the agent send mail, create events, etc. on the user's behalf.
- Tokens are encrypted at rest the same way as the generic OAuth node (`~/.agentapps/oauth_tokens.json`, key in `~/.agentapps/oauth.key`).

More providers (Google Workspace, Slack, etc.) can be added later by extending the same registry.

### Easiest connector to test: GitHub

Microsoft 365 needs an Azure AD app registration, which can take a while to set up. **GitHub is much faster to try end-to-end** — no tenant, no admin consent screen:

1. Go to [github.com/settings/developers](https://github.com/settings/developers) → **OAuth Apps** → **New OAuth App**.
2. Set the **Authorization callback URL** to `http(s)://<your-host>/auth/oauth-connect/callback` (e.g. `http://localhost:8000/auth/oauth-connect/callback` for local testing).
3. After creating it, copy the **Client ID** and generate a **Client secret**.
4. Set the env vars and restart:
   ```bash
   export AGENTAPPS_GITHUB_CLIENT_ID="your-client-id"
   export AGENTAPPS_GITHUB_CLIENT_SECRET="your-client-secret"
   ```
5. Drag a **Connector** node into a flow, set Provider to `github`, connect it to an agent, and save.
6. In the Portal, open the Connectors panel (cable icon) — GitHub should now show a **Connect** button. Click it, authorize on GitHub's own page, and the agent can now call `GET /user/repos`, read issues, etc. on your behalf.

### More connectors

The Connectors panel (cable icon in the Portal header) is a searchable popup, not a dropdown, so it scales as more providers are added. Currently available, each configured the same way — an env var pair, then a **Connect** button appears for everyone:

| Connector | Env vars | Where to register an app |
|---|---|---|
| Microsoft 365 (Outlook & OneDrive) | `AGENTAPPS_MS365_CLIENT_ID`, `AGENTAPPS_MS365_CLIENT_SECRET`, `AGENTAPPS_MS365_TENANT` | [Azure AD app registration](https://portal.azure.com) |
| GitHub | `AGENTAPPS_GITHUB_CLIENT_ID`, `AGENTAPPS_GITHUB_CLIENT_SECRET` | [github.com/settings/developers](https://github.com/settings/developers) |
| Slack | `AGENTAPPS_SLACK_CLIENT_ID`, `AGENTAPPS_SLACK_CLIENT_SECRET` | [api.slack.com/apps](https://api.slack.com/apps) |
| Google Workspace (Gmail, Drive, Calendar) | `AGENTAPPS_GOOGLE_CLIENT_ID`, `AGENTAPPS_GOOGLE_CLIENT_SECRET` | [Google Cloud Console](https://console.cloud.google.com/apis/credentials) |
| Notion | `AGENTAPPS_NOTION_CLIENT_ID`, `AGENTAPPS_NOTION_CLIENT_SECRET` | [notion.so/my-integrations](https://www.notion.so/my-integrations) (create a "public" integration) |
| HubSpot | `AGENTAPPS_HUBSPOT_CLIENT_ID`, `AGENTAPPS_HUBSPOT_CLIENT_SECRET` | [developers.hubspot.com](https://developers.hubspot.com/docs/api/working-with-oauth) |
| Jira & Confluence (Atlassian) | `AGENTAPPS_JIRA_CLIENT_ID`, `AGENTAPPS_JIRA_CLIENT_SECRET` | [developer.atlassian.com/console/myapps](https://developer.atlassian.com/console/myapps) (OAuth 2.0 (3LO) app) |
| ServiceNow | `AGENTAPPS_SERVICENOW_CLIENT_ID`, `AGENTAPPS_SERVICENOW_CLIENT_SECRET`, `AGENTAPPS_SERVICENOW_INSTANCE` (e.g. `mycompany` for `mycompany.service-now.com`) | System OAuth > Application Registry, inside your own ServiceNow instance |
| Glean | `AGENTAPPS_GLEAN_CLIENT_ID`, `AGENTAPPS_GLEAN_CLIENT_SECRET`, `AGENTAPPS_GLEAN_INSTANCE` (e.g. `mycompany` for `mycompany-be.glean.com`) | Glean admin console > API/OAuth clients |
| Zendesk | `AGENTAPPS_ZENDESK_CLIENT_ID`, `AGENTAPPS_ZENDESK_CLIENT_SECRET`, `AGENTAPPS_ZENDESK_SUBDOMAIN` (e.g. `mycompany` for `mycompany.zendesk.com`) | Admin Center > Apps and integrations > OAuth Clients |
| Salesforce | `AGENTAPPS_SALESFORCE_CLIENT_ID`, `AGENTAPPS_SALESFORCE_CLIENT_SECRET` | Setup > App Manager > New Connected App |

For every one of these, the redirect/callback URL to register is the same: `http(s)://<your-host>/auth/oauth-connect/callback`. ServiceNow, Glean and Zendesk are per-instance SaaS, so each also needs its own instance/subdomain env var set — the connector reports as "not configured" until every required env var for it is present, same rule as the rest.

Adding another provider later is a small, self-contained change: one entry in `_portal_connector_registry()` in `flow/server.py` (authorize/token URLs, scopes, API base, and the tool description the agent sees) — no UI changes needed, since the Connectors panel, the chat's inline `[CONNECT:key]` button, and the Builder's Connector node all read the registry dynamically.

#### Configuring connectors without environment variables

Setting env vars on the server isn't the only option. An **admin** (role `admin`) can instead open **Connector Settings** (the shield icon next to the Connectors popup, in both the classic and React portals) and type each provider's client ID/secret — and its instance/subdomain/tenant, for the providers that need one — directly into a settings screen. Nothing else needs to change:

- Settings saved this way are stored **encrypted at rest** (`~/.agentapps/connector_configs.json`, same Fernet key the OAuth token store uses), never in plain text, and are never echoed back by the API — only whether a secret is set.
- A setting saved here **takes priority** over the matching env var if both are present. Clearing it (the **Clear** button) reverts the connector to its env var, if one is set.
- Access is admin-only: the underlying `/admin/connector-configs` endpoints call the same `_require_admin()` check every other admin-only route uses.
- This is additive — env vars keep working exactly as before for anyone who prefers to configure connectors that way (e.g. via infra-as-code / secrets manager).

**Visibility in Tables (`/builder#tables`)**: a read-only system table, **`connector_registry`**, mirrors the status of all 11 connectors — provider, source (`admin_setting` / `env_var` / `unset`), client ID, whether a secret is set, and the extra field (instance/subdomain/tenant) where relevant. It follows the exact same pattern as the platform's other reserved tables (`user_registry`, `trigger_registry`, etc.): `system: true`, `readonly: true` (can't be deleted or hand-edited from the table UI), and it rebuilds itself whenever a connector setting is saved or cleared. **Client secrets are never written into it** — only a `has_client_secret` flag — same rule `user_registry` uses to keep password hashes out. If your SQL Server sync is configured (`--db-*` flags / `_db_get()`), this table syncs there too, like the others.

**Documentation tab**: Connector Settings has a second tab, **Documentation**, right next to Settings. It's a per-connector accordion with where to register an OAuth app for each provider (a direct link, or a note that it's configured inside the provider's own admin console for on-prem-style SaaS like ServiceNow/Glean/Zendesk/Salesforce), a short numbered setup checklist, and the actual **redirect URL** to paste into that provider's app registration — computed from your server's real host, with a one-click copy button. This content is defined once, server-side, in `_CONNECTOR_DOCS` in `flow/server.py`, and served from `/admin/connector-configs` alongside the settings data, so both UIs stay in sync automatically.

This is a good way to confirm the whole flow (node → admin env vars → Portal panel → inline chat Connect button) works on your setup before investing time in the Azure AD app registration for Microsoft 365.

### In Python
```python
from agentapps.tools import RestAPITool, MCPClientTool

# Machine-to-machine
api = RestAPITool(base_url="https://api.example.com", auth_type="oauth2",
                  token_url="https://login.example.com/oauth2/token",
                  client_id="...", client_secret="...", scope="read")

# MCP server behind OAuth
mcp = MCPClientTool(server_url="https://mcp.example.com", tool_name="search",
                    tool_description="Search", auth_type="oauth2",
                    token_url="https://login.example.com/oauth2/token",
                    client_id="...", client_secret="...")
```

---

## Running the tests

```bash
pip install pytest            # optional: pip install falkordblite (for the graph tests)
pytest tests -q
```

The suite uses a built-in mock OAuth provider (no internet needed) and a temporary home folder. It covers the REST API and MCP tools, OAuth sign-in and refresh, the encrypted token store, the server's Connect/callback endpoints and graph visualization. To smoke-test your own API, set the `AGENTAPPS_TEST_*` variables described in `tests/test_live_api.py`.

---

## HTTPS / SSL

Secure HTTPS is required for production webhooks.

### Option 1 — Auto self-signed certificate (easiest)
```bash
pip install cryptography
agentapps-flow --ssl-self-signed
```

### Option 2 — Bring your own certificate (Let's Encrypt / purchased)
```bash
agentapps-flow --ssl-cert /path/to/cert.pem --ssl-key /path/to/key.pem
```

### Option 3 — Let's Encrypt
```bash
pip install certbot
certbot certonly --standalone -d yourdomain.com

agentapps-flow \
  --ssl-cert /etc/letsencrypt/live/yourdomain.com/fullchain.pem \
  --ssl-key  /etc/letsencrypt/live/yourdomain.com/privkey.pem
```

### Option 3 — Standard HTTPS port (443)
```bash
agentapps-flow --port 443 --ssl-self-signed
```

> On Linux/macOS, binding to port 443 requires root or sudo. Consider using a reverse proxy (nginx, Caddy) for production.

### Using with ngrok (recommended for local webhooks)
```bash
# Terminal 1
agentapps-flow

# Terminal 2
ngrok http 7860
```

Use the `https://xxxx.ngrok-free.app` URL as your webhook base URL.

### Webhook URL format
```
https://your-domain.com/webhook/<project-name>?token=<bearer-token>
```

Tokens are generated in the Flow Builder under ☰ Menu → 🔗 Webhooks.

---

## All CLI Flags

| Flag | Default | Description |
|---|---|---|
| `--port` | `7860` | Port to listen on |
| `--host` | `0.0.0.0` | Host to bind to |
| `--no-browser` | off | Don't auto-open browser |
| `--reload` | off | Hot-reload on file changes (dev mode) |
| `--password` | — | Set UI login password |
| `--ssl-self-signed` | off | Auto-generate self-signed certificate |
| `--ssl-cert` | — | Path to SSL certificate `.pem` file |
| `--ssl-key` | — | Path to SSL private key `.pem` file |
| `--enable-shell` | off | Enable ShellTool |
| `--enable-browser` | off | Enable BrowserTool |

---

## Requirements

- Python >= 3.8
- An API key from OpenAI, Google Gemini, xAI Grok — or a local Ollama instance

---

## License

MIT License

---

## Contributing

Contributions welcome! Please feel free to submit a Pull Request on [GitHub](https://github.com/91Abdul/agentapps).

### Client secrets are encrypted at rest

OAuth client secrets of REST API and MCP nodes (and saved MCP servers) are encrypted when a flow is saved (`enc1:` values, Fernet key in `~/.agentapps/oauth.key`, the same key used for user tokens). They are decrypted only in memory when a token is requested.

- Existing flows with plain secrets keep working and are encrypted the next time they are saved.
- The key is machine-bound: a flow exported to another machine needs the secret re-entered there (a clear error says so).
- Back up `~/.agentapps/oauth.key` together with your projects.
- Needs the `cryptography` package; without it the flow is saved as before and a warning is printed.


## License keys are now signed, not secret-based

Older builds validated license keys (`AAFLOW-...`) against a secret string compiled
into the package. Any such secret can be read back out of a `.pyc` file, which meant
anyone could mint their own valid license. License keys are now `AAFLOW2-...`,
verified with an **Ed25519 public-key signature**: the package ships only the public
key (it can check a signature, not create one), so a valid key can only come from you.

- One-time setup: `python license_tools/gen_keypair.py`, then paste the printed
  public key into `_LICENSE_PUBLIC_KEY_B64` near the top of the license section in
  `flow/server.py`.
- Issue a key: `python license_tools/issue_license.py --email a@b.com --projects 25 --expiry 2027-12-31 --privkey "<your private key>"`.
- `license_tools/` is for you only -- it is excluded from `build_protected.py` and
  never ships in the pip package. Keep the private key out of git entirely (a
  password manager, not a file in the repo).
- Old `AAFLOW-...` keys you already issued keep working (read-only legacy path);
  issue all new keys with `AAFLOW2-...`.
- The local `license.json` file is still encrypted at rest, now derived from the
  machine ID alone -- that only obscures a leaked backup, it isn't what makes a
  license trustworthy. A tamper-evident checksum also catches a hand-edited file.

### What this does and doesn't protect against

Compiling source to `.pyc` (`build_protected.py`) only stops a casual look at your
code -- `.pyc` can be decompiled, and nothing in Python truly hides source from
someone who installs the package. Protecting a secret or a license *algorithm* the
way the old scheme tried to is fundamentally not possible this way; protecting who
can *mint a valid key* with a key pair, as above, is. A user can still patch out the
license check in their own copy once they're past login; this scheme stops someone
else from handing out fake keys to other people, which was the real exposure.

## React Portal (preview) — `/portal-next`

An optional React rebuild of the end-user Portal, served next to the existing one. `/portal` (HTML) is unchanged and remains the default.

- Looks the same: original CSS and markup are reused; the home screen renders pixel-identical to `/portal`.
- Covers chat (streaming steps, stop, attachments, sessions, agent lock, feedback, pins), approvals (overlay + detail), report viewer, execution panel, pinned cards, recent runs, "Build with AI" menu, layout editor and data security.
- **Switching:** the classic portal shows a **New UI** button; the React portal shows **Classic UI**. The choice is remembered per browser (`localStorage.agentapps_portal_ui`): once switched, `/portal` forwards to `/portal-next` until the user switches back (or opens `/portal?classic=1`). The button only appears when `flow/portal_ui` is present.
- **Sign-in page:** `/login` is now a React page in the same Google style (floating-label fields, show password, Caps Lock hint, light/dark, Microsoft SSO button when enabled). It still posts to `/auth/login`, so authentication, lockouts and rate limits are unchanged. The previous page remains at `/login?classic=1` and is used automatically if `flow/portal_ui/login.html` is missing.
- **Look:** the React portal uses a Google / Material 3 style (Google Sans + Roboto, Google blue, pill inputs, tonal surfaces, light and dark). The classic look is one switch away: open `/portal-next?classic=1` (and `?classic=0` to return). The theme lives in `portal-react/src/styles/google.css` and is scoped to `html.gx`, so the original CSS is untouched.
- Prebuilt files ship in `flow/portal_ui/` — no Node needed to run it.
- To change the UI: `cd portal-react && npm install && npm run build` (outputs to `flow/portal_ui`). `npm run dev` proxies to a server on port 7860.
- Overlay logic lives in `src/lib/legacy.ts` (copied from `portal.html` for identical behaviour); chat engine in `src/lib/chat.tsx`.
- The protected build (`build_protected.py`) ships only the built `flow/portal_ui`, not the React sources.
