# LightAgent

> LightAgent: Lightweight AI agent framework with memory, mcp & skill. Supports multi-agent collaboration, self-learning, and major LLMs (OpenAI/DeepSeek/Qwen). Open-source with MCP/SSE protocol integration.

- **Type:** MCP server
- **Install:** `agentstack add mcp-wanxingai-lightagent`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [wanxingai](https://agentstack.voostack.com/s/wanxingai)
- **Installs:** 0
- **Category:** [AI & ML](https://agentstack.voostack.com/c/ai-and-ml)
- **Latest version:** 0.1.0
- **License:** Apache-2.0
- **Upstream author:** [wanxingai](https://github.com/wanxingai)
- **Source:** https://github.com/wanxingai/LightAgent

## Install

```sh
agentstack add mcp-wanxingai-lightagent
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

English | 
    简体中文 | 
    繁體中文 | 
    Español | 
    Français | 
    Deutsch | 
    日本語 | 
    한국어 | 
    Português | 
    Русский 
  

  LightAgent🚀 – small footprint, big potential. 🌟(Open-source Agentic framework)

LightAgent is an ultra‑lightweight, open‑source framework that now natively supports Skills — letting you compose reusable capabilities with persistent memory, tool use, and tree‑of‑thought reasoning. It streamlines multi‑agent collaboration (build self‑learning agents in one step), connects to MCP over stdio and SSE, runs on any modern LLM (OpenAI, DeepSeek, Qwen, and more), and outputs OpenAI‑compatible streaming APIs for instant drop‑in with any chat interface. Small, modular, and skill‑ready — spin it up in five minutes.

---
## News
- **[2026-06-24]** LightAgent v0.9.0 Development: Adds checkpointed LightFlow workflows with resume/rerun support, approval nodes, richer step status and trace metadata, reusable Guardrails templates, stronger MemoryPolicy controls, and the first SharedMemoryPool prototype.
- **[2026-06-14]** LightAgent v0.8.1 Development: Adds MemoryScope metadata conventions, stricter MemoryPolicy provenance filters, and guidance for separating trace, user memory, self-reflection memory, and LightSwarm delegation state.
- **[2026-06-02]** LightAgent v0.8.0 Development: Adds initial LightFlow workflow orchestration for deterministic multi-step agent execution with DAG dependencies, step output passing, retries, and flow trace events.
- **[2026-05-29]** LightAgent v0.7.0 Development: Adds opt-in trace observability with structured run/model/tool/error events, `agent.export_trace()`, and prompt-safe model request summaries for production debugging.
- **[2026-05-28]** LightAgent v0.6.5 Released: Adds opt-in structured run results, structured streaming events, catchable LightAgent errors, and tool argument validation while keeping legacy `agent.run()` and `stream=True` behavior compatible.
- **[2026-05-27]** LightAgent v0.6.4 Released: Improves runtime tool dispatch reliability, adds structured error codes and troubleshooting guidance, expands OpenAI-compatible provider documentation for OpenRouter and local models, and updates browser-use integration examples.

Older release notes are available on [GitHub Releases](https://github.com/wanxingai/LightAgent/releases).

---

## ✨ Features

- **Lightweight and Efficient** 🚀: Minimalist design, quick deployment, suitable for various application scenarios. (No LangChain, No LlamaIndex) The core framework stays small, modular, and fully open source while using focused dependencies for provider, MCP, memory, and tracing integrations. 
- **Memory Support** 🧠: Supports custom long-term memory for each user, natively supporting the `mem0` memory module, automatically managing user personalized memory during conversations, making agents smarter.
- **Autonomous Learning** 📚️: Each agent possesses autonomous learning capabilities, and admins with permissions can manage each agent.
- **Tool Integration** 🛠️: Support for custom tools (`Tools`) and MCP tool integration, flexible expansion to meet diverse needs.  
- **Complex Goals** 🌳: Built-in Tree of Thought (`ToT`) module with reflection, supporting complex task decomposition and multi-step reasoning, enhancing task processing capabilities.  
- **Multi-Agent Collaboration** 🤖: Simpler to implement multi-agent collaboration than Swarm, with built-in LightSwarm for intent recognition and task delegation, enabling smarter handling of user input and delegating tasks to other agents as needed. 
- **Workflow Orchestration** 🔁: LightFlow chains agents into deterministic multi-step workflows with explicit dependencies, step output passing, retries, checkpointed run records, resume/rerun support, approval nodes, fallback agents, and traceable execution.
- **Shared Memory Prototype** 🧠: SharedMemoryPool provides append-first in-memory shared memory with provenance metadata, scoped retrieval, and MemoryPolicy-compatible results for multi-agent experiments.
- **Independent Execution** 🤖: Tasks and tool calls are completed autonomously without human intervention.  
- **Multi-Model Support** 🔄: Compatible with OpenAI-style providers such as OpenAI, OpenRouter, Zhipu ChatGLM, Baichuan, StepFun, DeepSeek, Qwen, vLLM, llama.cpp, and other OpenAI-compatible endpoints.  
- **Streaming API** 🌊: Supports OpenAI streaming format API service output, seamlessly integrates with mainstream chat frameworks, enhancing user experience.  
- **Trace Observability** 🔎: Opt-in `trace=True` run traces record structured run lifecycle, model request summaries, tool calls, tool results, and errors without changing the default string return value.  
- **Guardrails Templates** 🛡️: Reusable input/tool/output guardrail templates help block private data, require confirmation for sensitive tools, validate high-risk parameters, and redact sensitive output.
- **Tool Generator** 🚀: Just provide your API documentation to the [Tool Generator], which will automatically create exclusive tools for you, allowing you to quickly build hundreds of personalized custom tools in just 1 hour to improve efficiency and unleash your creative potential.
- **Agent Self-Learning** 🧠️: Each agent has its own scene memory capabilities and the ability to self-learn from user conversations.
- **Adaptive Tool Mechanism** 🛠️: Supports adding an unlimited number of tools, allowing the large model to first select a candidate tool set from thousands of tools, filtering irrelevant tools before submitting context to the large model, significantly reducing token consumption.

## 🧭 Architecture At A Glance

| Layer | Main API | Use it when you need |
| --- | --- | --- |
| Single agent runtime | `LightAgent` | One agent with model calls, tools, memory, streaming, trace, and guardrails. |
| Multi-agent routing | `LightSwarm` | Role-based delegation across specialized agents. |
| Deterministic workflow | `LightFlow` | Ordered DAG workflows, retries, checkpoints, approvals, resume, and rerun. |
| Tools and integrations | `tools`, `ToolRegistry`, MCP | Python tools, generated tools, runtime tool loading, or MCP tool servers. |
| Memory boundary | `MemoryPolicy`, `MemoryScope` | Tenant isolation, provenance, trust, expiration, and write admission controls. |
| Shared memory prototype | `SharedMemoryPool` | In-memory shared memory experiments across agents. |
| Safety controls | `input_guardrails`, `tool_guardrails`, `output_guardrails` | Privacy blocking, sensitive tool confirmation, high-risk parameter checks, and output redaction. |
| Observability | `trace=True`, `agent.export_trace()` | Structured run, model, tool, error, and workflow trace events. |

## Core Usage Patterns

LightAgent keeps the default call path simple while allowing production controls to be added incrementally.

| Pattern | Minimal call | Notes |
| --- | --- | --- |
| Basic response | `agent.run(query)` | Returns a string by default. |
| Streaming | `agent.run(query, stream=True)` | Returns OpenAI-compatible streaming chunks. |
| Structured result | `agent.run(query, result_format="object")` | Returns content plus structured metadata. |
| Trace | `agent.run(query, trace=True)` | Records events without changing the default string return. |
| User memory | `agent.run(query, user_id="alice")` | Uses the configured memory backend and memory policy. |
| Tools | `LightAgent(..., tools=[fn])` | Functions should expose `tool_info` metadata. |
| Guardrails | `LightAgent(..., input_guardrails=[...])` | Add input, tool, and output policies per agent. |
| Workflow | `LightFlow().step(...).run(query)` | Use for deterministic multi-step execution. |

## 🧩 Multi-agent troubleshooting (failure map)

If you are using LightSwarm or other multi-agent patterns and start seeing role drift, cross-agent memory issues or confusing logs, you can check the
[Multi-agent failure map](docs/multi_agent_failure_map.md) for a small symptom → mode → debug checklist.  
This page is docs-only and does not change any framework code.

## 📋 FAQ

For common installation, model provider, tool, memory, MCP, Skills, streaming, and LightSwarm questions, see [FAQ](docs/FAQ.md).

For deterministic multi-step workflows, checkpointed run records, resume/rerun, approval nodes, fallback agents, and step status tracking, see [LightFlow](docs/lightflow.md).

For custom tool creation, runtime tools, ToolRegistry, ToolLoader, AsyncToolDispatcher, and MCP tool integration, see [Tools Guide](docs/tools.md).

For shared long-term memory or graph memory deployments, review the [Memory Security Guidance](docs/memory_security.md).

For lightweight shared memory experiments, see [SharedMemoryPool](docs/shared_memory_pool.md).

For memory write admission, expiration-aware retrieval, and low-quality memory write blocking, see [Memory Admission And Mutation Controls](docs/memory_admission.md).

For separating trace, user memory, self-reflection memory, and LightSwarm delegation state, see [Memory, Trace, And Swarm Boundaries](docs/memory_trace_swarm_boundaries.md).

For input, tool, and output safety policies, see [Guardrails](docs/guardrails.md).

For OpenRouter, local LLM, and OpenAI-compatible provider setup, see [Model Provider Configuration](docs/model_providers.md).

For structured error codes and troubleshooting hints, see [Error Handling](docs/error_handling.md).

For v0.7.0 trace observability, see [Trace Observability](docs/tracing.md).

For browser-use integration with recent `browser-use` versions, see [browser-use Integration](docs/browser_use.md).

---

## 🚧 Coming Soon

- **Agent Collaborative Communication** 🛠️: Agents can also share information and transmit messages, achieving complex information communication and task collaboration.
- **Agent Assessment** 📊: Built-in agent assessment tool for conveniently evaluating and optimizing the agents you build, aligning with business scenarios, and continuously improving intelligence levels.  

---
## 🌟 Why Choose LightAgent?

- **Open Source and Free** 💖: Fully open source, community-driven, continuously updated, contributions are welcome!  
- **Easy to Get Started** 🎯: Detailed documentation, rich examples, quick to get started, easy integration into your project.  
- **Community Support** 👥: An active developer community ready to assist and provide answers at any time.  
- **High Performance** ⚡: Optimized design, efficient operation, meeting high concurrency requirements.  

---

## 🛠️ Quick Start

### Install the latest version of LightAgent

```bash
pip install lightagent
```

(Optional installation) Install the Mem0 package via pip:

```bash
pip install mem0ai
```

Alternatively, you can use Mem0 on a hosted platform by clicking [here](https://www.mem0.ai/).

### Hello World Example Code

```python
from LightAgent import LightAgent

# Initialize Agent
agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

# Run Agent
response = agent.run("Hello, who are you?")
print(response)
```

### Inspect a Run Trace (v0.7.0)

Tracing is opt-in and keeps the default `agent.run()` behavior backward compatible.

```python
from LightAgent import LightAgent

agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

result = agent.run("Hello, who are you?", result_format="object", trace=True)
print(result.content)
print(result.trace_id)
print(result.trace)

for event in agent.export_trace():
    print(event["type"], event["data"])
```

### Checkpoint a LightFlow Run (v0.9.0)

`LightFlow` can persist workflow checkpoints and resume failed runs without
starting from the first step again.

```python
from LightAgent import JsonLightFlowStore, LightAgent, LightFlow

research_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")
writer_agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url")

store = JsonLightFlowStore(".lightflow_runs")
flow = (
    LightFlow(store=store)
    .step("research", agent=research_agent, timeout=30)
    .step("write", agent=writer_agent, depends_on=["research"], max_retry=2)
)

result = flow.run("Analyze this company", run_id="report-001", trace=True)

if not result.success:
    result = flow.resume("report-001")

print(result.status)
print(flow.get_run("report-001")["steps"])
```

### Use SharedMemoryPool (v0.9.0)

`SharedMemoryPool` is a lightweight in-memory prototype for multi-agent shared
memory experiments.

```python
from LightAgent import LightAgent, MemoryPolicy, SharedMemoryPool

shared_memory = SharedMemoryPool(agent_name="writer")

agent = LightAgent(
    name="writer",
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=shared_memory,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allow_unattributed_results=False,
        allowed_sources=("user",),
        allowed_scopes=("user",),
    ),
)

agent.run("Remember that I prefer concise reports.", user_id="alice")
print(shared_memory.list_records(user_id="tenant-a:alice"))
```

### Set Model Self-Perception via System Prompt

```python
from LightAgent import LightAgent

# Initialize Agent
agent = LightAgent(
     role="Please remember that you are LightAgent, a useful assistant that helps users use multiple tools.",  # system role description
     model="gpt-4.1",  # Supported models: openai, chatglm, deepseek, qwen, etc.
     api_key="your_api_key",  # Replace with your large model provider API Key
     base_url="your_base_url",  # Replace with your large model provider api url
 )
# Run Agent
response = agent.run("Who are you?")
print(response)
```

### Tool Example Code

```python
from LightAgent import LightAgent

# Define Tool
def get_weather(city_name: str) -> str:
    """
    Get the current weather for `city_name`
    """
    return f"Query result: {city_name} is sunny."
# Define tool information inside the function
get_weather.tool_info = {
    "tool_name": "get_weather",
    "tool_description": "Get current weather information for the specified city.",
    "tool_params": [
        {"name": "city_name", "description": "The name of the city to query", "type": "string", "required": True},
    ]
}

tools = [get_weather]

# Initialize Agent
agent = LightAgent(model="gpt-4.1", api_key="your_api_key", base_url="your_base_url", tools=tools)

# Run Agent
response = agent.run("Please check the weather in Shanghai.")
print(response)
```
Supports an unlimited number of customizable tools.

Multiple tool examples: tools = [search_news, get_weather, get_stock_realtime_data, get_stock_kline_data]

---

## Function Details

README keeps the core usage model in one place. Longer examples, adapter-specific setup, and production guidance live in the dedicated docs pages.

### 1. Detachable Memory Module (`mem0`)
LightAgent accepts any memory backend that provides `store(data, user_id)` and `retrieve(query, user_id)`. This keeps memory detachable: you can start with a simple custom class, use `mem0`, or plug in a vector/graph memory adapter without changing agent code.

Use `user_id` to isolate conversations, and use `MemoryPolicy` when memory is shared across users, tenants, agents, or traces.

```python
from LightAgent import LightAgent, MemoryPolicy

agent = LightAgent(
    model="gpt-4.1",
    api_key="your_api_key",
    base_url="your_base_url",
    memory=your_memory_backend,
    memory_policy=MemoryPolicy(
        namespace="tenant-a",
        allowed_sources=("user", "reflection"),
        allowed_scopes=("user", "agent"),
        reject_duplicate_writes=True,
        min_write_length=8,
    ),
)

response = agent.run("Remember that I prefer concise reports.", user_id="alice")
```

See [Memory Security Guidance](docs/memory_security.md), [Memory Admission And Mutation Controls](docs/memory_admission.md), and [Memory, Trace, And Swarm Boundaries](docs/memory_trace_swarm_boundaries.md).

### 2. Tool Integration
Use

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [wanxingai](https://github.com/wanxingai)
- **Source:** [wanxingai/LightAgent](https://github.com/wanxingai/LightAgent)
- **License:** Apache-2.0

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-wanxingai-lightagent
- Seller: https://agentstack.voostack.com/s/wanxingai
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
